Initialize optimizer research workspace with official baselines and history-free coverage

Vendor pinned MeZO, AGZO, LOZO and LoREN sources with independent environments. Add direct in-place fix/adjust/node training, derived history-free basis gradients, development-best checkpoints and experiment tooling. Keep models, datasets, caches and credentials outside Git.

Validation: 93 project tests passed; 521 vendored author files verified.
This commit is contained in:
gloamxun committed 2026-11-12 23:32:33 +08:00
commit e0feabec8f
596 files changed
+87356

No files matched your search

+1
View File
@@ -0,0 +1 @@
3.11.15
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2025 Hyunseok Seung
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+103
View File
@@ -0,0 +1,103 @@
# Low-Rank Curvature for Zeroth-Order Optimization in LLM Fine-Tuning
This repository provides the official implementation of **LOREN**, a curvature-aware zeroth-order (ZO) optimization
method for efficient fine-tuning of LLMs. LOREN adaptively learns a **low-rank curvature preconditioner** and integrates
it with REINFORCE leave-one-out (RLOO) estimator to **reduce variance**, achieving superior convergence, accuracy, and memory efficiency compared to existing ZO methods.
> Accepted at **AAAI Conference on Artificial Intelligence (AAAI-26)**, Singapore, January 2026.
---
## Overview
LOREN reformulates preconditioned ZO optimization as *learning an anisotropic perturbation distribution* that captures
local curvature. It combines:
- **Rank-1 block-diagonal preconditioning** to encode curvature efficiently.
- **RLOO variance reduction** to stabilize and denoise gradient estimates.
### Benchmark Results
<p align="center">
<img src="figures/gpt_qnli_acc.png" alt="GPT-2-XL QNLI" width="49.5%"/>
<img src="figures/opt13_cb_acc.png" alt="OPT-13B BoolQ" width="48%"/>
</p>
<p align="center">
Figure 1: Test accuracy curves for GPT-2-XL fine-tuned on QNLI and OPT-13B fine-tuned on CB, using early stopping.
</p>
<p align="center">
<img src="figures/opt13b_train_loss.png" alt="OPT13B" width="98%"/>
</p>
<p align="center">
Figure 2: Training loss curves for different ZO optimizers when fine-tuning OPT-13B on SuperGLUE tasks.
</p>
---
## Models
| Family | Model |
|:-----------|:--|
| DistilBERT | `distilbert-base-cased` |
| RoBERTa | `roberta-large` |
| GPT | `gpt2-xl` |
| OPT | `facebook/opt-2.7b`, `facebook/opt-13b` |
| LLaMA | `meta-llama/Meta-Llama-3-8B` |
## Tasks
**GLUE:** `mnli`, `qnli`, `sst2`, `cola`
**SuperGLUE:** `rte`, `boolq`, `wic`, `cb`
## Algorithms
| Algorithm | Description | Reference |
|:--------------|:----------------------------------------------------|:-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `ZO` | Baseline memory-efficient ZO | [Malladi et al., 2023, *Fine-Tuning Language Models with Just Forward Passes*](https://proceedings.neurips.cc/paper_files/paper/2023/file/a627810151be4d13f907ac898ff7e948-Paper-Conference.pdf) |
| `ZOAdam` | MeZO with Adam's adaptive update | |
| `ZOSVRG` | MeZO with stochastic variance-reduced gradients | [Gautam et al., 2024, *Variance-reduced Zeroth-Order Methods for Fine-Tuning Language Models*](https://openreview.net/pdf?id=yc758jO4i5) |
| `LOZO` | Low-rank ZO gradient | [Chen et al., 2025, *Enhancing Zeroth-Order Fine-Tuning for Language Models with Low-Rank Structures*](https://openreview.net/pdf?id=9BiVepgmWW) |
| `HiZOO` | Hessian informed ZO | [Zhao et al., 2025, *Second-Order Fine-Tuning without Pain for LLMs: A Hessian Informed Zeroth-Order Optimizer*](https://openreview.net/forum?id=bEqI61iBue) |
| `LOREN`(ours) | Low-rank curvature-aware ZO with variance reduction | Seung et al., 2026, *Low-Rank Curvature for Zeroth-Order Optimization in LLM Fine-Tuning* |
---
## How to Run
Fine-tune a model with a chosen algorithm:
``` shell
python main.py\
--epochs $epochs \
--model_name $model \
--task $task \
--algorithm $algorithm \
--lr $lr \
--weight_decay 0.0 \
--num_queries $num_queries \ # Default: 2 (MeZO, LOZO, MeZO-Adam), 3 (MeZO-SVRG, HiZOO)
--perturbation_scale 1e-3 \
--lr_mezosvrg_mb 1e-6 --q 2 --anneal 5 \ # MeZO-SVRG
--eps 1e-8 \ # MeZO-Adam
--rank 2 --step_interval 50 \ # LOZO
--hessian_smooth_type constant1e-8 \ # HiZOO
--lr_cov 1e-3 --damping 0.1 \ # LOREN
--samplesize 512 --samplesize_validation 256 \
--batchsize $bsz \
--batchsize_limit $bsz_lim \
--full_parameter \
--max_seq_length 128 \
--device 0 --save_every 10000000 --logging csv \
--init_seed 42 --trial $trial \
--early_stopping --patience 1000
```
---
## Citation
```
@inproceedings{seung2026lowrank,
title={Low-Rank Curvature for Zeroth-Order Optimization in LLM Fine-tuning},
author={Seung, Hyunseok and Lee, Jaewoo and Ko, Hyunsuk},
booktitle={The Fortieth AAAI Conference on Artificial Intelligence},
year={2026},
}
```
+81
View File
@@ -0,0 +1,81 @@
# LOREN:独立环境、入口与排障
官方来源:https://github.com/hseung88/loren.git;锁定提交:`b80a32bc394332d1a1f115f41dfb5dcf7b326d37`。
官方文件保留原样;此目录新增 pyproject.toml、uv.lock、native.py、run_compatible.py 和本文。
原仓库 Git 历史存放在被忽略的 `.upstream-git/`,防止主项目意外把整个目录当成 gitlink。
查看上游版本:`git --git-dir=.upstream-git --work-tree=. rev-parse HEAD`。
不要在这个目录执行普通 git commit/push;主项目尚未提交。
## 安装与版本
在 WSL 中执行(不需要激活根目录环境):
```bash
cd ~/experiments_codebase
source scripts/env.sh
cd baselines/loren
uv sync --locked
uv run --locked python native.py --help
```
此目录 `.venv` 独立,Python 3.11,torch 2.13.0,原生 Transformers 4.44.2。
直接依赖精确版本写在 pyproject.toml,全部间接依赖和 wheel 哈希写在 uv.lock。
`uv sync --locked` 默认 native;`uv sync --locked --no-default-groups --group modern` 切换到 Transformers 4.57.1。
两组互斥,使用同一个本库 `.venv`,不会激活其他方法的环境。不要使用 `uv pip install -U` 绕开锁。
## 官方入口及命令
原入口 `main.py`。本地资源包装入口 `native.py` 仅设置共享路径、提供本地 Dataset 和启动参数,然后运行原始程序。
`--asset-model`、`--asset-task`、`--asset-out` 是包装参数,其余参数透传官方入口;以 `--help` 为准。
MeZO/LOZO/AGZO包装器默认固定 train_set_seed=42,并将result_file显式指向共享输出;否则原版会因num_dev配合空采样seed触发断言,或因相对result目录缺失在训练完成后报错。用户后置同名参数可覆盖这些默认值。
```bash
uv run --locked python native.py --asset-model facebook/opt-1.3b --asset-task sst2 --epochs 1 --samplesize 4 --samplesize_validation 4 --batchsize 2 --batchsize_limit 2 --lr 1e-6 --num_queries 2 --perturbation_scale 1e-3 --damping 0.1 --lr_cov 1e-3 --weight_decay 0 --max_seq_length 64 --logging csv --init_seed 42
```
调参请使用官方参数:学习率 `--lr`,差分半径 `--perturbation_scale`,batch `--batchsize`。
参数覆盖:MeZO/LOZO/AGZO 默认 full(不传 LoRA/prefix/head-only 开关);LOREN 包装器显式传 `--full_parameter`。
全参数覆盖不等于无结构全维搜索;LOZO/AGZO 仍使用结构化扰动。
## Qwen3 / DROP 与统一比较入口
```bash
uv run --locked --no-default-groups --group modern python run_compatible.py --model Qwen/Qwen3-0.6B --task sst2 --budget 12 --train-samples 16 --dev-samples 4 --eval-samples 4 --batch-size 2 --eval-batch-size 2 --calibration-samples 2 --no-save-checkpoint
# DROP:将 --task 改为 drop,并合理增加 --max-length(短冒烟可以先用128)。
```
兼容层 `../../src/experiments_codebase/official.py` 从本库源码编译官方数值函数;不导入旧 Trainer,也不另写一套公式。
通用数据协议和计账在 `../../src/experiments_codebase/task.py`、`runner.py`。
此入口统一 SST2 为两 verbalizer 的交叉熵、DROP 为答案 token 的 teacher-forced CE;它与部分官方任务目标不同,日志会标记 task adapter。
预算为总 main forward,而非更新步数;检测和基提取前向不免费。评估前向另列。
不支持从兼容检查点续训;可用 `--action evaluate --checkpoint ...` 或 `--action generate --checkpoint ... --prompt ...` 推理。
## 核心位置
- 核心算法:`model/glue_transformer_loren.py: configure_params / perturb_parameters / lnes_zo_update`。
- 模型/数据:`model/glue_transformer.py; dataset/glue.py; trainer/`。
- 官方超参数原型:入口中的参数 dataclass/parser 与原始 shell 脚本;与本站兼容入口参数不是同一命名空间。
## 系统组件与常见问题
原生任务是 GLUE/SuperGLUE;模型分支没有 Qwen,任务分支没有 DROP。原生入口不支持这两个扩展。modern 兼容入口可把同一官方数值核用于 Qwen/DROP,但不是作者端到端任务复现。原生使用分类模型/新分类头,兼容入口使用因果模型 verbalizer,两者成绩不能直接混为同一协议。
WSL 必须能看到 NVIDIA 驱动:先运行 `nvidia-smi`。RTX 5070 Ti 是 Blackwell;原论文旧版 torch/CUDA wheel 不支持其架构。
本机选用支持当前显卡的 torch 2.13.0,不声称完全复刻论文年代的二进制环境。
CUDA runtime 随 wheel 安装,普通运行无需 nvcc;自编译第三方扩展才需要 CUDA toolkit、gcc/g++、make、Python headers。
Fedora 常见系统依赖:`git curl ca-certificates libgomp libstdc++`;缺库先用 `ldd` 核查,不要盲目替换驱动。
uv 会下载 Python 3.11,不依赖系统 Python 3.14;保持 `.python-version`。
如果 WSL 解析到 198.18.* 且直连超时,可在未跟踪的根 `.env` 配置你现有代理,再 `source ../../scripts/env.sh`;不要把代理/token 写入源码。
本次用临时 HTTP(S)_PROXY 沿用主机代理;未修改系统网络配置。
`huggingface-hub` 不能随意升到2.x:Transformers 4.x 需要 <1.0。已锁0.36.0。
新版setuptools移除了pkg_resources,旧Trainer/accelerate仍导入它;锁80.9.0同时满足torch要求的>=77.0.3。LOREN官方requirements漏列loguru,本环境已补0.7.3。
旧 datasets/pyarrow/numpy 有 ABI 约束,三者必须遵守 uv.lock;不能拿现代 `.venv` 的 site-packages 混入原生环境。
共享DROP不能用datasets5.x的List元数据序列化后直接给2.x/3.x读;请在根锁定环境datasets3.6执行prepare_assets,工具可从原始parquet重建不兼容资产。
E盘必须真实挂载。Assets默认位于 `/mnt/e/Experiments/Assets`,包装器在写入前检查 mountpoint。
模型和数据只从本地共享目录读取;资产缺失先在根环境运行 `scripts/prepare_assets.py --download-missing`。
Qwen的词表较大,长序列或大 batch 会增显存;先减batch/长度,不要把OOM归因于优化算法。
## 验证状态
以根目录 `reports/validation_report.json` 和 `reports/validation.log` 为准,区分安装、导入、短步训练、模型任务矩阵。
`--help` 通过不代表训练通过,短步通过也不代表论文精度复现。未完成项目会明确记录。
+4
View File
@@ -0,0 +1,4 @@
from .logging import get_logger
__all__ = ['get_logger']
+73
View File
@@ -0,0 +1,73 @@
import math
import torch
@torch.no_grad()
def generate_basis(m, rank, ref_mat, orthogonal=False):
Z = torch.randn(m, rank, dtype=ref_mat.dtype, device=ref_mat.device)
if orthogonal is True:
U, S, Vt = torch.linalg.svd(Z.T @ Z)
S = 1. / torch.sqrt(S)
return (Z @ U @ torch.diag(S) @ Vt) * math.sqrt(rank)
else:
return Z
@torch.no_grad()
def sgd_with_wdecay(param, grad, lr, weight_decay):
param.mul_(1 - lr * weight_decay)
param.add_(grad, alpha=-lr)
@torch.no_grad()
def ema_update(param, grad, lr, weight_decay, beta):
updated_param = param.mul(1 - lr * weight_decay)
updated_param.add_(grad, alpha=-lr)
param.mul_(beta).add_(updated_param, alpha=1.0 - beta)
def exponential_cooling_schedule(initial_temp, alpha, iteration):
"""
Exponential cooling schedule function for simulated annealing.
Parameters:
initial_temp (float): The initial temperature.
alpha (float): The cooling rate (0 < alpha < 1).
iteration (int): The current iteration number.
Returns:
float: The temperature at the given iteration.
"""
return initial_temp * (alpha ** iteration)
def logarithmic_cooling_schedule(initial_temp, iteration):
"""
Logarithmic cooling schedule function for simulated annealing.
Parameters:
initial_temp (float): The initial temperature.
iteration (int): The current iteration number.
Returns:
float: The temperature at the given iteration.
"""
return initial_temp / (1 + math.log(1 + iteration))
def linear_cooling_schedule(initial_temp, final_temp, max_iterations, iteration):
"""
Linear cooling schedule function for simulated annealing.
Parameters:
initial_temp (float): The initial temperature.
final_temp (float): The final temperature.
max_iterations (int): The maximum number of iterations.
iteration (int): The current iteration number.
Returns:
float: The temperature at the given iteration.
"""
return initial_temp - (initial_temp - final_temp) * (iteration / max_iterations)
@@ -0,0 +1,208 @@
import math
import warnings
from functools import partial
from typing import Callable, Iterable, Optional, Tuple, Union
import torch
from torch import nn
# from torch.optim import Optimizer
# from torch.optim.lr_scheduler import LambdaLR, ReduceLROnPlateau
from transformers.utils import logging
from transformers.utils.versions import require_version
logger = logging.get_logger(__name__)
def get_reduce_on_plateau_schedule(learning_rate, name, num_warmup_steps, num_decay_steps, current_step,
num_training_steps):
# to be updated
return learning_rate
def _get_inverse_sqrt_schedule_lr_lambda(current_step: int, *, num_warmup_steps: int, timescale: int = None):
if current_step < num_warmup_steps:
return float(current_step) / float(max(1, num_warmup_steps))
shift = timescale - num_warmup_steps
decay = 1.0 / math.sqrt((current_step + shift) / timescale)
return decay
def get_inverse_sqrt_schedule(learning_rate, name, num_warmup_steps, num_decay_steps, current_step, num_training_steps):
# to be updated
return learning_rate
def get_constant_schedule_with_warmup(learning_rate, name, num_warmup_steps, num_decay_steps, current_step,
num_training_steps):
if current_step < num_warmup_steps:
return float(current_step) / float(max(1.0, num_warmup_steps)) * learning_rate
return learning_rate
def get_linear_schedule_with_warmup(learning_rate, name, num_warmup_steps, num_decay_steps, current_step,
num_training_steps):
if current_step < num_warmup_steps:
return float(current_step) / float(max(1, num_warmup_steps)) * learning_rate
return max(0.0, float(num_training_steps - current_step) / float(
max(1, num_training_steps - num_warmup_steps))) * learning_rate
def get_cosine_schedule_with_warmup(learning_rate, name, num_warmup_steps, num_decay_steps, current_step,
num_training_steps):
num_cycles = 2
if current_step < num_warmup_steps:
return float(current_step) / float(max(1, num_warmup_steps)) * learning_rate
progress = float(current_step - num_warmup_steps) / float(max(1, num_training_steps - num_warmup_steps))
return max(0.0, 0.5 * (1.0 + math.cos(math.pi * float(num_cycles) * 2.0 * progress))) * learning_rate
def get_cosine_with_hard_restarts_schedule_with_warmup(learning_rate, name, num_warmup_steps, num_decay_steps,
current_step, num_training_steps):
num_cycles = 2
if current_step < num_warmup_steps:
return float(current_step) / float(max(1, num_warmup_steps)) * learning_rate
progress = float(current_step - num_warmup_steps) / float(max(1, num_training_steps - num_warmup_steps))
if progress >= 1.0:
return 0.0 * learning_rate
return max(0.0, 0.5 * (1.0 + math.cos(math.pi * ((float(num_cycles) * progress) % 1.0)))) * learning_rate
def get_polynomial_decay_schedule_with_warmup(learning_rate, name, num_warmup_steps, num_decay_steps, current_step,
num_training_steps):
lr_init = learning_rate
lr_end = 1e-10
power = 3
if current_step < num_warmup_steps:
return float(current_step) / float(max(1, num_warmup_steps)) * learning_rate
elif current_step > num_training_steps:
return lr_end / lr_init * learning_rate # as LambdaLR multiplies by lr_init
else:
lr_range = lr_init - lr_end
decay_steps = num_training_steps - num_warmup_steps
pct_remaining = 1 - (current_step - num_warmup_steps) / decay_steps
decay = lr_range * pct_remaining ** power + lr_end
return decay / lr_init * learning_rate # as LambdaLR multiplies by lr_init
def get_polynomial_decay_schedule(learning_rate, name, num_warmup_steps, num_decay_steps, current_step,
num_training_steps):
lr_init = learning_rate
lr_end = 1e-10
power = 3
if current_step > num_training_steps:
return lr_end / lr_init * learning_rate # as LambdaLR multiplies by lr_init
else:
lr_range = lr_init - lr_end
decay_steps = num_training_steps - 0
pct_remaining = 1 - (current_step - 0) / decay_steps
decay = lr_range * pct_remaining ** power + lr_end
return decay / lr_init * learning_rate # as LambdaLR multiplies by lr_init
def get_constant_polynomial_decay_schedule(learning_rate, name, num_warmup_steps, num_decay_steps, current_step,
num_training_steps):
lr_init = learning_rate
lr_end = 1e-10
power = 3
if current_step < num_decay_steps:
return learning_rate
elif current_step > num_training_steps:
return lr_end / lr_init * learning_rate # as LambdaLR multiplies by lr_init
else:
lr_range = lr_init - lr_end
decay_steps = num_training_steps - num_decay_steps
pct_remaining = 1 - (current_step - num_decay_steps) / decay_steps
decay = lr_range * pct_remaining ** power + lr_end
return decay / lr_init * learning_rate / 100 # as LambdaLR multiplies by lr_init
def get_constant_decay1_schedule(current_step, num_training_steps):
if current_step < 9800:
return 1e-6
else:
return 1e-8
def get_constant6_schedule(current_step, num_training_steps):
return 1e-6
def get_constant8_schedule(current_step, num_training_steps):
return 1e-8
def get_constant10_schedule(current_step, num_training_steps):
return 1e-10
def get_constant12_schedule(current_step, num_training_steps):
return 1e-12
def get_constant4_schedule(current_step, num_training_steps):
return 1e-4
def get_constant2_schedule(current_step, num_training_steps):
return 1e-2
def get_constant0_schedule(current_step, num_training_steps):
return 0
def get_constant_schedule_with_warmup(current_step, num_training_steps):
if current_step < num_warmup_steps:
return float(current_step) / float(max(1.0, num_warmup_steps)) * 1e-6
return 0
def get_constant_polynomial_decay_schedule_with_warmup(learning_rate, name, num_warmup_steps, num_decay_steps,
current_step, num_training_steps):
lr_init = learning_rate
lr_end = 1e-7
power = 3
if current_step < num_warmup_steps:
return float(current_step) / float(max(1, num_warmup_steps)) * learning_rate
elif current_step >= num_warmup_steps and current_step < num_decay_steps:
return learning_rate
elif current_step > num_training_steps:
return lr_end / lr_init * learning_rate # as LambdaLR multiplies by lr_init
else:
lr_range = lr_init - lr_end
decay_steps = num_training_steps - num_decay_steps
pct_remaining = 1 - (current_step - num_decay_steps) / decay_steps
decay = lr_range * pct_remaining ** power + lr_end
return decay / lr_init * learning_rate # as LambdaLR multiplies by lr_init
TYPE_TO_SCHEDULER_FUNCTION = {
'linear_with_warmup': get_linear_schedule_with_warmup,
'cosine_with_warmup': get_cosine_schedule_with_warmup,
'cosine_with_hard_restarts_with_warmup': get_cosine_with_hard_restarts_schedule_with_warmup,
'polynomial_decay_with_warmup': get_polynomial_decay_schedule_with_warmup,
'inverse_sqrt': get_inverse_sqrt_schedule,
'reduce_on_plateau': get_reduce_on_plateau_schedule,
'constant_polynomial_decay': get_constant_polynomial_decay_schedule,
'constant_polynomial_decay_with_warmup': get_constant_polynomial_decay_schedule_with_warmup,
'polynomial_decay': get_polynomial_decay_schedule,
'constant0': get_constant0_schedule,
'constant1e-6': get_constant6_schedule,
'constant1e-8': get_constant8_schedule,
'constant1e-10': get_constant10_schedule,
'constant1e-12': get_constant12_schedule,
'constant1e-2': get_constant2_schedule,
'constant1e-4': get_constant4_schedule,
'constant_with_warmup': get_constant_schedule_with_warmup,
'constant_decay1': get_constant_decay1_schedule,
}
def Hessian_smooth_scheduler(Hessian_smooth_type, current_step, num_training_steps):
schedule_func = TYPE_TO_SCHEDULER_FUNCTION[Hessian_smooth_type]
return schedule_func(current_step, num_training_steps)
+39
View File
@@ -0,0 +1,39 @@
import sys
from loguru import logger
__all__ = ["get_logger"]
logger_sink = {}
LOG_FORMAT = (
"[<green>{time:MM-DD HH:mm:ss}</green>] "
# "<red>[{process.name}]</red>|"
# "<yellow>{level: <6}</yellow> "
# "<cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan>\n\t - <level>{message}</level>\n"
"<yellow>{function}</yellow>:<cyan>{line:<4}</cyan>| {message}"
)
logger.remove()
def get_logger(file_name=None, clear=False, **kwargs):
global logger_sink
if clear:
logger.remove()
logger_sink.clear()
if file_name is None:
file_name = sys.stderr
if "level" not in kwargs:
kwargs["level"] = "INFO"
if "format" not in kwargs:
kwargs["format"] = LOG_FORMAT
if file_name in logger_sink.values():
logger.debug(f"{str(file_name)} already registered")
else:
sink_id = logger.add(file_name, **kwargs)
logger_sink[sink_id] = file_name
logger.debug(f"sink_id: {sink_id:02d} ---> {str(file_name)}")
return logger
+171
View File
@@ -0,0 +1,171 @@
import os
import pickle
import torch
import contextlib
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
matplotlib.rcParams['pdf.fonttype'] = 42
plt.rcParams.update({'font.size': 12})
def save_pickle(data, folder, filename):
os.makedirs(folder, exist_ok=True)
filepath = os.path.join(folder, filename)
with open(filepath, 'wb') as file:
pickle.dump(data, file)
def load_pickle(file_path, key):
try:
with open(file_path, 'rb') as file:
# Load the data from the pickle file
data = pickle.load(file)
# Print the contents of the pickle file
print("Contents of the pickle file:")
if key == 'Tr_Loss':
arr = windowed_mean(data[key], window_size=4)
print(np.nanmin(arr))
elif key == 'Val_Acc':
arr = windowed_mean(data[key], window_size=4)
print(np.max(arr))
elif key == 'Query':
print(np.sum(data[key]))
else:
print(data[key])
except FileNotFoundError:
print(f"Error: File '{file_path}' not found.")
except Exception as e:
print(f"Error: Unable to load the pickle file. {e}")
def convert_to_cpu_float(dictionary):
"""
Convert PyTorch tensors in a dictionary from cuda:0 to floats on CPU.
Parameters:
- dictionary: Dictionary with keys and PyTorch tensors/lists of tensors on cuda:0.
Returns:
- Converted dictionary with tensors/lists as floats on CPU.
"""
converted_dict = {}
for key, value in dictionary.items():
if isinstance(value, torch.Tensor):
converted_dict[key] = value.cpu().float()
elif isinstance(value, list):
converted_dict[key] = [item.cpu().numpy() for item in value]
else:
converted_dict[key] = value # Non-tensor values remain unchanged
return converted_dict
def average_across_batch(arr, epochs):
arr_np = np.array(arr)
arr_avg = np.mean(np.array(np.split(arr_np, epochs)), axis=1)
return np.reshape(arr_avg, (1, arr_avg.shape[0]))
def moving_average(a, n=20):
ret = np.cumsum(a, dtype=float)
ret[n:] = ret[n:] - ret[:-n]
return ret[n - 1:] / n
def plot_results(title, d, loss="Train Loss: ", lim_x=1000, lim_y=3):
plt.figure()
for k, val in d.items():
v = np.array([val])
means = np.mean(v, axis=0)
# mins = np.amin(v, axis=0)
# maxes = np.amax(v, axis=0)
means = moving_average(means)
plt.plot(range(1, len(means)+1), means, linewidth=2, linestyle='solid', markersize=12, label=k)
plt.title(title)
plt.yscale('log')
plt.xlim(1, lim_x)
plt.ylim(0.9, lim_y)
plt.ylabel(loss)
plt.xlabel('Step')
plt.legend(bbox_to_anchor=(0.65, 1.0), loc="upper left")
plt.grid()
plt.tight_layout()
plt.savefig(title + '.pdf')
def plot_results_time(title, d_y, d_x, loss="Train Loss: ", lim_x=1000, lim_y=3):
plt.figure()
for k, val in d_y.items():
v = np.array([val])
v_x = np.cumsum(np.array([d_x[k]]))*(1e-17)
means = np.mean(v, axis=0)
# mins = np.amin(v, axis=0)
# maxes = np.amax(v, axis=0)
means = moving_average(means)
ll = len(means)
plt.plot(v_x[:ll], means, linewidth=2, linestyle='solid', markersize=12, label=k)
plt.title(title)
plt.yscale('log')
plt.xscale('log')
plt.xlim(0, lim_x)
# plt.ylim(0.7, lim_y)
plt.ylabel(loss)
plt.xlabel('Time (s)')
plt.legend(bbox_to_anchor=(0.0, 1), loc="upper left")
plt.grid()
plt.tight_layout()
plt.savefig(title + '.pdf')
def plot_results_query(title, d_y, d_x, loss="Train Loss: ", lim_x=1000, lim_y=3):
plt.figure()
for k, val in d_y.items():
v = np.array([val])
v_x = np.cumsum(np.array([d_x[k]]))
means = np.mean(v, axis=0)
# mins = np.amin(v, axis=0)
# maxes = np.amax(v, axis=0)
means = moving_average(means)
ll = len(means)
plt.plot(v_x[:ll], means, linewidth=2, linestyle='solid', markersize=12, label=k)
plt.title(title)
plt.yscale('log')
plt.xscale('log')
plt.xlim(1e3, lim_x)
plt.ylim(0.7, lim_y)
plt.ylabel(loss)
plt.xlabel('Queries')
plt.legend(bbox_to_anchor=(0.0, 1), loc="upper left")
plt.grid()
plt.tight_layout()
plt.savefig(title + '.pdf')
def windowed_mean(arr, window_size):
arr = np.array(arr)
return np.mean(arr.reshape(-1, window_size), axis=1)
@contextlib.contextmanager
def temp_seed(seed):
state = np.random.get_state()
np.random.seed(seed)
try:
yield
finally:
np.random.set_state(state)
+29
View File
@@ -0,0 +1,29 @@
from .glue import GLUEDataModule, GLUE_TASKS
from .superglue import SuperGLUEDataModule, SUPERGLUE_TASKS
__all__ = ['GLUEDataModule', 'GLUE_TASKS', 'SuperGLUEDataModule', 'SUPERGLUE_TASKS']
def get_data_module(args):
if args.task in GLUE_TASKS:
dm_class = GLUEDataModule
elif args.task in SUPERGLUE_TASKS:
dm_class = SuperGLUEDataModule
else:
raise ValueError(f"Task {args.task} is not supported")
dm = dm_class(
model_name_or_path=args.model_name,
task_name=args.task,
max_seq_length=args.max_seq_length,
sample_size=args.samplesize,
train_batch_size=args.batchsize,
validation_sample_size=args.samplesize_validation,
eval_batch_size=args.batchsize,
soft_prompt=args.soft_prompt,
hf_token=args.hf_token
)
dm.setup(stage='fit')
return dm
+184
View File
@@ -0,0 +1,184 @@
from typing import Optional
import datasets
import lightning as L
from torch.utils.data import DataLoader, Subset
from transformers import AutoTokenizer
from dataset.mezo_dataset import tokenize_multipart_input
GLUE_TASKS = ["cola", "sst2", "mnli", "qnli"]
class GLUEDataModule(L.LightningDataModule):
task_text_field_map = {
"cola": ["sentence"],
"sst2": ["sentence"],
"mnli": ["premise", "hypothesis"],
"qnli": ["question", "sentence"],
}
glue_task_num_labels = {
"cola": 2,
"sst2": 2,
"mnli": 3,
"qnli": 2,
}
loader_columns = [
"datasets_idx",
"input_ids",
"token_type_ids",
"attention_mask",
"start_positions",
"end_positions",
"labels"
]
glue_task_label_mapping = {
'sst2': {
0: 'terrible',
1: 'great'
}
}
def __init__(
self,
model_name_or_path: str,
task_name: str = "mrpc",
max_seq_length: int = 512,
train_batch_size: int = 32,
eval_batch_size: int = 32,
sample_size: int = 128,
validation_sample_size: int = 128,
soft_prompt: bool = False,
hf_token: Optional[str] = None,
**kwargs,
):
super().__init__()
self.model_name_or_path = model_name_or_path
self.task_name = task_name
self.max_seq_length = max_seq_length
self.train_batch_size = train_batch_size
self.eval_batch_size = eval_batch_size
self.sample_size = sample_size
self.validation_sample_size = validation_sample_size
self.text_fields = self.task_text_field_map[task_name]
self.num_labels = self.glue_task_num_labels[task_name]
self.tokenizer = AutoTokenizer.from_pretrained(self.model_name_or_path, use_fast=True, token=hf_token)
self.soft_prompt = soft_prompt
if soft_prompt is True:
self.loader_columns.append("mask_pos")
def setup(self, stage: str = 'fit', randomize=False, seed=None):
self.dataset = datasets.load_dataset("glue", self.task_name)
for split in self.dataset.keys():
if split == "test":
continue
if self.soft_prompt is True:
self.dataset[split] = self.dataset[split].map(
self.convert_to_features_soft_prompt,
batched=False,
remove_columns=["label"],
load_from_cache_file=True
)
else:
self.dataset[split] = self.dataset[split].map(
self.convert_to_features,
batched=True,
remove_columns=["label"],
load_from_cache_file=True
)
self.columns = [c for c in self.dataset[split].column_names if c in self.loader_columns]
self.dataset[split].set_format(type="torch", columns=self.columns)
self.eval_splits = [x for x in self.dataset.keys() if "validation" in x]
self.subset_indices = list(range(self.sample_size))
self.subset_indices_val = list(range(self.validation_sample_size))
self.subset_train_dataset = Subset(self.dataset["train"], self.subset_indices)
if len(self.eval_splits) == 1:
self.subset_val_dataset = Subset(self.dataset["validation"], self.subset_indices_val)
else:
self.subset_val_dataset = Subset(self.dataset["validation_matched"], self.subset_indices_val)
def prepare_data(self):
datasets.load_dataset("glue", self.task_name)
AutoTokenizer.from_pretrained(self.model_name_or_path, use_fast=True)
def train_dataloader(self):
return DataLoader(self.subset_train_dataset, batch_size=self.train_batch_size, shuffle=True)
def train_full_dataloader(self):
return DataLoader(self.subset_train_dataset, batch_size=self.sample_size, shuffle=True)
def val_dataloader(self):
return DataLoader(self.subset_val_dataset, batch_size=self.eval_batch_size)
def test_dataloader(self):
if len(self.eval_splits) == 1:
return DataLoader(self.dataset["test"], batch_size=self.eval_batch_size)
elif len(self.eval_splits) > 1:
return [DataLoader(self.dataset[x], batch_size=self.eval_batch_size) for x in self.eval_splits]
def convert_to_features_soft_prompt(self, example_batch, indices=None):
if self.task_name == 'sst2':
inputs = tokenize_multipart_input(
input_text_list=[example_batch[self.text_fields[0]]],
max_length=self.max_seq_length,
tokenizer=self.tokenizer,
task_name=self.task_name,
prompt=True,
template='*cls**sent_0*_It_was*mask*.*sep+*',
label_word_list={0: ' terrible', 1: ' great'}
)
inputs['labels'] = example_batch["label"]
return inputs
elif self.task_name == 'mnli':
inputs = tokenize_multipart_input(
input_text_list=[example_batch[self.text_fields[0]], example_batch[self.text_fields[1]]],
max_length=256,
tokenizer=self.tokenizer,
task_name=self.task_name,
prompt=True,
template='*cls**sent-_0*?*mask*,*+sentl_1**sep+*',
label_word_list={'contradiction': 'No', 'entailment': 'Yes', 'neutral': 'Maybe'},
first_sent_limit=240
)
inputs['labels'] = example_batch["label"]
return inputs
def convert_to_features(self, example_batch, indices=None):
# Either encode single sentence or sentence pairs
if len(self.text_fields) > 1:
texts_or_text_pairs = list(zip(example_batch[self.text_fields[0]],
example_batch[self.text_fields[1]]))
else:
texts_or_text_pairs = example_batch[self.text_fields[0]]
# Tokenize the text/text pairs
if (self.model_name_or_path == 'distilbert-base-cased' or
self.model_name_or_path == 'roberta-large'):
features = self.tokenizer.batch_encode_plus(texts_or_text_pairs,
max_length=self.max_seq_length,
pad_to_max_length=True,
truncation=True)
# Rename label to labels to make it easier to pass to model forward
features["labels"] = example_batch["label"]
elif 'gpt2' in self.model_name_or_path or 'opt' in self.model_name_or_path:
if self.tokenizer.pad_token_id is None:
self.tokenizer.pad_token_id = self.tokenizer.eos_token_id
features = self.tokenizer.batch_encode_plus(texts_or_text_pairs,
max_length=self.max_seq_length,
pad_to_max_length=True,
truncation=True)
features["labels"] = example_batch["label"]
return features
+696
View File
@@ -0,0 +1,696 @@
"""Dataset utils for different data settings for GLUE."""
import os
import torch
import numpy as np
import time
from filelock import FileLock
import json
# from src.processors import processors_mapping, num_labels_mapping, output_modes_mapping, compute_metrics_mapping, median_mapping
from transformers.data.processors.utils import InputFeatures
import dataclasses
from dataclasses import dataclass
from typing import List, Optional, Union
import pandas as pd
from common.logging import logger
# logger = logging.getLogger(__name__)
# logger.setLevel(logging.INFO)
@dataclass(frozen=True)
class OurInputFeatures(InputFeatures):
"""
Inherit from Transformers' InputFeatuers.
"""
input_ids: List[int]
attention_mask: Optional[List[int]] = None
token_type_ids: Optional[List[int]] = None
label: Optional[Union[int, float]] = None
mask_pos: Optional[List[int]] = None # Position of the mask token
label_word_list: Optional[List[int]] = None # Label word mapping (dynamic)
# For icl sfc
sfc_input_ids: List[int] = None
sfc_attention_mask: Optional[List[int]] = None
sfc_mask_pos: Optional[List[int]] = None
def to_json_string(self):
"""Serializes this instance to a JSON string."""
return json.dumps(dataclasses.asdict(self)) + "\n"
def input_example_to_string(example, sep_token):
if example.text_b is None:
return example.text_a
else:
# Warning: very simple hack here
return example.text_a + ' ' + sep_token + ' ' + example.text_b
def input_example_to_tuple(example):
if example.text_b is None:
if pd.isna(example.text_a) or example.text_a is None:
return ['']
logger.warn("Empty input")
else:
return [example.text_a]
else:
return [example.text_a, example.text_b]
def tokenize_multipart_input(
input_text_list,
max_length,
tokenizer,
task_name=None,
prompt=False,
template=None,
label_word_list=None,
first_sent_limit=None,
other_sent_limit=None,
gpt3=False,
truncate_head=False,
support_labels=None,
):
def enc(text):
return tokenizer.encode(text, add_special_tokens=False)
input_ids = []
attention_mask = []
token_type_ids = [] # Only for BERT
mask_pos = None # Position of the mask token
if prompt:
"""
Concatenate all sentences and prompts based on the provided template.
Template example: '*cls*It was*mask*.*sent_0**<sep>*label_0:*sent_1**<sep>**label_1*:*sent_2**<sep>*'
*xx* represent variables:
*cls*: cls_token
*mask*: mask_token
*sep*: sep_token
*sep+*: sep_token, also means +1 for segment id
*sent_i*: sentence i (input_text_list[i])
*sent-_i*: same as above, but delete the last token
*sentl_i*: same as above, but use lower case for the first word
*sentl-_i*: same as above, but use lower case for the first word and delete the last token
*+sent_i*: same as above, but add a space before the sentence
*+sentl_i*: same as above, but add a space before the sentence and use lower case for the first word
*label_i*: label_word_list[i]
*label_x*: label depends on the example id (support_labels needed). this is only used in GPT-3's in-context learning
Use "_" to replace space.
PAY ATTENTION TO SPACE!! DO NOT leave space before variables, for this will lead to extra space token.
"""
assert template is not None
special_token_mapping = {
'bos': tokenizer.bos_token_id, 'cls': tokenizer.cls_token_id, 'eos': tokenizer.eos_token_id, 'mask': tokenizer.mask_token_id, 'sep': tokenizer.sep_token_id, 'sep+': tokenizer.sep_token_id,
}
template_list = template.split('*') # Get variable list in the template
segment_id = 0 # Current segment id. Segment id +1 if encountering sep+.
for part_id, part in enumerate(template_list):
new_tokens = []
segment_plus_1_flag = False
if part in special_token_mapping:
if (part == 'cls' or part == 'bos'): # and ('T5' in type(tokenizer).__name__ or tokenizer.model_type == "gpt2"):
# T5 or GPT-2 do not have cls token
continue
new_tokens.append(special_token_mapping[part])
if part == 'sep+':
segment_plus_1_flag = True
elif part[:6] == 'label_':
# Note that label_word_list already has extra space, so do not add more space ahead of it.
label_id = int(part.split('_')[1])
label_word = label_word_list[label_id]
new_tokens.append(label_word)
elif part[:7] == 'labelx_':
instance_id = int(part.split('_')[1])
label_id = support_labels[instance_id]
label_word = label_word_list[label_id]
new_tokens.append(label_word)
elif part[:5] == 'sent_':
sent_id = int(part.split('_')[1])
new_tokens += enc(input_text_list[sent_id])
elif part[:6] == '+sent_':
# Add space
sent_id = int(part.split('_')[1])
new_tokens += enc(' ' + input_text_list[sent_id])
elif part[:6] == 'sent-_':
# Delete the last token
sent_id = int(part.split('_')[1])
new_tokens += enc(input_text_list[sent_id][:-1])
elif part[:6] == 'sentl_':
# Lower case the first token
sent_id = int(part.split('_')[1])
text = input_text_list[sent_id]
text = text[:1].lower() + text[1:]
new_tokens += enc(text)
elif part[:7] == '+sentl_':
# Lower case the first token and add space
sent_id = int(part.split('_')[1])
text = input_text_list[sent_id]
text = text[:1].lower() + text[1:]
new_tokens += enc(' ' + text)
elif part[:7] == 'sentl-_':
# Lower case the first token and discard the last token
sent_id = int(part.split('_')[1])
text = input_text_list[sent_id]
text = text[:1].lower() + text[1:]
new_tokens += enc(text[:-1])
elif part[:6] == 'sentu_':
# Upper case the first token
sent_id = int(part.split('_')[1])
text = input_text_list[sent_id]
text = text[:1].upper() + text[1:]
new_tokens += enc(text)
elif part[:7] == '+sentu_':
# Upper case the first token and add space
sent_id = int(part.split('_')[1])
text = input_text_list[sent_id]
text = text[:1].upper() + text[1:]
new_tokens += enc(' ' + text)
elif part[:8] == '+sentu-_':
# Upper case the first token and add space
sent_id = int(part.split('_')[1])
text = input_text_list[sent_id]
text = text[:1].upper() + text[1:]
new_tokens += enc(' ' + text[:-1])
else:
# Just natural language prompt
part = part.replace('_', ' ')
# handle special case when T5 tokenizer might add an extra space
if len(part) == 1:
new_tokens.append(tokenizer.convert_tokens_to_ids(part))
else:
new_tokens += enc(part)
if part[:4] == 'sent' or part[1:5] == 'sent':
# If this part is the sentence, limit the sentence length
sent_id = int(part.split('_')[1])
if sent_id == 0:
if first_sent_limit is not None:
new_tokens = new_tokens[:first_sent_limit]
else:
if other_sent_limit is not None:
new_tokens = new_tokens[:other_sent_limit]
input_ids += new_tokens
attention_mask += [1 for i in range(len(new_tokens))]
token_type_ids += [segment_id for i in range(len(new_tokens))]
if segment_plus_1_flag:
segment_id += 1
else:
if tokenizer.cls_token_id is not None:
input_ids = [tokenizer.cls_token_id]
attention_mask = [1]
token_type_ids = [0]
else:
input_ids = []
attention_mask = []
token_type_ids = []
for sent_id, input_text in enumerate(input_text_list):
if input_text is None:
# Do not have text_b
continue
if pd.isna(input_text) or input_text is None:
# Empty input
input_text = ''
input_tokens = enc(input_text) + [tokenizer.sep_token_id]
input_ids += input_tokens
attention_mask += [1 for i in range(len(input_tokens))]
token_type_ids += [sent_id for i in range(len(input_tokens))]
if 'T5' in type(tokenizer).__name__: # T5 does not have CLS token
input_ids = input_ids[1:]
attention_mask = attention_mask[1:]
token_type_ids = token_type_ids[1:]
# Padding
if first_sent_limit is not None and len(input_ids) > max_length:
# If using sentence limit, the total length still exceeds the maximum limit, report a warning
logger.warn("Input exceeds max_length limit: {}".format(tokenizer.decode(input_ids)))
# Code below is commented out, because we use dynamic padding rather than static padding to max_length
while len(input_ids) < max_length:
input_ids.append(tokenizer.pad_token_id)
attention_mask.append(0)
token_type_ids.append(0)
# Truncate
if len(input_ids) > max_length:
if truncate_head:
input_ids = input_ids[-max_length:]
attention_mask = attention_mask[-max_length:]
token_type_ids = token_type_ids[-max_length:]
else:
# Default is to truncate the tail
input_ids = input_ids[:max_length]
attention_mask = attention_mask[:max_length]
token_type_ids = token_type_ids[:max_length]
# Find mask token
if prompt and tokenizer.mask_token_id is not None:
# Make sure that the masked position is inside the max_length
assert tokenizer.mask_token_id in input_ids, \
"Mask token not found for input: {} {}".format(input_text_list, input_ids)
mask_pos = [input_ids.index(tokenizer.mask_token_id)]
assert mask_pos[0] < max_length
elif prompt and tokenizer.mask_token_id is None:
# autoregressive model
mask_pos = [len(input_ids) - 1]
result = {'input_ids': input_ids, 'attention_mask': attention_mask}
if 'BERT' in type(tokenizer).__name__:
# Only provide token type ids for BERT
result['token_type_ids'] = token_type_ids
if prompt:
result['mask_pos'] = mask_pos
return result
class FewShotDataset(torch.utils.data.Dataset):
"""Few-shot dataset."""
def __init__(self, args, tokenizer, cache_dir=None, mode="train", use_demo=False):
self.args = args
self.task_name = args.task_name
self.processor = processors_mapping[args.task_name]
self.tokenizer = tokenizer
self.mode = mode
# If not using demonstrations, use use_demo=True
self.use_demo = use_demo
if self.use_demo:
print("Use demonstrations")
assert mode in ["train", "dev", "test"]
# Get label list and (for prompt) label word list
self.label_list = self.processor.get_labels()
self.num_labels = len(self.label_list)
if args.prompt and args.mapping is not None:
self.label_to_word = eval(args.mapping)
for key in self.label_to_word:
# For RoBERTa/BART/T5, tokenization also considers space, so we use space+word as label words.
if self.label_to_word[key][0] not in ['<', '[', '.', ',']:
# Make sure space+word is in the vocabulary
assert len(tokenizer.tokenize(' ' + self.label_to_word[key])) == 1
self.label_to_word[key] = tokenizer.convert_tokens_to_ids(tokenizer.tokenize(' ' + self.label_to_word[key])[0])
else:
self.label_to_word[key] = tokenizer.convert_tokens_to_ids(self.label_to_word[key])
print("Label {} to word {} ({})".format(key, tokenizer.convert_ids_to_tokens(self.label_to_word[key]), self.label_to_word[key]))
if len(self.label_list) > 1:
self.label_word_list = [self.label_to_word[label] for label in self.label_list]
else:
# Regression task
# '0' represents low polarity and '1' represents high polarity.
self.label_word_list = [self.label_to_word[label] for label in ['0', '1']]
else:
self.label_to_word = None
self.label_word_list = None
# Multiple sampling: when using demonstrations, we sample different combinations of demonstrations during
# inference and aggregate the results by averaging the logits. The number of different samples is num_sample.
if (mode == "train") or not self.use_demo:
# We do not do multiple sampling when not using demonstrations or when it's the training mode
self.num_sample = 1
else:
self.num_sample = args.num_sample
# If we use multiple templates, we also need to do multiple sampling during inference.
if args.prompt and args.template_list is not None:
print("There are %d templates. Multiply num_sample by %d" % (len(args.template_list), len(args.template_list)))
self.num_sample *= len(args.template_list)
print("Total num_sample for mode %s: %d" % (mode, self.num_sample))
# Load cache
# Cache name distinguishes mode, task name, tokenizer, and length. So if you change anything beyond these elements, make sure to clear your cache.
cached_features_file = os.path.join(
cache_dir if cache_dir is not None else args.data_dir,
"cached_{}_{}_{}_{}".format(
mode,
tokenizer.__class__.__name__ + "-" + tokenizer.model_type,
str(args.max_seq_length),
args.task_name,
),
)
print(f"Creating/loading examples from dataset file at {args.data_dir}")
lock_path = cached_features_file + ".lock"
with FileLock(lock_path):
if os.path.exists(cached_features_file) and not args.overwrite_cache:
start = time.time()
self.support_examples, self.query_examples = torch.load(cached_features_file)
print(
f"Loading features from cached file {cached_features_file} [took %.3f s]", time.time() - start
)
else:
print(f"Creating features from dataset file at {args.data_dir}")
# The support examples are sourced from the training set.
self.support_examples = self.processor.get_train_examples(args.data_dir)
if mode == "dev":
self.query_examples = self.processor.get_dev_examples(args.data_dir)
elif mode == "test":
self.query_examples = self.processor.get_test_examples(args.data_dir)
else:
self.query_examples = self.support_examples
start = time.time()
torch.save([self.support_examples, self.query_examples], cached_features_file)
# ^ This seems to take a lot of time so I want to investigate why and how we can improve.
print(
"Saving features into cached file %s [took %.3f s]", cached_features_file, time.time() - start
)
# For filtering in using demonstrations, load pre-calculated embeddings
if self.use_demo and args.demo_filter:
split_name = ''
if mode == 'train':
split_name = 'train'
elif mode == 'dev':
if args.task_name == 'mnli':
split_name = 'dev_matched'
elif args.task_name == 'mnli-mm':
split_name = 'dev_mismatched'
else:
split_name = 'dev'
elif mode == 'test':
if args.task_name == 'mnli':
split_name = 'test_matched'
elif args.task_name == 'mnli-mm':
split_name = 'test_mismatched'
else:
split_name = 'test'
else:
raise NotImplementedError
self.support_emb = np.load(os.path.join(args.data_dir, "train_{}.npy".format(args.demo_filter_model)))
self.query_emb = np.load(os.path.join(args.data_dir, "{}_{}.npy".format(split_name, args.demo_filter_model)))
print("Load embeddings (for demonstration filtering) from {}".format(os.path.join(args.data_dir, "{}_{}.npy".format(split_name, args.demo_filter_model))))
assert len(self.support_emb) == len(self.support_examples)
assert len(self.query_emb) == len(self.query_examples)
# Size is expanded by num_sample
self.size = len(self.query_examples) * self.num_sample
# Prepare examples (especially for using demonstrations)
support_indices = list(range(len(self.support_examples)))
self.example_idx = []
for sample_idx in range(self.num_sample):
for query_idx in range(len(self.query_examples)):
# If training, exclude the current example. Else keep all.
if self.use_demo and args.demo_filter:
# Need sentence_transformers for demonstrations,
# which is not included in the requirements for us, but see original LM-BFF repo.
from sentence_transformers import SentenceTransformer, util
# Demonstration filtering
candidate = [support_idx for support_idx in support_indices
if support_idx != query_idx or mode != "train"]
sim_score = []
for support_idx in candidate:
sim_score.append((support_idx, util.pytorch_cos_sim(self.support_emb[support_idx], self.query_emb[query_idx])))
sim_score.sort(key=lambda x: x[1], reverse=True)
if self.num_labels == 1:
# Regression task
limit_each_label = int(len(sim_score) // 2 * args.demo_filter_rate)
count_each_label = {'0': 0, '1': 0}
context_indices = []
if args.debug_mode:
print("Query %s: %s" % (self.query_examples[query_idx].label, self.query_examples[query_idx].text_a)) # debug
for support_idx, score in sim_score:
if count_each_label['0' if float(self.support_examples[support_idx].label) <= median_mapping[args.task_name] else '1'] < limit_each_label:
count_each_label['0' if float(self.support_examples[support_idx].label) <= median_mapping[args.task_name] else '1'] += 1
context_indices.append(support_idx)
if args.debug_mode:
print(" %.4f %s | %s" % (score, self.support_examples[support_idx].label, self.support_examples[support_idx].text_a)) # debug
else:
limit_each_label = int(len(sim_score) // self.num_labels * args.demo_filter_rate)
count_each_label = {label: 0 for label in self.label_list}
context_indices = []
if args.debug_mode:
print("Query %s: %s" % (self.query_examples[query_idx].label, self.query_examples[query_idx].text_a)) # debug
for support_idx, score in sim_score:
if count_each_label[self.support_examples[support_idx].label] < limit_each_label:
count_each_label[self.support_examples[support_idx].label] += 1
context_indices.append(support_idx)
if args.debug_mode:
print(" %.4f %s | %s" % (score, self.support_examples[support_idx].label, self.support_examples[support_idx].text_a)) # debug
else:
# Using demonstrations without filtering
context_indices = [support_idx for support_idx in support_indices
if support_idx != query_idx or mode != "train"]
# We'll subsample context_indices further later.
self.example_idx.append((query_idx, context_indices, sample_idx))
# If it is not training, we pre-process the data; otherwise, we process the data online.
if mode != "train":
self.features = []
_ = 0
for query_idx, context_indices, bootstrap_idx in self.example_idx:
# The input (query) example
example = self.query_examples[query_idx]
# The demonstrations
supports = self.select_context([self.support_examples[i] for i in context_indices])
if args.template_list is not None:
template = args.template_list[sample_idx % len(args.template_list)] # Use template in order
else:
template = args.template
self.features.append(self.convert_fn(
example=example,
supports=supports,
use_demo=self.use_demo,
label_list=self.label_list,
prompt=args.prompt,
template=template,
sfc_template=getattr(args, "icl_sfc_prompt", None),
label_word_list=self.label_word_list,
verbose=True if _ == 0 else False,
))
_ += 1
else:
self.features = None
def select_context(self, context_examples):
"""
Select demonstrations from provided examples.
"""
max_demo_per_label = 1
counts = {k: 0 for k in self.label_list}
if len(self.label_list) == 1:
# Regression
counts = {'0': 0, '1': 0}
selection = []
if self.args.gpt3_in_context_head or self.args.gpt3_in_context_tail:
# For GPT-3's in-context learning, we sample gpt3_in_context_num demonstrations randomly.
order = np.random.permutation(len(context_examples))
for i in range(min(self.args.gpt3_in_context_num, len(order))):
selection.append(context_examples[order[i]])
else:
# Our sampling strategy
order = np.random.permutation(len(context_examples))
for i in order:
label = context_examples[i].label
if len(self.label_list) == 1:
# Regression
label = '0' if float(label) <= median_mapping[self.args.task_name] else '1'
if counts[label] < max_demo_per_label:
selection.append(context_examples[i])
counts[label] += 1
if sum(counts.values()) == len(counts) * max_demo_per_label:
break
assert len(selection) > 0
return selection
def __len__(self):
return self.size
def __getitem__(self, i):
if self.features is None:
query_idx, context_indices, bootstrap_idx = self.example_idx[i]
# The input (query) example
example = self.query_examples[query_idx]
# The demonstrations
supports = self.select_context([self.support_examples[i] for i in context_indices])
if self.args.template_list is not None:
template = self.args.template_list[sample_idx % len(self.args.template_list)]
else:
template = self.args.template
features = self.convert_fn(
example=example,
supports=supports,
use_demo=self.use_demo,
label_list=self.label_list,
prompt=self.args.prompt,
template=template,
label_word_list=self.label_word_list,
verbose=False,
)
else:
features = self.features[i]
return features
def get_labels(self):
return self.label_list
def convert_fn(
self,
example,
supports,
use_demo=False,
label_list=None,
prompt=False,
template=None,
sfc_template=None,
label_word_list=None,
verbose=False
):
"""
Returns a list of processed "InputFeatures".
"""
max_length = self.args.max_seq_length
# Prepare labels
label_map = {label: i for i, label in enumerate(label_list)} # Mapping the label names to label ids
if len(label_list) == 1:
# Regression
label_map = {'0': 0, '1': 1}
# Get example's label id (for training/inference)
if example.label is None:
example_label = None
elif len(label_list) == 1:
# Regerssion
example_label = float(example.label)
else:
example_label = label_map[example.label]
# Prepare other features
if not use_demo:
# No using demonstrations
inputs = tokenize_multipart_input(
input_text_list=input_example_to_tuple(example),
max_length=max_length,
tokenizer=self.tokenizer,
task_name=self.args.task_name,
prompt=prompt,
template=template,
label_word_list=label_word_list,
first_sent_limit=self.args.first_sent_limit,
other_sent_limit=self.args.other_sent_limit,
)
features = OurInputFeatures(**inputs, label=example_label)
else:
# Using demonstrations
# Max length
if self.args.double_demo:
# When using demonstrations, double the maximum length
# Note that in this case, args.max_seq_length is the maximum length for a single sentence
max_length = max_length * 2
if self.args.gpt3_in_context_head or self.args.gpt3_in_context_tail:
# When using GPT-3's in-context learning, take the maximum tokenization length of the model (512)
if self.tokenizer.model_type == "gpt2":
max_length = 1024
elif self.tokenizer.model_type == "opt":
max_length = 2048
else:
max_length = 512
# All input sentences, including the query and the demonstrations, are put into augmented_examples,
# and are numbered based on the order (starting from 0). For single sentence tasks, the input (query)
# is the sentence 0; for sentence-pair tasks, the input (query) is the sentence 0 and 1. Note that for GPT-3's
# in-context learning, the input (query) might be at the end instead of the beginning (gpt3_in_context_head)
augmented_example = []
query_text = input_example_to_tuple(example) # Input sentence list for query
support_by_label = [[] for i in range(len(label_map))]
if self.args.gpt3_in_context_head or self.args.gpt3_in_context_tail:
support_labels = []
augmented_example = query_text
for support_example in supports:
augmented_example += input_example_to_tuple(support_example)
current_label = support_example.label
if len(label_list) == 1:
current_label = '0' if float(current_label) <= median_mapping[self.args.task_name] else '1' # Regression
support_labels.append(label_map[current_label])
else:
# Group support examples by label
for label_name, label_id in label_map.items():
if len(label_list) == 1:
# Regression
for support_example in filter(lambda s: ('0' if float(s.label) <= median_mapping[self.args.task_name] else '1') == label_name, supports):
support_by_label[label_id] += input_example_to_tuple(support_example)
else:
for support_example in filter(lambda s: s.label == label_name, supports):
support_by_label[label_id] += input_example_to_tuple(support_example)
augmented_example = query_text
for label_id in range(len(label_map)):
augmented_example += support_by_label[label_id]
# Tokenization (based on the template)
inputs = tokenize_multipart_input(
input_text_list=augmented_example,
max_length=max_length,
tokenizer=self.tokenizer,
task_name=self.args.task_name,
prompt=prompt,
template=template,
label_word_list=label_word_list,
first_sent_limit=self.args.first_sent_limit,
other_sent_limit=self.args.other_sent_limit,
truncate_head=self.args.truncate_head,
gpt3=self.args.gpt3_in_context_head or self.args.gpt3_in_context_tail,
support_labels=None if not (self.args.gpt3_in_context_head or self.args.gpt3_in_context_tail) else support_labels
)
if sfc_template is not None:
# Process sfc example
if verbose:
print("*** SFC Example ***")
sfc_feature = self.convert_fn(
example, supports, use_demo=use_demo, label_list=label_list, prompt=prompt, template=sfc_template, label_word_list=label_word_list, verbose=verbose
)
features = OurInputFeatures(**inputs, label=example_label, sfc_input_ids=sfc_feature.input_ids, sfc_attention_mask=sfc_feature.attention_mask, sfc_mask_pos=sfc_feature.mask_pos)
else:
features = OurInputFeatures(**inputs, label=example_label)
if verbose:
print("*** Example ***")
print("guid: %s" % (example.guid))
print("features: %s" % features)
print("text: %s" % self.tokenizer.decode(features.input_ids))
return features
+183
View File
@@ -0,0 +1,183 @@
import datasets
import numpy as np
import pytorch_lightning as pl
from datasets import Dataset, DatasetDict
from torch.utils.data import DataLoader, Subset
from transformers import AutoTokenizer
from common.utils import temp_seed
SUPERGLUE_TASKS = ["rte", "wic", "copa", "boolq", "cb", "wsc"]
class SuperGLUEDataModule(pl.LightningDataModule):
task_num_labels = {
"rte": 2,
"wic": 2,
"copa": 2,
"boolq": 2,
"cb": 3,
"wsc": 2,
}
loader_columns = [
"datasets_idx",
"input_ids",
"token_type_ids",
"attention_mask",
"start_positions",
"end_positions",
"labels"
]
def __init__(
self,
model_name_or_path: str,
task_name: str = "rte",
max_seq_length: int = 512,
train_batch_size: int = 32,
eval_batch_size: int = 32,
sample_size: int = 128,
validation_sample_size: int = 128,
**kwargs,
):
super().__init__()
self.model_name_or_path = model_name_or_path
self.task_name = task_name
self.max_seq_length = max_seq_length
self.train_batch_size = train_batch_size
self.eval_batch_size = eval_batch_size
self.sample_size = sample_size
self.validation_sample_size = validation_sample_size
self.num_labels = self.task_num_labels[task_name]
self.tokenizer = AutoTokenizer.from_pretrained(self.model_name_or_path, use_fast=True)
def sample_subset(self, split="train", seed=0, num=100):
with temp_seed(seed):
lens = len(self.dataset[split])
index = np.random.permutation(lens).tolist()[:num + 1]
index = index[:num]
return index
def load_dataset(self, task_name):
hf_dataset = datasets.load_dataset("super_glue", task_name)
dataset = DatasetDict()
if task_name == "rte":
dataset = hf_dataset.map(lambda x: {"input": (x["premise"], x["hypothesis"])})
elif task_name == "boolq":
dataset = hf_dataset.map(lambda x: {"input": (x["passage"], x["question"]+"?" if x["question"][-1] != "?" else x["question"])})
elif task_name == "copa":
dataset = DatasetDict()
for split in hf_dataset.keys():
examples = []
for example in hf_dataset[split]:
premise = example["premise"]
choice1 = example["choice1"]
choice2 = example["choice2"]
question = example["question"]
if question == "cause":
examples.append({
"input": [choice1, premise],
"label": int(example["label"] == 0) if example["label"] is not None else None
})
examples.append({
"input": [choice2, premise],
"label": int(example["label"] == 1) if example["label"] is not None else None
})
else:
examples.append({
"input": [premise, choice1],
"label": int(example["label"] == 0) if example["label"] is not None else None
})
examples.append({
"input": [premise, choice2],
"label": int(example["label"] == 1) if example["label"] is not None else None
})
dataset[split] = Dataset.from_list(examples)
elif task_name == "cb":
dataset = hf_dataset.map(lambda x: {"input": (x["premise"], x["hypothesis"])})
elif task_name == "wic":
dataset = hf_dataset.map(lambda x: {"input": (f"{x['word']} : {x['sentence1']}", x['sentence2'])})
elif task_name == "wsc":
def wsc_formatter(example):
text = example['text']
span1_index = example['span1_index']
span2_index = example['span2_index']
span1_text = example['span1_text']
span2_text = example['span2_text']
words = text.split()
span1_word_len = len(span1_text.split())
span2_word_len = len(span2_text.split())
words[span1_index:span1_index + span1_word_len] = [f"# {span1_text} #"]
if span1_word_len > 1:
# If the span is more than one word, we need to adjust the index of the second span since the first more than one word has been replaced by a single word
span2_index -= span1_word_len - 1
words[span2_index:span2_index + span2_word_len] = [f"* {span2_text} *"]
return " ".join(words)
dataset = hf_dataset.map(lambda x: {"input": wsc_formatter(x)})
return dataset
def setup(self, stage='fit', randomize=False, seed=None):
self.dataset = self.load_dataset(self.task_name)
for split in self.dataset.keys():
if split == "test":
continue
self.dataset[split] = self.dataset[split].map(
self.convert_to_features,
batched=True,
remove_columns=["label"],
load_from_cache_file=True
)
self.columns = [c for c in self.dataset[split].column_names if c in self.loader_columns]
self.dataset[split].set_format(type="torch", columns=self.columns)
if len(self.dataset["train"]) < self.sample_size:
self.sample_size = len(self.dataset["train"])
self.eval_splits = ["validation"]
if len(self.dataset[self.eval_splits[0]]) < self.validation_sample_size:
self.validation_sample_size = len(self.dataset[self.eval_splits[0]])
self.subset_indices = list(range(self.sample_size))
self.subset_indices_val = list(range(self.validation_sample_size))
self.subset_train_dataset = Subset(self.dataset["train"], self.subset_indices)
self.subset_val_dataset = Subset(self.dataset["validation"], self.subset_indices_val)
def prepare_data(self):
datasets.load_dataset("super_glue", self.task_name)
AutoTokenizer.from_pretrained(self.model_name_or_path, use_fast=True)
def train_dataloader(self):
return DataLoader(self.subset_train_dataset, batch_size=self.train_batch_size, shuffle=True)
def train_full_dataloader(self):
return DataLoader(self.subset_train_dataset, batch_size=self.sample_size, shuffle=True)
def val_dataloader(self):
return DataLoader(self.subset_val_dataset, batch_size=self.eval_batch_size)
def test_dataloader(self):
return DataLoader(self.dataset["test"], batch_size=self.eval_batch_size)
def convert_to_features(self, example_batch, indices=None):
if self.tokenizer.pad_token_id is None:
# GPT2 and OPT
self.tokenizer.pad_token_id = self.tokenizer.eos_token_id
features = self.tokenizer.batch_encode_plus(
example_batch["input"], max_length=self.max_seq_length, pad_to_max_length=True, truncation=True
)
features["labels"] = example_batch["label"]
return features
Binary file not shown.

After

Width:  |  Height:  |  Size: 816 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 151 KiB

+157
View File
@@ -0,0 +1,157 @@
import argparse
import logging
import math
import os
from datetime import datetime
import torch
import transformers
from common.logging import get_logger
from dataset import get_data_module
from model import get_model
from trainer import finetune_ZO, finetune_FO
def parse_arguments():
parser = argparse.ArgumentParser(description='Argument Parser for Model Fine-tuning')
# common
parser.add_argument('--model_name', type=str, default='distilbert-base-cased',
help='Name of the pre-trained model')
parser.add_argument('--task', type=str, default='mnli', help='Task for model training')
parser.add_argument('--algorithm', type=str, default='ZO', help='Algorithm to use',
choices=["FOSGD", "FOAdam", "ZO", "ZOAdam", "ZOSVRG", "LOZO", "HiZOO", "LOREN"])
parser.add_argument('--device', type=int, default=0, help='GPU Number')
parser.add_argument('--results', type=str, default='results_demo',
help='Name of folder to store results')
# training
parser.add_argument('--epochs', type=int, default=1, help='Number of training epochs')
parser.add_argument('--batchsize', type=int, default=64, help='Batch size for training')
parser.add_argument('--batchsize_limit', type=int, default=64,
help='Max batch size to be used to avoid memory error')
parser.add_argument('--full_parameter', action='store_true',
help='True for full parameter fine-tuning')
# dataset
parser.add_argument('--samplesize', type=int, default=512, help='Training data sample size')
parser.add_argument('--samplesize_validation', type=int, default=256,
help='Validation data sample size')
parser.add_argument('--max_seq_length', type=int, default=256,
help='Max sequence length for inputs')
# optimization
parser.add_argument('--lr', type=float, default=2e-3, help='Learning rate')
parser.add_argument('--weight_decay', type=float, default=0.01, help='weight_decay')
parser.add_argument('--perturbation_scale', type=float, default=1e-3,
help='Perturbation scale for SPSA estimators')
parser.add_argument('--early_stopping', action='store_true', help='Enable early stopping')
parser.add_argument('--patience', type=int, default=10, help='Early stopping patience; '
'if the validation accuracy does not improve for this number of evaluations, '
'stop training')
parser.add_argument('--num_queries', type=int, default=10,
help='Number of queries to evaluate in large batch update')
# experiment
parser.add_argument('--soft_prompt', action='store_true', help='True for using soft prompt')
parser.add_argument('--save_ckpt', action='store_true', help='Save checkpoint')
parser.add_argument('--save_every', type=int, default=10, help='Save checkpoint every n epochs')
parser.add_argument('--eval_every', type=int, default=1,
help='Evaluate on validation set every n epochs')
parser.add_argument('--fp16', action='store_true', help='Use FP16 precision')
parser.add_argument('--bf16', action='store_true', help='Use BF16 precision')
parser.add_argument('--logging', type=str, default="csv", choices=['tensorboard', 'csv'],
help="Choose logging method; either wandb or tensorboard or none")
parser.add_argument('--trial', type=int, default=0, help='Trial number')
parser.add_argument('--init_seed', type=int, default=None, help='Random seed for model initialization')
parser.add_argument('--clipping', action='store_true', help='set to True to apply gradient clipping')
# SVRG
parser.add_argument('--q', type=int, default=2, help='q parameter used only for ZO-SVRG')
parser.add_argument('--lr_mezosvrg_mb', type=float, default=1e-6,
help='Mini-batch learning rate for MeZO-SVRG')
parser.add_argument('--anneal', type=float, default=1.5, help='Annealing parameter')
# Adam
parser.add_argument('--eps', type=float, default=1e-8, help='the level of adaptivity (eps for adam)')
parser.add_argument('--low_bit_adam', type=int, default=0,
help='Use Adam with quantized states; options: 4 or 8')
# LOZO
parser.add_argument('--rank', type=int, default=2, help='rank of U and V')
parser.add_argument('--step_interval', type=int, default=50, help='frequency of updating matrix V')
# HiZOO
parser.add_argument('--hessian_smooth_type', type=str, default="constant1e-8",
help="hessian smooth type")
# LOREN
parser.add_argument('--damping', type=float, default=1.0, help='damping')
parser.add_argument('--lr_cov', type=float, default=1e-3, help='Learning rate for covariance')
args = parser.parse_args()
return args
def setup_logger():
timestamp = datetime.now().strftime("%Y%m%d%H%M%S")
logfile = os.path.join(args.output_dir, f'log_{timestamp}.txt')
logger = get_logger(logfile, level="DEBUG")
get_logger(level='INFO')
"""
The default of training_args.log_level is passive, so we set log level at info here
to have that default.
"""
transformers.utils.logging.set_verbosity_info()
transformers.utils.logging.set_verbosity(logging.INFO)
transformers.utils.logging.enable_default_handler()
transformers.utils.logging.enable_explicit_format()
return logger
if __name__ == "__main__":
os.environ["TOKENIZERS_PARALLELISM"] = "true"
args = parse_arguments()
args.hf_token = os.getenv('HF_TOKEN')
trimmed_model_name = args.model_name.split('/')[-1]
num_steps = math.ceil(args.samplesize / args.batchsize) * args.epochs
args.run_name = f'{args.algorithm}_lr{args.lr:.0e}_nq-{args.num_queries}'
if args.algorithm == 'ZOSVRG':
args.run_name += f'_lr_mb_{args.lr_mezosvrg_mb:.0e}_q_{args.q:.0e}_anneal_{args.anneal:.0e}'
elif args.algorithm == 'ZOAdam':
args.run_name += f'_eps_{args.eps:.0e}'
if args.low_bit_adam == 4 or args.low_bit_adam == 8:
args.run_name += f'_{args.low_bit_adam}bit'
elif args.algorithm == 'LOZO':
args.run_name += f'_rank_{args.rank}_step-interval_{args.step_interval}'
elif args.algorithm == 'HiZOO':
args.run_name += f'_hessian_smooth-{args.hessian_smooth_type}'
elif args.algorithm == 'LOREN':
args.run_name += f'_damp-{args.damping:.0e}_covlr{args.lr_cov:.0e}'
args.run_name += f'_bsz{args.batchsize}_steps{num_steps}'
args.output_dir = os.path.join(args.results, trimmed_model_name, args.task, args.run_name)
if args.logging == "tensorboard":
from lightning.pytorch.loggers import TensorBoardLogger
writer = TensorBoardLogger(args.output_dir)
elif args.logging == 'csv':
from lightning.pytorch.loggers import CSVLogger
writer = CSVLogger(args.output_dir,
flush_logs_every_n_steps=10)
os.makedirs(args.output_dir, exist_ok=True)
# logging setup
logger = setup_logger()
logger.debug(f"Training Arguments {args}")
if torch.cuda.is_available():
device = torch.device("cuda:" + str(args.device))
else:
device = torch.device("cpu")
dm = get_data_module(args)
transformer = get_model(args, dm)
if 'FO' in args.algorithm:
finetune_FO(args, device, dm, transformer, writer)
else:
finetune_ZO(args, device, dm, transformer, writer)
+65
View File
@@ -0,0 +1,65 @@
from .glue_transformer import GLUETransformer
from .glue_transformer_fo import GLUETransformerFO
from .glue_transformer_mezo import GLUETransformerMeZo
from .glue_transformer_svrg import GLUETransformerMeZoSVRG
from .glue_transformer_adam import GLUETransformerMeZoAdam
from .glue_transformer_lozo import GLUETransformerLoZo
from .glue_transformer_hizoo import GLUETransformerHiZOO
from .glue_transformer_loren import GLUETransformerLOREN
from .opt import OPTDecoder, OPTForCausalLM, OPTModel
from .roberta import RobertaConfig, RobertaLMHead, RobertaModel, RobertaPreTrainedModel
from .prompt_finetune import (RobertaModelForPromptFinetuning, OPTModelForPromptFinetuning,
LlamaModelForPromptFinetuning)
__all__ = ['GLUETransformer', 'GLUETransformerMeZo',
'GLUETransformerMeZoSVRG', 'GLUETransformerMeZoAdam',
'GLUETransformerHiZOO', 'GLUETransformerLOREN',
'RobertaPreTrainedModel', 'RobertaModel', 'RobertaLMHead',
'RobertaModelForPromptFinetuning', 'RobertaConfig', 'OPTModelForPromptFinetuning',
'OPTModel', 'OPTForCausalLM', 'OPTDecoder', 'LlamaModelForPromptFinetuning']
model_class = {
'FOSGD': GLUETransformerFO,
'FOAdam': GLUETransformerFO,
'ZO': GLUETransformerMeZo,
'ZOSVRG': GLUETransformerMeZoSVRG,
'ZOAdam': GLUETransformerMeZoAdam,
'LOZO': GLUETransformerLoZo,
'HiZOO': GLUETransformerHiZOO,
'LOREN': GLUETransformerLOREN,
}
def get_model(args, dm):
glue_transformer = model_class[args.algorithm]
transformer = glue_transformer(
model_name_or_path=args.model_name,
num_labels=dm.num_labels,
eval_splits=dm.eval_splits,
task_name=dm.task_name,
learning_rate=args.lr_mezosvrg_mb if 'SVRG' in args.algorithm else args.lr,
learning_rate_aux=args.lr if 'SVRG' in args.algorithm else None,
lr_anneal=args.anneal,
full_parameter=args.full_parameter,
batchsize_limit=args.batchsize_limit,
zero_order_eps=args.perturbation_scale,
soft_prompt=args.soft_prompt,
use_SGD=True if 'SGD' in args.algorithm else False,
logger_type=args.logging,
hf_token=args.hf_token,
model_init_seed=args.init_seed,
q=args.q,
step_interval=args.step_interval,
rank=args.rank,
weight_decay=args.weight_decay,
eps=args.eps,
damping=args.damping,
lr_cov=args.lr_cov,
num_queries=args.num_queries,
clipping=args.clipping,
hessian_smooth_type=args.hessian_smooth_type,
num_epochs=args.epochs,
)
return transformer
+421
View File
@@ -0,0 +1,421 @@
import math
import os
import pickle
from typing import Optional
import lightning as L
import numpy as np
import torch
from common.logging import logger as logging
from transformers import (AutoConfig, AutoModelForSequenceClassification,
OPTForSequenceClassification, LlamaForSequenceClassification)
from .prompt_finetune import RobertaModelForPromptFinetuning
from .roberta import RobertaConfig
MODEL_NAME = "model.pt"
OPTIMIZER_NAME = "optimizer.pt"
DATA_MODULE_NAME = "data_module.pkl"
TRAIN_STATE_NAME = "train_state.pkl"
WANDB_INFO_NAME = "wandb_info.pkl"
STEP_INFO_NAME = "step_info.pkl"
class TrainState:
def __init__(self):
self.validation_step_outputs = []
self.tr_loss = []
self.tr_loss_minibatch = []
self.time = []
self.query = []
self.grad_norm = []
self.proj_val = []
self.z_grad = []
self.val_loss_ls = []
self.val_acc = []
self.lr_list = []
self.memory_usage = []
self.global_training_steps = 0
self.learning_rate = 0
self.learning_rate_aux = 0
self.full_grad = None
class GLUETransformer(L.LightningModule):
def __init__(
self,
model_name_or_path: str,
num_labels: int,
zero_order_eps: float = 1e-3,
learning_rate_aux: float = 1e-3,
minibatch: int = 64,
max_norm: float = 18000.0,
z_std: float = 1.0,
lr_anneal: float = 1.0,
full_parameter: bool = True,
batchsize_limit: int = 16,
eval_splits: Optional[list] = None,
soft_prompt: bool = False,
use_SGD: bool = True,
logger_type: str = 'wandb',
hf_token: Optional[str] = None,
lora: bool = False,
model_init_seed: Optional[int] = None,
num_queries: int = 2,
**kwargs,
):
super().__init__()
self.save_hyperparameters()
self.model_name = model_name_or_path
self.config = AutoConfig.from_pretrained(model_name_or_path, num_labels=num_labels)
self.soft_prompt = soft_prompt
self.lora = lora
if model_init_seed is not None:
original_seed = torch.initial_seed()
torch.manual_seed(model_init_seed)
if model_name_or_path == 'distilbert-base-cased' or model_name_or_path == 'roberta-large':
if self.soft_prompt is True and model_name_or_path == 'roberta-large':
config = RobertaConfig.from_pretrained(
'roberta-large',
num_labels=num_labels,
finetuning_task=self.hparams.task_name)
self.model = RobertaModelForPromptFinetuning.from_pretrained(
"roberta-large",
config=config
)
else:
self.model = AutoModelForSequenceClassification.from_pretrained(model_name_or_path, config=self.config)
elif 'gpt2' in model_name_or_path:
self.model = AutoModelForSequenceClassification.from_pretrained(model_name_or_path, config=self.config)
self.model.config.pad_token_id = self.model.config.eos_token_id
elif 'opt' in model_name_or_path:
self.model = OPTForSequenceClassification.from_pretrained(model_name_or_path, num_labels=num_labels)
elif 'llama' in model_name_or_path or self.config.model_type == 'llama':
self.model = LlamaForSequenceClassification.from_pretrained(model_name_or_path, config = self.config,
use_auth_token=True)
self.model.config.pad_token_id = self.model.config.eos_token_id
else:
raise NotImplementedError(f"Model {model_name_or_path} not supported yet.")
if model_init_seed is not None:
torch.manual_seed(original_seed)
logging.debug(self.model)
self.use_SGD = use_SGD
self.zero_order_eps = zero_order_eps
self.minibatch = minibatch
self.max_norm = max_norm
self.z_std = z_std
self.lr_anneal = lr_anneal
self.full_parameter = full_parameter
self.batchsize_limit = batchsize_limit
self.logger_type = logger_type
self.num_queries = num_queries
# train state
self.state = TrainState()
self.state.validation_step_outputs = []
self.state.tr_loss = []
self.state.tr_loss_minibatch = []
self.state.time = []
self.state.query = []
self.state.grad_norm = []
self.state.proj_val = []
self.state.z_grad = []
self.state.val_loss_ls = []
self.state.val_acc = []
self.state.lr_list = []
self.state.memory_usage = []
self.state.global_training_steps = 0
self.state.learning_rate = self.hparams.learning_rate
self.state.learning_rate_aux = learning_rate_aux
def forward(self, **inputs):
return self.model(**inputs)
def forward_ZO_val(self, inputs):
model = self.model
model.eval()
batch_size = inputs['input_ids'].shape[0]
iterations = math.ceil(batch_size/self.batchsize_limit)
loss_sum = 0
correct_sum = 0
total_samples = 0
for i in range(iterations):
input_batch = {}
for k, v in inputs.items():
input_batch[k] = v[i*self.batchsize_limit:min((i+1)*self.batchsize_limit, batch_size)]
with torch.no_grad():
outputs = model(**input_batch)
logits = outputs[1]
if self.hparams.num_labels > 1:
preds = torch.argmax(logits, axis=1)
elif self.hparams.num_labels == 1:
preds = logits.squeeze()
labels = input_batch["labels"]
correct_sum += (preds == labels).sum().item()
total_samples += len(labels)
loss_sum += outputs[0].float() * len(labels) # loss is averaged over samples
torch.cuda.empty_cache()
# freeing up memory
del input_batch, outputs, logits, preds
return loss_sum, correct_sum, total_samples
def configure_params(self):
model = self.model
if self.full_parameter:
self.params = [(n, p) for n, p in model.named_parameters()]
else:
raise NotImplementedError("partial optimization not supported yet.")
def configure_optimizers(self):
"""Prepare optimizer"""
model = self.model
if self.full_parameter:
self.params_to_opt = model.parameters()
else:
raise NotImplementedError("partial optimization not supported yet.")
if self.use_SGD:
optimizer = torch.optim.SGD(self.params_to_opt, lr=self.hparams.learning_rate)
else:
optimizer = torch.optim.Adam(self.params_to_opt, lr=self.hparams.learning_rate)
return optimizer
def training_step(self, batch, batch_idx):
outputs = self(**batch)
loss = outputs[0]
return {'loss': loss}
def on_train_batch_end(self, outputs, batch, batch_idx):
loss = outputs['loss']
self.state.tr_loss.append(loss.detach().cpu().float().numpy())
logging.info(f'train_loss : {loss.item():.4f}')
self.log('train_loss', loss.item())
self.measure_memory_usage()
def validation_step(self, batch, batch_idx, dataloader_idx=0):
outputs = self(**batch)
val_loss, logits = outputs[:2]
self.state.val_loss_ls.append(val_loss.detach().cpu().float().numpy())
if self.hparams.num_labels > 1:
preds = torch.argmax(logits, axis=1)
elif self.hparams.num_labels == 1:
preds = logits.squeeze()
labels = batch["labels"]
# Compute Validation Accuracy
correct_predictions = (preds == labels).sum().item()
total_samples = len(labels)
accuracy = correct_predictions / total_samples
self.state.val_acc.append(accuracy)
val_info = {"loss": val_loss, "preds": preds, "labels": labels}
self.state.validation_step_outputs.append(val_info)
return val_info
def on_validation_epoch_end(self):
if len(self.state.validation_step_outputs) == 0:
return
loss_sum = torch.stack(
[x['loss'] * len(x['labels']) for x in self.state.validation_step_outputs]
).sum()
val_preds = torch.cat([x['preds'] for x in self.state.validation_step_outputs])
val_labels = torch.cat([x['labels'] for x in self.state.validation_step_outputs])
avg_loss = loss_sum.item() / len(val_labels)
val_acc = (val_preds == val_labels).sum().item() / len(val_labels)
logging.info(f'val_loss: {avg_loss:.4f}, val_acc: {val_acc:.3f}')
self.log('val_loss', avg_loss)
self.log('val_acc', val_acc)
self.state.validation_step_outputs.clear()
return {"val_loss": avg_loss, "val_acc": val_acc}
@torch.no_grad()
def zo_forward_memory_eff(self, model, inputs):
model.eval()
batch_size = inputs['input_ids'].shape[0]
iterations = math.ceil(batch_size/self.batchsize_limit)
loss = 0.0
for i in range(iterations):
input_batch = {}
for k, v in inputs.items():
input_batch[k] = v[i*self.batchsize_limit:min((i+1)*self.batchsize_limit, batch_size)]
with torch.inference_mode():
outputs = model(**input_batch)
loss += outputs[0].float()
return loss / iterations
def zo_forward(self, model, inputs):
model.eval()
with torch.no_grad():
outputs = model(**inputs)
loss = outputs[0]
return loss.detach()
def efficient_perturb_parameters(self,
parameters,
random_seed: int,
uniform: bool = False,
use_beta: bool = False,
scaling_factor=1):
torch.manual_seed(random_seed)
e = self.beta if use_beta else self.zero_order_eps
for _, param in parameters:
if uniform:
# uniform distribution over unit sphere
z = torch.randn(size=param.data.size(), device=param.data.device, dtype=param.data.dtype)
z = z / torch.linalg.norm(z)
else:
z = torch.normal(mean=0, std=self.z_std, size=param.data.size(),
device=param.data.device, dtype=param.data.dtype)
param.data = param.data + scaling_factor * z * e
return
def efficient_perturb_parameters_layerwise(self,
parameters,
seed_list: list,
uniform: bool = False,
use_beta: bool = False,
scaling_factor=1):
# assert the same size of seed list and trainable parameters
assert len(seed_list) == len(parameters)
e = self.beta if use_beta else self.zero_order_eps
for (_, param), seed in zip(parameters, seed_list):
torch.manual_seed(seed)
if uniform:
# uniform distribution over unit sphere
z = torch.randn(size=param.data.size(), device=param.data.device, dtype=param.data.dtype)
z = z / torch.linalg.norm(z)
else:
z = torch.normal(mean=0, std=self.z_std, size=param.data.size(),
device=param.data.device, dtype=param.data.dtype)
param.data = param.data + scaling_factor * z * e
return
def log_training_loss(self, model, batch, fullbatch=False, tb_writer=None):
with torch.no_grad():
# loss computation
loss = self.zo_forward_memory_eff(model, batch)
if fullbatch:
logging.info(f"Fullbatch Train Loss : {loss:.3f}")
self.state.tr_loss.append(loss.detach().cpu().float().numpy())
if tb_writer is not None:
tb_writer.add_scalar("fb_train_loss", loss.item(), self.state.global_training_steps)
else:
logging.info(f"Minibatch Train Loss : {loss:.3f}")
self.state.tr_loss_minibatch.append(loss.detach().cpu().float().numpy())
if tb_writer is not None:
tb_writer.add_scalar("mb_train_loss", loss.item(), self.state.global_training_steps)
def forward_difference_grad_est(self, model, parameters, batch, uniform=False):
random_seed = np.random.randint(1000000000, size=1)
with torch.no_grad():
# first function evaluation
self.efficient_perturb_parameters(parameters, random_seed, uniform=uniform)
loss1 = self.zo_forward_memory_eff(model, batch)
# second function evaluation
self.efficient_perturb_parameters(parameters, random_seed, uniform=uniform, scaling_factor=-1)
loss2 = self.zo_forward_memory_eff(model, batch)
proj_grad = (loss1 - loss2)/self.zero_order_eps
self.state.proj_val.append(torch.abs(proj_grad).detach().cpu().float().numpy())
estimator = {}
torch.manual_seed(random_seed)
for name, param in parameters:
if uniform:
# uniform distribution over unit sphere
z = torch.randn(size=param.data.size(), device=param.data.device, dtype=param.data.dtype)
z = z / torch.linalg.norm(z)
else:
z = torch.normal(mean=0, std=self.z_std, size=param.data.size(), device=param.data.device, dtype=param.data.dtype)
estimator[name] = proj_grad*z
return estimator
def clip_gradients_dict(self, grad_dict):
"""Clip the gradients in a dictionary to a maximum norm."""
total_norm = 0
for param_name, grad in grad_dict.items():
total_norm += grad.norm(2) ** 2
total_norm = total_norm ** 0.5
logging.debug(f'Norm: {total_norm}')
self.state.grad_norm.append(total_norm)
clip_coef = self.state.max_norm / (total_norm + 1e-6)
if clip_coef < 1:
for param_name, grad in grad_dict.items():
grad_dict[param_name].mul_(clip_coef)
return grad_dict
def compute_grad_norm_zo(self, grad_dict):
"""Compute gradient norm."""
total_norm = 0
for param_name, grad in grad_dict.items():
total_norm += grad.norm(2) ** 2
total_norm = total_norm ** 0.5
logging.debug(f'Gradient Norm: {total_norm}')
self.state.grad_norm.append(total_norm)
def compute_grad_norm_fo(self, param):
total_norm = 0
for p in param:
if not p.detach().grad is None:
param_norm = p.detach().grad.data.norm(2)
total_norm += param_norm.item() ** 2
total_norm = total_norm ** (1. / 2)
logging.debug(f'Grad Norm: {total_norm}')
self.state.grad_norm.append(total_norm)
def get_average_tensors(self, tensor_list, n=50):
v1 = torch.stack(tensor_list[-n:]).mean(dim=0)
v2 = torch.stack(tensor_list[-2*n:-n]).mean(dim=0)
return v1, v2
def get_average_np(self, np_list, n=50):
ll = np.array(np_list)
v1 = np.mean(ll[-n:])
v2 = np.mean(ll[-3*n:-2*n])
return v1, v2
def measure_memory_usage(self):
device = next(self.model.parameters()).device
allocated_memory_bytes = torch.cuda.memory_reserved(device)
allocated_memory_gb = allocated_memory_bytes / (1024 ** 3)
self.state.memory_usage.append(allocated_memory_gb)
# logging.info(f'Memory usage (GB): {allocated_memory_gb:.2f}')
return allocated_memory_gb
def load_from_checkpoint(self, checkpoint_path: str):
self.model.load_state_dict(torch.load(os.path.join(checkpoint_path, MODEL_NAME)))
self.state = pickle.load(open(os.path.join(checkpoint_path, TRAIN_STATE_NAME), 'rb'))
def save_checkpoint(self, checkpoint_path: str):
os.makedirs(checkpoint_path, exist_ok=True)
torch.save(self.model.state_dict(), os.path.join(checkpoint_path, MODEL_NAME))
pickle.dump(self.state, open(os.path.join(checkpoint_path, TRAIN_STATE_NAME), 'wb'))
@@ -0,0 +1,64 @@
import time
import numpy as np
import torch
from .glue_transformer_mezo import GLUETransformerMeZo
class GLUETransformerMeZoAdam(GLUETransformerMeZo):
def zo_step(self, model, batch, random_seed):
"""
Zeroth-order gradient estimation
"""
# first function evaluation
self.perturb_parameters(random_seed, scaling_factor=1)
loss1 = self.zo_forward_memory_eff(model, batch)
# second function evaluation
self.perturb_parameters(random_seed, scaling_factor=-2)
loss2 = self.zo_forward_memory_eff(model, batch)
projected_grad = ((loss1 - loss2) / (2 * self.zero_order_eps)).item()
# model_dtype = next(self.model.parameters()).dtype
# projected_grad = projected_grad.to(model_dtype)
# reset model back to its parameters at start of step
self.perturb_parameters(random_seed, scaling_factor=1)
return loss1, projected_grad
def training_step(self, model, batch, tb_writer=None, **kwargs):
# run ZO update
num_grad_est = self.num_queries // 2
n = batch['input_ids'].size(0)
start_time = time.perf_counter()
random_seeds = [np.random.randint(1000000000) for _ in range(num_grad_est)]
optimizer = kwargs['optimizer']
log_dict = kwargs['log']
losses = []
for k in range(num_grad_est):
loss, projected_grad = self.zo_step(model, batch, random_seeds[k])
losses.append(loss.item())
mean_proj_grad = projected_grad / num_grad_est
# compute SPSA gradient estimator
torch.manual_seed(random_seeds[k])
for _, param in self.params:
param.grad = mean_proj_grad * torch.normal(mean=0, std=1, size=param.data.size(),
device=param.data.device,
dtype=param.data.dtype)
optimizer.step()
param.grad = None
lmean = np.mean(losses)
self.state.global_training_steps += 1
# logging
total_time = time.perf_counter() - start_time
self.state.time.append(total_time)
self.state.query.append(2*n*num_grad_est)
log_dict['train_loss'] = lmean.item()
log_dict['time'] = total_time
@@ -0,0 +1,32 @@
import time
import torch
from .glue_transformer import GLUETransformer
class GLUETransformerFO(GLUETransformer):
def __init__(self, *args, use_sgd=False, **kwargs):
super().__init__(*args, **kwargs)
self.use_sgd = use_sgd
def training_step(self, model, batch, tb_writer=None, **kwargs):
start_time = time.perf_counter()
optimizer = kwargs['optimizer']
log_dict = kwargs['log']
outputs = model(**batch)
loss = outputs[0]
optimizer.zero_grad()
loss.backward()
optimizer.step()
self.state.global_training_steps += 1
# Logging
total_time = time.perf_counter() - start_time
n = batch['input_ids'].size(0)
self.state.time.append(total_time)
self.state.query.append(n)
log_dict['train_loss'] = loss.item()
log_dict['time'] = total_time
@@ -0,0 +1,127 @@
import time
from typing import Optional
import numpy as np
import torch
from .glue_transformer_mezo import GLUETransformerMeZo
from common.hessian_smooth_scheduler import Hessian_smooth_scheduler
class GLUETransformerHiZOO(GLUETransformerMeZo):
def __init__(
self,
model_name_or_path: str,
num_labels: int,
zero_order_eps: float = 1e-3,
learning_rate_aux: float = 1e-3,
minibatch: int = 64,
max_norm: float = 18000.0,
z_std: float = 1.0,
lr_anneal: float = 1.0,
full_parameter: bool = True,
batchsize_limit: int = 16,
eval_splits: Optional[list] = None,
soft_prompt: bool = False,
use_SGD: bool = True,
logger_type: str = 'wandb',
hf_token: Optional[str] = None,
lora: bool = False,
model_init_seed: Optional[int] = None,
num_queries: int = 10,
weight_decay: float = 0.01,
hessian_smooth_type: str = "constant1e-8",
num_epochs: int = 3000,
**kwargs,
):
super().__init__(model_name_or_path,
num_labels,
zero_order_eps,
learning_rate_aux,
minibatch,
max_norm,
z_std,
lr_anneal,
full_parameter,
batchsize_limit,
eval_splits,
soft_prompt,
use_SGD,
logger_type,
hf_token,
lora,
model_init_seed)
self.Hessian_matrix = {}
self.hessian_smooth_type = hessian_smooth_type
self.num_epochs = num_epochs
self.num_queries = num_queries
self.weight_decay = weight_decay
def configure_params(self):
super().configure_params()
for name, param in self.params:
if param.requires_grad:
self.Hessian_matrix[name] = torch.ones(size=param.data.size(), device=param.data.device,
dtype=param.data.dtype)
@torch.no_grad()
def efficient_Hessian_perturb_parameters(self, random_seed: int, Hessian_matrix=None,
scaling_factor=1):
torch.manual_seed(random_seed)
for name, param in self.params:
z = torch.normal(mean=0, std=1, size=param.data.size(), device=param.data.device, dtype=param.data.dtype)
param.data = param.data + scaling_factor / torch.sqrt(Hessian_matrix[name]) * z * self.zero_order_eps
def zo_Hessian_step(self, model, batch, random_seed):
loss_original = self.zo_forward_memory_eff(model, batch)
self.efficient_Hessian_perturb_parameters(random_seed, self.Hessian_matrix, scaling_factor=1)
loss1 = self.zo_forward_memory_eff(model, batch)
self.efficient_Hessian_perturb_parameters(random_seed, self.Hessian_matrix, scaling_factor=-2)
loss2 = self.zo_forward_memory_eff(model, batch)
self.efficient_Hessian_perturb_parameters(random_seed, self.Hessian_matrix, scaling_factor=1)
return loss_original, loss1, loss2
def zo_Hessian_update(self, random_seed, loss_original, loss1, loss2, Hessian_smooth, num_grad_est):
torch.manual_seed(random_seed)
for name, param in self.params:
z = torch.normal(mean=0, std=1, size=param.data.size(), device=param.data.device,
dtype=param.data.dtype)
Hessian_temp = self.Hessian_matrix[name] * z * z
Hessian_estimator = (torch.abs(loss1 + loss2 - 2 * loss_original) * Hessian_temp * Hessian_smooth / (
2 * self.zero_order_eps * self.zero_order_eps))
self.Hessian_matrix[name] = ((1 - Hessian_smooth) * self.Hessian_matrix[name] + Hessian_estimator)
grad = (loss1 - loss2) / (2 * self.zero_order_eps) * z / torch.sqrt(self.Hessian_matrix[name])
grad = grad / num_grad_est
param.data = param.data - self.state.learning_rate * (grad + self.weight_decay * param.data)
def training_step(self, model, batch, tb_writer=None, **kwargs):
num_grad_est = self.num_queries // 3
n = batch['input_ids'].size(0)
start_time = time.perf_counter()
random_seeds = [np.random.randint(1000000000) for _ in range(num_grad_est)]
log_dict = kwargs['log']
Hessian_smooth = Hessian_smooth_scheduler(self.hessian_smooth_type, self.state.global_training_steps,
self.num_epochs)
losses = []
for k in range(num_grad_est):
loss_original, loss1, loss2 = self.zo_Hessian_step(model, batch, random_seeds[k])
losses.append(loss_original.item())
self.zo_Hessian_update(random_seeds[k], loss_original, loss1, loss2, Hessian_smooth, num_grad_est)
lmean = np.mean(losses)
self.state.global_training_steps += 1
# logging
total_time = time.perf_counter() - start_time
self.state.time.append(total_time)
self.state.query.append(3 * n * num_grad_est)
log_dict['train_loss'] = lmean.item()
log_dict['time'] = total_time
@@ -0,0 +1,159 @@
import math
import time
from typing import Optional
import numpy as np
import torch
from .glue_transformer_lozo import GLUETransformerLoZo
from common.alg_utils import sgd_with_wdecay
class GLUETransformerLOREN(GLUETransformerLoZo):
def __init__(
self,
model_name_or_path: str,
num_labels: int,
zero_order_eps: float = 1e-3,
learning_rate_aux: float = 1e-3,
minibatch: int = 64,
max_norm: float = 18000.0,
z_std: float = 1.0,
lr_anneal: float = 1.0,
full_parameter: bool = True,
batchsize_limit: int = 16,
eval_splits: Optional[list] = None,
soft_prompt: bool = False,
use_SGD: bool = True,
logger_type: str = 'wandb',
hf_token: Optional[str] = None,
lora: bool = False,
model_init_seed: Optional[int] = None,
weight_decay: float = 0.01,
damping: float = 0.1,
lr_cov: float = 2e-3,
beta1: float = 0.9,
num_queries: int = 10,
**kwargs,
):
super().__init__(model_name_or_path,
num_labels,
zero_order_eps,
learning_rate_aux,
minibatch,
max_norm,
z_std,
lr_anneal,
full_parameter,
batchsize_limit,
eval_splits,
soft_prompt,
use_SGD,
logger_type,
hf_token,
lora,
model_init_seed,
weight_decay)
self.damping = damping
self.lr_cov = lr_cov
self.d_sqrt = math.sqrt(damping)
self.evec_a = {}
self.momentum = {}
self.num_queries = num_queries
self.beta1 = beta1
self.param_info = {}
assert num_queries >= 2, 'At least 2 samples are required for RLOO estimation'
def configure_params(self):
super().configure_params()
for name, param in self.params:
param_shape = param.shape
param_flat_size = param.numel()
evec_size = param.size(1) if param.ndim >= 2 else param_flat_size
a = torch.randn(evec_size, device=param.device, dtype=param.dtype)
self.evec_a[name] = a
if param.ndim >= 2:
self.momentum[name] = torch.zeros_like(param)
self.param_info[name] = {
'shape': param_shape,
'flat_size': param_flat_size,
'evec_size': evec_size,
'mfactor': param_flat_size // evec_size
}
@torch.no_grad()
def perturb_parameters(self, random_seed: int, scaling_factor=1):
torch.manual_seed(random_seed)
for name, param in self.params:
info = self.param_info[name]
shape = info['shape']
a = self.evec_a[name]
a_flat = a.view(1, -1).expand(info['mfactor'], -1).reshape(-1)
u_vec = torch.randn_like(param).view(-1)
sq_norm_a = torch.dot(a_flat, a_flat)
dot_au = torch.dot(a_flat, u_vec)
damping_sq_norm_a = math.sqrt(self.damping + sq_norm_a.item())
alpha = (self.d_sqrt + damping_sq_norm_a) * dot_au / (sq_norm_a * damping_sq_norm_a)
sqrt_cov_u = u_vec.sub(alpha * a_flat).view(shape)
param.add_(sqrt_cov_u, alpha=scaling_factor * self.zero_order_eps)
@torch.no_grad()
def lnes_zo_update(self, random_seeds, fvals, fmean):
fweight = torch.tensor(fvals, device='cuda') - fmean
num_queries_inv = 1.0 / (self.num_queries - 1)
eps_inv = 1.0 / (self.zero_order_eps * (self.num_queries - 1))
for k in range(self.num_queries):
torch.manual_seed(random_seeds[k])
for name, param in self.params:
info = self.param_info[name]
shape = info['shape']
a = self.evec_a[name]
a_flat = a.view(1, -1).expand(info['mfactor'], -1).reshape(-1)
u_vec = torch.randn_like(param).view(-1)
sq_norm_a = torch.dot(a_flat, a_flat)
dot_au = torch.dot(a_flat, u_vec)
damping_sq_norm_a = math.sqrt(self.damping + sq_norm_a.item())
alpha = (self.d_sqrt + damping_sq_norm_a) * dot_au / (sq_norm_a * damping_sq_norm_a)
sqrt_cov_u = u_vec.sub(alpha * a_flat).view(shape)
gx = sqrt_cov_u.mul(fweight[k] * eps_inv)
if param.ndim >= 2:
self.momentum[name].mul_(self.beta1).add_(gx)
gx = self.momentum[name]
sgd_with_wdecay(param, gx, self.state.learning_rate, self.weight_decay)
c1 = (dot_au * u_vec - a_flat)
c2 = (self.d_sqrt + damping_sq_norm_a) * (dot_au ** 2 - sq_norm_a) * a_flat / (sq_norm_a * damping_sq_norm_a)
ak_grad = fweight[k] * (self.zero_order_eps ** 2) * (c1 - c2) / damping_sq_norm_a
ak_grad = ak_grad.view(shape).sum(0) * num_queries_inv
sgd_with_wdecay(self.evec_a[name], ak_grad, self.lr_cov, self.weight_decay)
def training_step(self, model, batch, tb_writer=None, **kwargs):
n = batch['input_ids'].size(0)
start_time = time.perf_counter()
random_seeds = [np.random.randint(1000000000) for _ in range(self.num_queries)]
log_dict = kwargs['log']
fvals = []
with torch.inference_mode():
for k in range(self.num_queries):
self.perturb_parameters(random_seeds[k], scaling_factor=1)
loss = self.zo_forward_memory_eff(model, batch)
fvals.append(loss.item())
self.perturb_parameters(random_seeds[k], scaling_factor=-1)
fmean = np.mean(fvals)
self.lnes_zo_update(random_seeds, fvals, fmean)
self.state.global_training_steps += 1
total_time = time.perf_counter() - start_time
self.state.time.append(total_time)
self.state.query.append(self.num_queries * n)
log_dict['train_loss'] = fmean.item()
log_dict['time'] = total_time
@@ -0,0 +1,145 @@
import time
from typing import Optional
import numpy as np
import torch
from .glue_transformer_mezo import GLUETransformerMeZo
class GLUETransformerLoZo(GLUETransformerMeZo):
def __init__(
self,
model_name_or_path: str,
num_labels: int,
zero_order_eps: float = 1e-3,
learning_rate_aux: float = 1e-3,
minibatch: int = 64,
max_norm: float = 18000.0,
z_std: float = 1.0,
lr_anneal: float = 1.0,
full_parameter: bool = True,
batchsize_limit: int = 16,
eval_splits: Optional[list] = None,
soft_prompt: bool = False,
use_SGD: bool = True,
logger_type: str = 'wandb',
hf_token: Optional[str] = None,
lora: bool = False,
model_init_seed: Optional[int] = None,
step_interval: int = 50, # subspace bases update interval in LoZo
rank: int = 2,
weight_decay: float = 0.01,
**kwargs,
):
super().__init__(model_name_or_path,
num_labels,
zero_order_eps,
learning_rate_aux,
minibatch,
max_norm,
z_std,
lr_anneal,
full_parameter,
batchsize_limit,
eval_splits,
soft_prompt,
use_SGD,
logger_type,
hf_token,
lora,
model_init_seed)
self.rank = rank
self.basis_upd_interval = step_interval
self.subspace_basis = {}
self.weight_decay = weight_decay
@torch.no_grad()
def lowrank_perturb_parameters(self, random_seed, scaling_factor=1, pos=None):
torch.manual_seed(random_seed)
for name, param in self.params:
if param.data.ndim >= 2:
V = self.subspace_basis[name]
U = torch.randn(param.data.size(0), self.rank,
device=param.data.device, dtype=param.data.dtype)
param.data = param.data + scaling_factor * (U @ V.t()) * self.zero_order_eps
else:
z = torch.normal(mean=0, std=self.z_std, size=param.data.size(),
device=param.data.device, dtype=param.data.dtype)
param.data = param.data + scaling_factor * z * self.zero_order_eps
def lowrank_zo_step(self, model, batch, random_seed, pos=None):
self.lowrank_perturb_parameters(random_seed, scaling_factor=1, pos=pos)
loss1 = self.zo_forward_memory_eff(model, batch)
# second function evaluation
self.lowrank_perturb_parameters(random_seed, scaling_factor=-2, pos=pos)
loss2 = self.zo_forward_memory_eff(model, batch)
projected_grad = ((loss1 - loss2) / (2 * self.zero_order_eps)).item()
# reset model back to its parameters at start of step
self.lowrank_perturb_parameters(random_seed, scaling_factor=1, pos=pos)
return loss1, projected_grad
@torch.no_grad()
def _gd_with_decay(self, name, param, grad):
if "bias" not in name and "layer_norm" not in name and "layernorm" not in name:
param.mul_(1.0 - self.state.learning_rate * self.weight_decay)
param.sub_(grad, alpha=self.state.learning_rate)
def lowrank_zo_update(self, random_seed, proj_grad):
torch.manual_seed(random_seed)
for name, param in self.params:
if param.data.ndim >= 2:
V = self.subspace_basis[name]
U = torch.randn(param.data.size(0), self.rank,
device=param.data.device, dtype=param.data.dtype)
grad = proj_grad * (U @ V.t())
else:
z = torch.normal(mean=0, std=1, size=param.data.size(),
device=param.data.device, dtype=param.data.dtype)
grad = proj_grad * z
self._gd_with_decay(name, param, grad)
def update_basis(self, sub_dim: int = 1):
for name, param in self.params:
if param.data.ndim >= 2:
self.subspace_basis[name] = torch.randn(param.data.size(sub_dim),
self.rank,
device=param.data.device,
dtype=param.data.dtype)
def training_step(self, model, batch, tb_writer=None, **kwargs):
num_grad_est = self.num_queries // 2
n = batch['input_ids'].size(0)
start_time = time.perf_counter()
random_seeds = [np.random.randint(1000000000) for _ in range(num_grad_est)]
log_dict = kwargs['log']
step = self.state.global_training_steps
if step % self.basis_upd_interval == 0:
self.update_basis(sub_dim=1)
losses = []
for k in range(num_grad_est):
loss, proj_grad = self.lowrank_zo_step(model, batch, random_seeds[k])
losses.append(loss.item())
mean_proj_grad = proj_grad / num_grad_est
self.lowrank_zo_update(random_seeds[k], mean_proj_grad)
lmean = np.mean(losses)
self.state.global_training_steps += 1
total_time = time.perf_counter() - start_time
self.state.time.append(total_time)
self.state.query.append(2*n*num_grad_est)
log_dict['train_loss'] = lmean.item()
log_dict['time'] = total_time
@@ -0,0 +1,75 @@
import time
import numpy as np
import torch
from .glue_transformer import GLUETransformer
class GLUETransformerMeZo(GLUETransformer):
def perturb_parameters(self, random_seed: int, scaling_factor=1):
torch.manual_seed(random_seed)
for name, param in self.params:
z = torch.normal(mean=0, std=self.z_std, size=param.data.size(),
device=param.data.device, dtype=param.data.dtype)
param.data = param.data + scaling_factor * z * self.zero_order_eps
def zo_step(self, model, batch, random_seed):
"""
Zeroth-order gradient estimation
"""
# first function evaluation
self.perturb_parameters(random_seed, scaling_factor=1)
loss1 = self.zo_forward_memory_eff(model, batch)
# second function evaluation
self.perturb_parameters(random_seed, scaling_factor=-2)
loss2 = self.zo_forward_memory_eff(model, batch)
projected_grad = ((loss1 - loss2) / (2 * self.zero_order_eps)).item()
# model_dtype = next(self.model.parameters()).dtype
# projected_grad = projected_grad.to(model_dtype)
# reset model back to its parameters at start of step
self.perturb_parameters(random_seed, scaling_factor=1)
return loss1, projected_grad
@torch.no_grad()
def zo_update(self, random_seed, projected_grad, scale=-1):
torch.manual_seed(random_seed)
# compute SPSA gradient estimator
for _, param in self.params:
u = torch.normal(mean=0, std=1, size=param.data.size(),
device=param.data.device, dtype=param.data.dtype)
param.data = param.data + scale * self.state.learning_rate * projected_grad * u
def training_step(self, model, batch, tb_writer=None, **kwargs):
# run ZO update
num_grad_est = self.num_queries // 2
n = batch['input_ids'].size(0)
start_time = time.perf_counter()
random_seeds = [np.random.randint(1000000000) for _ in range(num_grad_est)]
log_dict = kwargs['log']
losses = []
for k in range(num_grad_est):
loss, projected_grad = self.zo_step(model, batch, random_seeds[k])
losses.append(loss.item())
mean_proj_grad = projected_grad / num_grad_est
self.zo_update(random_seeds[k], mean_proj_grad)
lmean = np.mean(losses)
self.state.global_training_steps += 1
# logging
total_time = time.perf_counter() - start_time
self.state.time.append(total_time)
self.state.query.append(2*n*num_grad_est)
log_dict['train_loss'] = lmean.item()
log_dict['time'] = total_time
@@ -0,0 +1,182 @@
import logging
import time
from typing import Optional
import numpy as np
import torch
from .glue_transformer_mezo import GLUETransformerMeZo
class GLUETransformerMeZoSVRG(GLUETransformerMeZo):
def __init__(
self,
model_name_or_path: str,
num_labels: int,
zero_order_eps: float = 1e-3,
learning_rate_aux: float = 1e-3,
minibatch: int = 64,
max_norm: float = 18000.0,
z_std: float = 1.0,
lr_anneal: float = 1.0,
full_parameter: bool = True,
batchsize_limit: int = 16,
eval_splits: Optional[list] = None,
soft_prompt: bool = False,
use_SGD: bool = True,
logger_type: str = 'wandb',
hf_token: Optional[str] = None,
lora: bool = False,
model_init_seed: Optional[int] = None,
q: int = 1,
**kwargs,
):
super().__init__(
model_name_or_path,
num_labels,
zero_order_eps,
learning_rate_aux,
minibatch,
max_norm,
z_std,
lr_anneal,
full_parameter,
batchsize_limit,
eval_splits,
soft_prompt,
use_SGD,
logger_type,
hf_token,
lora,
model_init_seed)
self.q = q
def training_step(self, model, batch, tb_writer=None, **kwargs):
# run MeZO-SVRG update
n = batch['input_ids'].size(0)
logging.debug(f'Batch size: {n}')
start_time = time.perf_counter()
log_dict = kwargs['log']
# current iteration
curr_iter = kwargs['curr_iter']
total_batches = kwargs['full_batch_size']
w = 2 * total_batches
full_batch = kwargs['is_full_batch']
# learning rate scheduling strategy
if len(self.state.tr_loss_minibatch) > 2*w and curr_iter % total_batches == 0:
v1, v2 = self.get_average_np(self.state.tr_loss_minibatch, int(w/2))
logging.debug(f'leading average: {v1}')
logging.debug(f'trailing average: {v2}')
if v1/v2 > 1.05:
self.state.learning_rate_aux = max(self.state.learning_rate_aux/self.lr_anneal, 1e-5)
self.state.learning_rate = max(self.state.learning_rate/self.lr_anneal, 1e-6)
logging.debug(f'Learning rate (full-batch): {self.state.learning_rate_aux}')
logging.debug(f'Learning rate (mini-batch): {self.state.learning_rate}')
self.state.lr_list.append(self.state.learning_rate_aux)
# parameters contains tuples of params to optimize in list
parameters = self.params
# do full batch update every q steps
if full_batch is True:
self.state.full_grad = self.SPSA_estimator(model, parameters, batch)
self.parameters = parameters.copy()
with torch.no_grad():
for name, param in parameters:
param.data = param.data - self.state.learning_rate_aux * self.state.full_grad[name]
else:
# minibatch update
parameters = self.SPSA_estimator_me(model, parameters, batch, scale=-1) # in-place operation
parameters = self.SPSA_estimator_me(model, self.parameters, batch) # in-place operation
with torch.no_grad():
for name, param in parameters:
param.data = param.data - self.state.learning_rate * self.state.full_grad[name]
self.state.global_training_steps += 1
total_time = time.perf_counter() - start_time
self.state.time.append(total_time)
self.state.query.append(2*n)
with torch.no_grad():
# loss computation
loss = self.zo_forward_memory_eff(model, batch)
# self.log_training_loss(model, batch,
# fullbatch=True if curr_iter % self.q == 0 else False,
# tb_writer=tb_writer)
if full_batch:
self.state.tr_loss.append(loss.detach().cpu().float().numpy())
log_dict['fb_train_loss'] = loss.item()
else:
self.state.tr_loss_minibatch.append(loss.detach().cpu().float().numpy())
log_dict['train_loss'] = loss.item()
log_dict['time'] = total_time
# log_dict['memory'] = self.measure_memory_usage()
def SPSA_estimator(self, model, parameters, batch):
return self.central_difference_grad_est(model, parameters, batch)
def SPSA_estimator_me(self, model, parameters, batch, scale=1):
# memory efficient SPSA estimator
return self.central_difference_grad_est_me(model, parameters, batch, scale)
def central_difference_grad_est(self, model, parameters, batch, uniform=False):
random_seed = np.random.randint(1000000000, size=1)
with torch.no_grad():
# first function evaluation
self.efficient_perturb_parameters(parameters, random_seed, uniform=uniform)
loss1 = self.zo_forward_memory_eff(model, batch)
# second function evaluation
self.efficient_perturb_parameters(parameters, random_seed, uniform=uniform, scaling_factor=-2)
loss2 = self.zo_forward_memory_eff(model, batch)
proj_grad = (loss1 - loss2)/(2 * self.zero_order_eps)
model_dtype = next(self.model.parameters()).dtype
proj_grad = proj_grad.to(model_dtype)
logging.debug(f'Projected Grad: {proj_grad}')
self.state.proj_val.append(torch.abs(proj_grad).detach().cpu().float().numpy())
estimator = {}
self.efficient_perturb_parameters(parameters, random_seed, uniform=uniform)
torch.manual_seed(random_seed)
for name, param in parameters:
if uniform:
# uniform distribution over unit sphere
z = torch.randn(size=param.data.size(), device=param.data.device, dtype=param.data.dtype)
z = z / torch.linalg.norm(z)
else:
z = torch.normal(mean=0, std=self.z_std, size=param.data.size(),
device=param.data.device, dtype=param.data.dtype)
estimator[name] = proj_grad*z
return estimator
def central_difference_grad_est_me(self, model, parameters, batch, scale, uniform=False):
# memory efficient central difference spsa estimator
random_seed = np.random.randint(1000000000, size=1)
with torch.no_grad():
# first function evaluation
self.efficient_perturb_parameters(parameters, random_seed, uniform=uniform)
loss1 = self.zo_forward_memory_eff(model, batch)
# second function evaluation
self.efficient_perturb_parameters(parameters, random_seed, uniform=uniform, scaling_factor=-2)
loss2 = self.zo_forward_memory_eff(model, batch)
proj_grad = (loss1 - loss2)/(2 * self.zero_order_eps)
self.state.proj_val.append(torch.abs(proj_grad).detach().cpu().float().numpy())
self.efficient_perturb_parameters(parameters, random_seed, uniform=uniform)
torch.manual_seed(random_seed)
for name, param in parameters:
if uniform:
# uniform distribution over unit sphere
z = torch.randn(size=param.data.size(), device=param.data.device, dtype=param.data.dtype)
z = z / torch.linalg.norm(z)
else:
z = torch.normal(mean=0, std=self.z_std, size=param.data.size(),
device=param.data.device, dtype=param.data.dtype)
param.data = param.data + scale * self.state.learning_rate * proj_grad * z
return parameters
File diff suppressed because it is too large. Load diff
+503
View File
@@ -0,0 +1,503 @@
import random
import logging
from typing import List, Optional, Tuple, Union
import torch
import torch.nn as nn
import torch.nn.functional as F
from transformers.modeling_outputs import BaseModelOutputWithPast
from transformers.models.bert.modeling_bert import (BertModel, BertOnlyMLMHead,
BertPreTrainedModel)
from transformers.models.gpt2.modeling_gpt2 import GPT2LMHeadModel
from transformers.models.llama.modeling_llama import LlamaPreTrainedModel, LlamaForCausalLM
from .opt import OPTDecoder, OPTForCausalLM, OPTModel
from .roberta import RobertaLMHead, RobertaModel, RobertaPreTrainedModel
logger = logging.getLogger(__name__)
def model_for_prompting_forward(
model,
input_ids=None,
attention_mask=None,
token_type_ids=None,
mask_pos=None,
labels=None,
sfc_input_ids=None,
sfc_attention_mask=None,
sfc_mask_pos=None
):
if sfc_input_ids is not None:
with torch.no_grad():
logits = model_for_prompting_forward(model, input_ids=sfc_input_ids,
attention_mask=sfc_attention_mask,
mask_pos=sfc_mask_pos)[0]
# icl_sfc_bias = F.log_softmax(logits.detach().squeeze(0))
if mask_pos is not None:
mask_pos = mask_pos.squeeze()
model_fn = model.get_model_fn()
# Encode everything
if token_type_ids is not None:
outputs = model_fn(
input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids
)
else:
outputs = model_fn(
input_ids,
attention_mask=attention_mask,
)
# Get <mask> token representation
sequence_output = outputs[0]
if mask_pos is not None:
sequence_mask_output = sequence_output[torch.arange(sequence_output.size(0)), mask_pos]
else:
sequence_mask_output = sequence_output[:, 0] # <cls> representation
# sequence_mask_output = sequence_output.mean(dim=1) # average representation
if model.label_word_list is not None:
# Logits over vocabulary tokens
head_fn = model.get_lm_head_fn()
prediction_mask_scores = head_fn(sequence_mask_output)
# Exit early and only return mask logits.
if model.return_full_softmax:
if labels is not None:
return torch.zeros(1, out=prediction_mask_scores.new()), prediction_mask_scores
return prediction_mask_scores
# Return logits for each label
logits = []
# use MLM logit
if model.model_args.use_task_word:
vocab_logits = model.lm_head(sequence_mask_output)
for _id in model.label_word_list:
logits.append(vocab_logits[:, _id].unsqueeze(-1))
# use learned linear head logit on top of task word representation (standard LM-BFF)
else:
for label_id in range(len(model.label_word_list)):
logits.append(prediction_mask_scores[:, model.label_word_list[label_id]].unsqueeze(-1))
logits = torch.cat(logits, -1)
# Regression task
if model.config.num_labels == 1:
logsoftmax = nn.LogSoftmax(-1)
logits = logsoftmax(logits) # Log prob of right polarity
else:
logits = model.classifier(sequence_mask_output)
loss = None
if labels is not None:
if model.config.num_labels == 1:
# Regression task
if model.label_word_list is not None:
labels = torch.stack([1 - (labels.view(-1) - model.lb) / (model.ub - model.lb), (labels.view(-1) - model.lb) / (model.ub - model.lb)], -1)
loss = nn.KLDivLoss(log_target=True)(logits.view(-1, 2), labels)
else:
labels = (labels.float().view(-1) - model.lb) / (model.ub - model.lb)
loss = nn.MSELoss()(logits.view(-1), labels)
else:
# print('logits', logits.shape)
# print('labels', labels.shape)
# if model.model_args.l2_loss:
# coords = torch.nn.functional.one_hot(labels.squeeze(), model.config.num_labels).float()
# loss = nn.MSELoss()(logits.view(-1, logits.size(-1)), coords)
# else:
loss = nn.CrossEntropyLoss()(logits.view(-1, logits.size(-1)), labels.view(-1))
# print('loss', loss)
if hasattr(model, "lr_weight"):
# Linear head
logits = torch.matmul(F.softmax(logits, -1), model.lr_weight)
if hasattr(model, "lr_bias"):
logits += model.lr_bias.unsqueeze(0)
# if model.model_args.sfc and hasattr(model, "sfc_bias"):
# logits = F.log_softmax(logits, -1) - model.sfc_bias
# if sfc_input_ids is not None:
# logits = F.log_softmax(logits, -1) - icl_sfc_bias
output = (logits,)
# if model.model_args.use_task_word and model.num_labels == 1:
# # Regression output
# output = (torch.exp(logits[..., 1].unsqueeze(-1)) * (model.ub - model.lb) + model.lb,)
return ((loss,) + output) if loss is not None else output
def convert_opt_model(model: OPTModel, config, num_exclude_layers):
model.model.decoder = EfficientOPTDecoder(config, num_exclude_layers)
return model
class BertModelForPromptFinetuning(BertPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.num_labels = config.num_labels
print(config)
self.model_type = config.model_type
self.bert = BertModel(config)
self.cls = BertOnlyMLMHead(config)
self.classifier = nn.Linear(config.hidden_size, self.num_labels)
self.init_weights()
# These attributes should be assigned once the model is initialized
self.model_args, self.data_args, self.label_word_list = None, None, None
# For regression
self.lb, self.ub = 0.0, 1.0
# For auto label search.
self.return_full_softmax = None
def get_model_fn(self):
return self.bert
def get_lm_head_fn(self):
return self.cls
def forward(self, input_ids=None, attention_mask=None, token_type_ids=None, mask_pos=None, labels=None):
return model_for_prompting_forward(self, input_ids, attention_mask, token_type_ids, mask_pos, labels)
class RobertaModelForPromptFinetuning(RobertaPreTrainedModel):
def __init__(self, config):
super().__init__(config)
logger.warn("By default for RoBERTa models the input embeddings and the output embeddings "
"are NOT tied!!!!")
self.num_labels = config.num_labels
print(config)
self.model_type = config.model_type
self.roberta = RobertaModel(config)
self.lm_head = RobertaLMHead(config)
self.classifier = nn.Linear(config.hidden_size, self.num_labels)
self.init_weights()
# These attributes should be assigned once the model is initialized
self.model_args, self.data_args, self.label_word_list = None, None, None
# For regression
self.lb, self.ub = 0.0, 1.0
# For auto label search.
self.return_full_softmax = None
def tie_emb(self):
output_embeddings = self.lm_head.decoder
self._tie_or_clone_weights(output_embeddings, self.roberta.get_input_embeddings())
def get_model_fn(self):
return self.roberta
def get_lm_head_fn(self):
return self.lm_head
def forward(self, input_ids=None, attention_mask=None, token_type_ids=None, mask_pos=None, labels=None):
return model_for_prompting_forward(self, input_ids, attention_mask, token_type_ids, mask_pos, labels)
class OPTModelForPromptFinetuning(OPTForCausalLM):
def __init__(self, config):
super().__init__(config)
logger.warn("By default for OPT models the input embeddings and the output embeddings are tied!!!!")
self.num_labels = config.num_labels
print(config)
self.model_type = config.model_type
# self.model = OPTModel(config)
# self.lm_head = nn.Linear(config.word_embed_proj_dim, config.vocab_size, bias=False)
# self.classifier = nn.Linear(config.hidden_size, self.num_labels)
# self.init_weights()
# These attributes should be assigned once the model is initialized
self.model_args, self.data_args, self.label_word_list = None, None, None
# For regression
self.lb, self.ub = 0.0, 1.0
# For auto label search.
self.return_full_softmax = None
def get_model_fn(self):
return self.model
def get_lm_head_fn(self):
return self.lm_head
def forward(self, input_ids=None, attention_mask=None, token_type_ids=None, mask_pos=None,
labels=None, sfc_input_ids=None, sfc_attention_mask=None, sfc_mask_pos=None):
return model_for_prompting_forward(self, input_ids, attention_mask, token_type_ids,
mask_pos, labels, sfc_input_ids=sfc_input_ids,
sfc_attention_mask=sfc_attention_mask,
sfc_mask_pos=sfc_mask_pos)
class GPT2ModelForPromptFinetuning(GPT2LMHeadModel):
def __init__(self, config):
super().__init__(config)
raise NotImplementedError("Need to check if the lm head is properly loaded and whether it is tied.")
self.num_labels = config.num_labels
print(config)
self.model_type = config.model_type
# self.transformer = GPT2Model(config)
# self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
self.classifier = nn.Linear(config.hidden_size, self.num_labels)
self.init_weights()
# These attributes should be assigned once the model is initialized
self.model_args, self.data_args, self.label_word_list = None, None, None
# For regression
self.lb, self.ub = 0.0, 1.0
# For auto label search.
self.return_full_softmax = None
def get_model_fn(self):
return self.transformer
def get_lm_head_fn(self):
return self.lm_head
def forward(self, input_ids=None, attention_mask=None, token_type_ids=None, mask_pos=None, labels=None):
return model_for_prompting_forward(self, input_ids, attention_mask, token_type_ids, mask_pos, labels)
class LlamaModelForPromptFinetuning(LlamaPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.num_labels = config.num_labels
self.model_type = config.model_type
self.base_model = LlamaForCausalLM.from_pretrained(config._name_or_path, config=config)
self.model_args = None
self.data_args = None
self.label_word_list = None
self.lb, self.ub = 0.0, 1.0
self.return_full_softmax = None
# self.classifier = nn.Linear(config.hidden_size, config.num_labels)
# self.init_weights()
def get_model_fn(self):
return self.base_model.model.forward
def get_lm_head_fn(self):
return lambda hidden: self.base_model.lm_head(hidden)
def forward(self, input_ids=None, attention_mask=None,
token_type_ids=None, mask_pos=None, labels=None,
sfc_input_ids=None, sfc_attention_mask=None, sfc_mask_pos=None):
return model_for_prompting_forward(
self,
input_ids, attention_mask, token_type_ids,
mask_pos, labels,
sfc_input_ids=sfc_input_ids,
sfc_attention_mask=sfc_attention_mask,
sfc_mask_pos=sfc_mask_pos,
)
class EfficientOPTDecoder(OPTDecoder):
def __init__(self, config, num_exclude):
super().__init__(config)
self.num_exclude = num_exclude # number of initial layers to operate with torch.no_grad
def forward(
self,
input_ids: torch.LongTensor = None,
attention_mask: Optional[torch.Tensor] = None,
head_mask: Optional[torch.Tensor] = None,
past_key_values: Optional[List[torch.FloatTensor]] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
use_cache: Optional[bool] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
) -> Union[Tuple, BaseModelOutputWithPast]:
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
output_hidden_states = (
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
)
use_cache = use_cache if use_cache is not None else self.config.use_cache
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
# retrieve input_ids and inputs_embeds
if input_ids is not None and inputs_embeds is not None:
raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
elif input_ids is not None:
input_shape = input_ids.size()
input_ids = input_ids.view(-1, input_shape[-1])
elif inputs_embeds is not None:
input_shape = inputs_embeds.size()[:-1]
else:
raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0
if inputs_embeds is None:
inputs_embeds = self.embed_tokens(input_ids)
# embed positions
if attention_mask is None:
attention_mask = torch.ones(inputs_embeds.shape[:2], dtype=torch.bool, device=inputs_embeds.device)
pos_embeds = self.embed_positions(attention_mask, past_key_values_length)
attention_mask = self._prepare_decoder_attention_mask(
attention_mask, input_shape, inputs_embeds, past_key_values_length
)
if self.project_in is not None:
inputs_embeds = self.project_in(inputs_embeds)
hidden_states = inputs_embeds + pos_embeds
# decoder layers
all_hidden_states = () if output_hidden_states else None
all_self_attns = () if output_attentions else None
next_decoder_cache = () if use_cache else None
# check if head_mask has a correct number of layers specified if desired
for attn_mask, mask_name in zip([head_mask], ["head_mask"]):
if attn_mask is not None:
if attn_mask.size()[0] != (len(self.layers)):
raise ValueError(
f"The `{mask_name}` should be specified for {len(self.layers)} layers, but it is for"
f" {head_mask.size()[0]}."
)
# run first few layers without grad
with torch.no_grad():
for idx, decoder_layer in enumerate(self.layers[:self.num_exclude]):
# add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
if output_hidden_states:
all_hidden_states += (hidden_states,)
dropout_probability = random.uniform(0, 1)
if self.training and (dropout_probability < self.layerdrop):
continue
past_key_value = past_key_values[idx] if past_key_values is not None else None
if self.gradient_checkpointing and self.training:
if use_cache:
logger.warning(
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
)
use_cache = False
def create_custom_forward(module):
def custom_forward(*inputs):
# None for past_key_value
return module(*inputs, output_attentions, None)
return custom_forward
layer_outputs = torch.utils.checkpoint.checkpoint(
create_custom_forward(decoder_layer),
hidden_states,
attention_mask,
head_mask[idx] if head_mask is not None else None,
None,
)
else:
layer_outputs = decoder_layer(
hidden_states,
attention_mask=attention_mask,
layer_head_mask=(head_mask[idx] if head_mask is not None else None),
past_key_value=past_key_value,
output_attentions=output_attentions,
use_cache=use_cache,
)
hidden_states = layer_outputs[0]
if use_cache:
next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
if output_attentions:
all_self_attns += (layer_outputs[1],)
# rest of the layers with grad
for idx, decoder_layer in enumerate(self.layers[self.num_exclude:]):
# add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
if output_hidden_states:
all_hidden_states += (hidden_states,)
dropout_probability = random.uniform(0, 1)
if self.training and (dropout_probability < self.layerdrop):
continue
past_key_value = past_key_values[idx] if past_key_values is not None else None
if self.gradient_checkpointing and self.training:
if use_cache:
logger.warning(
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
)
use_cache = False
def create_custom_forward(module):
def custom_forward(*inputs):
# None for past_key_value
return module(*inputs, output_attentions, None)
return custom_forward
layer_outputs = torch.utils.checkpoint.checkpoint(
create_custom_forward(decoder_layer),
hidden_states,
attention_mask,
head_mask[idx] if head_mask is not None else None,
None,
)
else:
layer_outputs = decoder_layer(
hidden_states,
attention_mask=attention_mask,
layer_head_mask=(head_mask[idx] if head_mask is not None else None),
past_key_value=past_key_value,
output_attentions=output_attentions,
use_cache=use_cache,
)
hidden_states = layer_outputs[0]
if use_cache:
next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
if output_attentions:
all_self_attns += (layer_outputs[1],)
if self.final_layer_norm is not None:
hidden_states = self.final_layer_norm(hidden_states)
if self.project_out is not None:
hidden_states = self.project_out(hidden_states)
# add hidden states from the last decoder layer
if output_hidden_states:
all_hidden_states += (hidden_states,)
next_cache = next_decoder_cache if use_cache else None
if not return_dict:
return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
return BaseModelOutputWithPast(
last_hidden_state=hidden_states,
past_key_values=next_cache,
hidden_states=all_hidden_states,
attentions=all_self_attns,
)
File diff suppressed because it is too large. Load diff
+71
View File
@@ -0,0 +1,71 @@
"""Run the original entry point with shared local assets. No optimizer rewrite."""
import argparse
from datetime import datetime,timezone
import json
import os
from pathlib import Path
import runpy
import sys
HERE=Path(__file__).resolve().parent
ROOT=HERE.parents[1]
sys.path.insert(0,str(ROOT/'src'))
from experiments_codebase.paths import paths,model_path,save
def main():
p=argparse.ArgumentParser(description=__doc__,add_help=False)
p.add_argument('--asset-model',default='facebook/opt-1.3b')
p.add_argument('--asset-task',choices=['sst2','drop'],default='sst2')
p.add_argument('--asset-out',type=Path)
args,rest=p.parse_known_args();method=HERE.name
roots=paths();os.environ.setdefault('WANDB_MODE','disabled');os.environ['WANDB_DIR']=str(roots['results']/'wandb')
out=(args.asset_out or roots['results']/f'native_{method}_{datetime.now(timezone.utc):%Y%m%dT%H%M%S%fZ}').resolve()
if not out.is_relative_to(roots['results'].resolve()):raise ValueError('Output must be under shared results')
# Both local datasets are supplied through the HF Dataset API expected by authors.
import datasets
original=datasets.load_dataset
def local_dataset(name,*pos,**kw):
config=pos[0] if pos else kw.get('name')
alias='sst2' if (name in ('glue','nyu-mll/glue') and config=='sst2') or name=='sst2' else ('drop' if name in ('drop','ucinlp/drop') else None)
if alias:
ds=datasets.load_from_disk(str(roots['data']/alias))
split=kw.get('split');return ds[split] if split else ds
return original(name,*pos,**kw)
datasets.load_dataset=local_dataset
model=str(model_path(args.asset_model))
if method=='loren':
if args.asset_task=='drop':raise ValueError('Official LOREN has no DROP task; use run_compatible.py with the modern group for a labeled task extension')
if 'Qwen' in args.asset_model:raise ValueError('Official LOREN has no Qwen model branch; use the modern compatibility entry')
entry=HERE/'main.py'
defaults=['--model_name',model,'--task',args.asset_task,'--algorithm','LOREN','--results',str(out),'--full_parameter']
else:
work=HERE/('zo-bench' if method=='agzo' else 'large_models')
entry=work/('run_lozo.py' if method=='lozo' else 'run.py')
task='SST2' if args.asset_task=='sst2' else 'DROP'
defaults=['--model_name',model,'--task_name',task,'--output_dir',str(out),'--trainer',{'mezo':'zo','lozo':'LOZO','agzo':'agzo'}[method],
'--report_to','none','--train_set_seed','42','--train_as_classification',str(task=='SST2'),'--lr_scheduler_type','constant']
defaults+=['--result_file',str(out/'result.json')]
# User's original HF/author flags appear last and override wrapper defaults.
if '--help' not in rest:
out.mkdir(parents=True,exist_ok=False)
save(out/'launch.json',dict(method=method,entry=str(entry),argv=defaults+rest,executable=sys.executable,adapter='Local assets and paths only; original Trainer/optimizer',pid=os.getpid()))
sys.path.insert(0,str(entry.parent));os.chdir(out if out.exists() else HERE)
sys.argv=[str(entry),*defaults,*rest]
if method=='agzo':
import torch
if torch.cuda.is_available() and not hasattr(torch,'npu'):
# The author's NPU helper has incomplete CUDA branches. Only device
# plumbing is adapted; trainer.py and AGZO numerical methods are intact.
import npu_compat as devices
devices.device_count=torch.cuda.device_count
devices.mem_get_info=torch.cuda.mem_get_info
devices.get_active_device_info=lambda:('cuda',torch.cuda.current_device(),torch.cuda.get_device_properties(0).total_memory/2**30,torch.cuda.get_device_name())
devices.safe_set_device=lambda index:(torch.cuda.set_device(int(index or 0)) or int(index or 0),torch.cuda.device_count())
devices.to_device=lambda tensor:tensor.cuda()
source=entry.read_text().replace('torch.npu.manual_seed_all(seed)','torch.cuda.manual_seed_all(seed)').replace('torch.npu.device_count()','torch.cuda.device_count()')
if out.exists():save(out/'compatibility_changes.json',{'scope':'CUDA device plumbing only','source_modified_on_disk':False,'numerical_optimizer_modified':False,'changes':['NPU seed -> CUDA seed','NPU device count -> CUDA count','device helper memory/info/count/set/to_device CUDA callbacks']})
exec(compile(source,str(entry),'exec'),dict(__name__='__main__',__file__=str(entry)))
return
runpy.run_path(str(entry),run_name='__main__')
if __name__=='__main__':main()
+14
View File
@@ -0,0 +1,14 @@
[project]
name = "official-loren-experiment"
version = "0.1.0"
requires-python = ">=3.11,<3.12"
dependencies = ["torch==2.13.0", "loguru==0.7.3", "setuptools==80.9.0", "numpy==1.26.4", "matplotlib==3.10.7", "psutil==7.1.3", "scikit-learn==1.7.2", "sentencepiece==0.2.1", "wandb==0.23.1", "rouge==1.0.1", "nltk==3.9.2", "einops==0.8.1", "lightning==2.5.6", "torchmetrics==1.8.2", "loralib==0.1.2", "tensorboard==2.20.0", "tensorboardX==2.6.4", "peft==0.13.2", "termcolor==3.2.0", "bitsandbytes==0.48.2"]
[dependency-groups]
native = ["transformers==4.44.2", "datasets==2.21.0", "pyarrow==17.0.0", "accelerate==1.12.0", "huggingface-hub==0.36.0"]
modern = ["transformers==4.57.1", "datasets==3.6.0", "pyarrow==20.0.0", "accelerate==1.12.0", "huggingface-hub==0.36.0"]
[tool.uv]
package = false
default-groups = ["native"]
conflicts = [[{group="native"}, {group="modern"}]]
+17
View File
@@ -0,0 +1,17 @@
numpy
datasets
lightning
matplotlib
scikit-learn
scipy
torch
torchmetrics
transformers
torchvision
loralib
wandb
tensorboard
tensorboardX
peft
termcolor
bitsandbytes
+7
View File
@@ -0,0 +1,7 @@
"""Modern task adapter calling pinned official numerical methods; not the original Trainer."""
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[2] / 'src'))
from experiments_codebase.runner import main
if __name__ == '__main__':
main(forced_method='loren')
+5
View File
@@ -0,0 +1,5 @@
from .train_loop import finetune_ZO
from .train_loop import finetune_FO
__all__ = ['finetune_ZO', 'finetune_FO']
+219
View File
@@ -0,0 +1,219 @@
import numpy as np
import torch
import lightning as L
from lightning.pytorch import Trainer
from common.logging import logger as logging
def reset_log_dict(log_dict):
log_dict['train_loss'] = 0.0
log_dict['val_loss'] = 0.0
log_dict['val_acc'] = 0.0
log_dict['time'] = 0.0
#log_dict['memory'] = 0.0
def finetune_FO(args,
device: torch.device,
dm: L.LightningDataModule,
transformer: L.LightningModule, tb_writer=None):
train_dataloader = dm.train_dataloader()
val_dataloader = dm.val_dataloader()
log_dict = {}
if args.bf16:
transformer.to(torch.bfloat16)
model = transformer.model.to(device)
transformer.configure_params()
optimizer = transformer.configure_optimizers()
transformer.model.eval()
if args.early_stopping:
best_val_acc = 0
patience_counter = 0
global_step = 0
for epoch in range(args.epochs):
log_dict['epoch'] = epoch
if (epoch + 1) % args.eval_every == 0:
# validation loop
reset_log_dict(log_dict)
val_loss_sums, val_correct, total_val_samples = [], 0, 0
for batch in val_dataloader:
b = {k: v.to(device) for k, v in batch.items()}
loss_sum, correct, total_samples = transformer.forward_ZO_val(b)
val_loss_sums.append(loss_sum.item())
val_correct += correct
total_val_samples += total_samples
val_loss_mean = np.sum(val_loss_sums) / total_val_samples
val_acc = val_correct / total_val_samples * 100.0
log_dict['val_loss'] = val_loss_mean
log_dict['val_acc'] = val_acc
if args.early_stopping:
if val_acc >= best_val_acc:
best_val_acc = val_acc
patience_counter = 0
else:
patience_counter += 1
log_dict["best_val_acc"] = best_val_acc
tb_writer.log_metrics(log_dict, step=global_step)
if args.early_stopping and patience_counter >= args.patience:
logging.info(
f"Early stopping at epoch {epoch+1}. Best validation accuracy: {best_val_acc}"
)
break
# training loop
transformer.model.train()
train_loss = 0.0
for batch_idx, batch in enumerate(train_dataloader):
reset_log_dict(log_dict)
b = {k: v.to(device) for k, v in batch.items()}
optimizer.zero_grad()
outputs = model(**b)
loss = outputs[0]
loss.backward()
alloc_mem = transformer.measure_memory_usage()
optimizer.step()
train_loss += loss.item()
global_step += 1
log_dict['train_loss'] = loss.item()
log_dict['time'] = 0.0 # or measure if you like
if tb_writer:
tb_writer.log_metrics(log_dict, step=global_step)
logging.info(f"[{epoch + 1:}] val_loss: {val_loss_mean:.5f}, val_acc: {val_acc:.3f}, "
f"mem: {alloc_mem:.5f}")
avg_train_loss = train_loss / len(train_dataloader)
logging.info(f'Avg. train loss: {avg_train_loss:.5f}')
if args.logging == "tensorboard" and tb_writer is not None:
tb_writer.close()
def finetune_ZO(args,
device: torch.device,
dm: L.LightningDataModule,
transformer: L.LightningModule, tb_writer=None):
train_dataloader = dm.train_dataloader()
val_dataloader = dm.val_dataloader()
log_dict = {}
kwargs = {'log': log_dict}
if args.bf16:
transformer.to(torch.bfloat16)
model = transformer.model.to(device)
# Algorithm-specific routines
if args.algorithm == 'ZOSVRG':
total_batches = len(train_dataloader)
fb_train_loader = dm.train_full_dataloader()
kwargs['full_batch_size'] = total_batches
elif args.algorithm == 'ZOAdam':
if args.low_bit_adam == 8:
import bitsandbytes as bnb
optimizer = bnb.optim.Adam8bit(model.parameters(),
lr=args.lr,
eps=args.eps,
weight_decay=0)
else:
optimizer = torch.optim.Adam(model.parameters(), lr=args.lr, eps=args.eps)
kwargs['optimizer'] = optimizer
transformer.configure_params()
transformer.model.eval()
if args.early_stopping:
best_val_acc = 0
patience_counter = 0
for epoch in range(args.epochs):
log_dict['epoch'] = epoch
if (epoch + 1) % args.eval_every == 0:
# validation loop
reset_log_dict(log_dict)
val_loss_sums, val_correct, total_val_samples = [], 0, 0
for batch in val_dataloader:
b = {k: v.to(device) for k, v in batch.items()}
loss_sum, correct, total_samples = transformer.forward_ZO_val(b)
val_loss_sums.append(loss_sum.item())
val_correct += correct
total_val_samples += total_samples
val_loss_mean = np.sum(val_loss_sums) / total_val_samples
val_acc = val_correct / total_val_samples * 100.0
log_dict['val_loss'] = val_loss_mean
log_dict['val_acc'] = val_acc
if args.early_stopping:
if val_acc >= best_val_acc:
best_val_acc = val_acc
patience_counter = 0
else:
patience_counter += 1
log_dict["best_val_acc"] = best_val_acc
tb_writer.log_metrics(log_dict, step=transformer.state.global_training_steps)
if args.early_stopping and patience_counter >= args.patience:
logging.info(
f"Early stopping at epoch {epoch+1}. Best validation accuracy: {best_val_acc}"
)
break
# training loop
transformer.model.train()
train_loss = 0.0
for batch_idx, batch in enumerate(train_dataloader):
reset_log_dict(log_dict)
if args.algorithm == 'ZOSVRG':
curr_iter = epoch * total_batches + batch_idx
kwargs['curr_iter'] = curr_iter
if (curr_iter % args.q) == 0:
batch = next(iter(fb_train_loader))
kwargs['is_full_batch'] = True
else:
kwargs['is_full_batch'] = False
b = {k: v.to(device) for k, v in batch.items()}
transformer.training_step(model, b, tb_writer=tb_writer, **kwargs)
if kwargs.get('is_full_batch', False):
train_loss += log_dict.get('fb_train_loss', 0.0)
else:
train_loss += log_dict.get('train_loss', 0.0)
if tb_writer:
tb_writer.log_metrics(log_dict, step=transformer.state.global_training_steps)
alloc_mem = transformer.measure_memory_usage()
logging.info(f"[{epoch + 1:}] val_loss: {val_loss_mean:.5f}, val_acc: {val_acc:.3f}, "
f"mem: {alloc_mem:.5f}")
train_loss /= len(train_dataloader)
logging.info(f'Avg. train loss: {train_loss:.5f}')
if args.logging == "tensorboard" and tb_writer is not None:
tb_writer.close()
+1941
View File
File diff suppressed because it is too large. Load diff