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

+161
View File
@@ -0,0 +1,161 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
lp_models/
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
.pybuilder/
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# PEP 582; used by e.g. github.com/David-OConnor/pyflow
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# pytype static type analyzer
.pytype/
# Cython debug symbols
cython_debug/
*.sh
.venv
.vscode
data
log*
runs
result
wandb
ensemble_predict_results
auto*
my*
slurm
tmp
display.py
llm_eval/result
llm_eval/display_result.py
llm_eval/data
*.ipynb
*.output
*.pdf
+1
View File
@@ -0,0 +1 @@
3.11.15
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2021 Princeton Natural Language Processing
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.
+48
View File
@@ -0,0 +1,48 @@
# MeZO: Fine-Tuning Language Models with Just Forward Passes
This is the implementation for the paper [Fine-Tuning Language Models with Just Forward Passes](https://arxiv.org/pdf/2305.17333.pdf).
In this paper we propose a memory-efficient zeroth-order optimizer (**MeZO**),
adapting the classical zeroth-order SGD method to operate in-place, thereby fine-tuning language models (LMs) with the same memory footprint as inference.
With a single A100 80GB GPU, MeZO can train a 30-billion parameter OPT model, whereas fine-tuning with Adam can train only a 2.7B LM.
MeZO demonstrates comparable performance to fine-tuning with backpropagation across multiple tasks, with up to 12× memory reduction. MeZO is also compatible with both full-parameter and parameter-efficient tuning techniques such as LoRA and prefix tuning. We also show that MeZO can effectively optimize non-differentiable objectives (e.g., maximizing accuracy or F1).
<p>
<img src="https://github.com/princeton-nlp/MeZO/blob/main/assets/fig2.png?raw=true" alt="Fig" width="100%"/>
<em>
GPU memory usage comparison between zero-shot, in-context learning (ICL), Adam fine-tuning (FT), and our proposed MeZO.
</em>
</p>
<p>
<img src="https://github.com/princeton-nlp/MeZO/blob/main/assets/fig1.png?raw=true" alt="Fig" width="100%"/>
<em>
OPT-13B results with zero-shot, in-context learning (ICL), MeZO (we report the best among MeZO/MeZO (LoRA)/MeZO (prefix)), and fine-tuning with Adam (FT). MeZO demonstrates superior results over zero-shot and ICL and performs on par with FT (within 1%) on 7 out of 11 tasks, despite using only 1/12 memory.
</em>
</p>
## Reproduce our paper results
For reproducing RoBERTa-large experiments, please refer to the [medium_models](https://github.com/princeton-nlp/MeZO/tree/main/medium_models) folder. For autoregressive LM (OPT) experiments, please refer to the [large_models](https://github.com/princeton-nlp/MeZO/tree/main/large_models) folder. If you want to learn more about how MeZO works and how we implement it, we recommend you to read the [large_models](https://github.com/princeton-nlp/MeZO/tree/main/large_models) folder as the implementation is clearer and more extensible. If you want to explore more variants of MeZO, we recommend trying out [medium_models](https://github.com/princeton-nlp/MeZO/tree/main/medium_models) as it's faster and has more variants implemented.
## How to add MeZO to my own code?
Our implementation of MeZO is based on [HuggingFace's Trainer](https://github.com/huggingface/transformers/blob/main/src/transformers/trainer.py). We add MeZO to the official implementation of trainer with minimum editing. Please refer to "How to add MeZO to my own code?" section in [large_models](https://github.com/princeton-nlp/MeZO/tree/main/large_models) README for more details.
## Bugs or questions?
If you have any questions related to the code or the paper, feel free to email Sadhika (`[email protected]`) or Tianyu (`[email protected]`). If you encounter any problems when using the code, or want to report a bug, you can open an issue. Please try to specify the problem with details so we can help you better and quicker!
## Citation
```bibtex
@article{malladi2023mezo,
title={Fine-Tuning Large Language Models with Just Forward Passes},
author={Malladi, Sadhika and Gao, Tianyu and Nichani, Eshaan and Damian, Alex and Lee, Jason D and Chen, Danqi and Arora, Sanjeev},
year={2023}
}
```
+81
View File
@@ -0,0 +1,81 @@
# MEZO:独立环境、入口与排障
官方来源:https://github.com/princeton-nlp/MeZO.git;锁定提交:`552cb1b710767f9a6e1dc8f9645d7640376f9941`。
官方文件保留原样;此目录新增 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/mezo
uv sync --locked
uv run --locked python native.py --help
```
此目录 `.venv` 独立,Python 3.11,torch 2.13.0,原生 Transformers 4.28.1。
直接依赖精确版本写在 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` 绕开锁。
## 官方入口及命令
原入口 `large_models/run.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 --max_steps 2 --num_train 16 --num_dev 4 --num_eval 4 --per_device_train_batch_size 2 --learning_rate 1e-6 --zo_eps 1e-3 --evaluation_strategy no --save_strategy no --logging_steps 1
```
调参请使用官方参数:学习率 `--learning_rate`,差分半径 `--zo_eps`,batch `--per_device_train_batch_size`。
参数覆盖: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 ...` 推理。
## 核心位置
- 核心算法:`large_models/trainer.py: zo_step / zo_update`。
- 模型/数据:`large_models/run.py: Framework; large_models/tasks.py / templates.py`。
- 官方超参数原型:入口中的参数 dataclass/parser 与原始 shell 脚本;与本站兼容入口参数不是同一命名空间。
## 系统组件与常见问题
原始 Transformers 4.28.1 不认识 Qwen3;Qwen3 必须使用 modern 依赖组和兼容入口。不要在原生环境单独升级 Transformers,这会破坏旧 Trainer 私有接口。
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` 通过不代表训练通过,短步通过也不代表论文精度复现。未完成项目会明确记录。
Binary file not shown.

After

Width:  |  Height:  |  Size: 145 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 178 KiB

+75
View File
@@ -0,0 +1,75 @@
# MeZO on Large Autoregressive Language Models
This part of the code is for MeZO experiments on large autoregressive language models. It includes training autoregressive LMs with linear probing, head tuning, full fine-tuning, parameter-efficient fine-tuning (PEFT), and MeZO. It also covers zero-shot and in-context learning (ICL) evaluation. It is tested on OPT-13B, 30B, and 66B but should be able to extend to other sizes and other autoregressive LMs.
## Installation
Please install the latest versions of PyTorch (`pytorch` following [https://pytorch.org](https://pytorch.org)), Transformers (`transformers`), and Accelerate (`accelerate`). This code is tested on `torch==2.1.0.dev20230514+cu118`, `transformers==4.28.1`, and `accelerate==0.17.1` with Python 3.9.7, but should work with older/later versions of these packages too.
## Usage
Use `run.py` for all functions (zero-shot/ICL/fine-tuning/MeZO):
```bash
python run.py {ARGUMENTS}
```
Please read `run.py` for a complete list of arguments. We introduce some of the most important ones below.
* `--num_train`: Number of training examples. For ICL, this is the number of demonstrations.
* `--num_dev`: Number of validation examples.
* `--num_test`: Number of testing examples.
* `--model_name`: HuggingFace model name or path.
* `--task_name`: Task name.
* `--trainer`: can be `none` (zero-shot/ICL), `regular` (fine-tuning), or `zo` (MeZO).
* `--train_as_classification`: turn this on for classification tasks (Cross Entropy over likelihood of each class' label words). Otherwise it is LM-style teacher forcing.
* `--zo_eps`: MeZO hyperparameter epsilon.
* `--prefix_tuning`: use prefix-tuning.
* `--lora`: use LoRA.
We also support all [HuggingFace trainer arguments](https://github.com/huggingface/transformers/blob/main/src/transformers/training_args.py) for easily setting fine-tuning hyperparameters.
We provide example scripts below for reproducing our experiments. All our examples sample 1,000 training examples, 500 validation examples, and 1,000 testing examples. For ICL, we use 32 demonstrations. For detailed hyperparameters and grid search configs, please refer to Appendix D of [our paper](https://arxiv.org/pdf/2305.17333.pdf).
```bash
# Zero-shot
MODEL=facebook/opt-13b TASK=SST2 bash icl.sh --num_train 0
# In-context learning
MODEL=facebook/opt-13b TASK=SST2 bash icl.sh
# Full-parameter fine-tuning, prefix-tuning, and LoRA
MODEL=facebook/opt-1.3b TASK=SST2 MODE=ft LR=1e-5 bash finetune.sh
MODEL=facebook/opt-1.3b TASK=SST2 MODE=prefix LR=1e-2 bash finetune.sh
MODEL=facebook/opt-1.3b TASK=SST2 MODE=lora LR=1e-4 bash finetune.sh
# Full-parameter fine-tuning using fully-sharded data parallel or FSDP (multi-GPU)
MODEL=facebook/opt-13b TASK=SST2 MODE=ft LR=1e-5 NUM_GPU=4 bash finetune_fsdp.sh
# MeZO (full-parameter, prefix-tuning, and LoRA)
MODEL=facebook/opt-13b TASK=SST2 MODE=ft LR=1e-7 EPS=1e-3 bash mezo.sh
MODEL=facebook/opt-13b TASK=SST2 MODE=prefix LR=1e-3 EPS=1e-1 bash mezo.sh
MODEL=facebook/opt-13b TASK=SST2 MODE=lora LR=5e-5 EPS=1e-2 bash mezo.sh
# MeZO with non-differentiable objective (SQuAD (F1) + MeZO prefix as an example)
MODEL=facebook/opt-13b TASK=SQuAD MODE=prefix LR=1e-2 EPS=1e-1 bash mezo.sh --non_diff --evaluation_strategy no --save_strategy no --save_model
```
Note that `icl.sh` and `mezo.sh` automatically support multi-GPU usage. For fine-tuning, use `finetune_fsdp.sh` for multi-GPU training and specific `NUM_GPU`. Evaluation results (json format) and checkpoints (HuggingFace format) will be saved in `result` folder.
Our recommended hyperparameter search range for OPT-13b (should also work for other sizes/models) are as follows,
| MeZO methods | LR | EPS |
| ------------- | ------------ | --- |
| Full parameter | 1e-6/1e-7 | 1e-3 |
| Prefix-tuning | 1e-2/1e-3 | 1e-1 |
| LoRA | 1e-4/5e-5 | 1e-2 |
## How to add MeZO to my own code?
Our implementation of MeZO is based on [HuggingFace Trainer](https://github.com/huggingface/transformers/blob/main/src/transformers/trainer.py). We try to add MeZO to the official implementation of trainer with minimum editing. Please refer to `trainer.py` for details. We edit the `_inner_training_loop` function (to see where we edited, search `MeZO added`; ignore the linear probing part) to replace the original optimizer with MeZO, which contains the following operations:
* `zo_perturb_parameters`: our in-place parameter perturbation function.
* `zo_forward` and `zo_forward_nondiff`: get loss value (differentiable/non-differentiable).
* `zo_step`: estimate the gradient by MeZO
* `zo_update`: update parameters by the estimated gradient.
To incorporate MeZO in your own HuggingFace code, simply overload HuggingFace's `Trainer` class and edit `_inner_training_loop` as we did in `trainer.py`, and add the above MeZO functions from `trainer.py` in your trainer. For a more intuitive explanation of the MeZO algorithm, please refer to Algorithm 1 in [our paper](https://arxiv.org/pdf/2305.17333.pdf).
File diff suppressed because it is too large. Load diff
+147
View File
@@ -0,0 +1,147 @@
import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
import torch
from torch import nn
from torch.nn import functional as F
import math
def find_module(root_module: nn.Module, key: str):
"""
Find a module with a specific name in a Transformer model
From OpenDelta https://github.com/thunlp/OpenDelta
"""
sub_keys = key.split(".")
parent_module = root_module
for sub_key in sub_keys[:-1]:
parent_module = getattr(parent_module, sub_key)
module = getattr(parent_module, sub_keys[-1])
return parent_module, sub_keys[-1], module
class LoRALinear(nn.Linear):
"""
LoRA implemented in a dense layer
From https://github.com/microsoft/LoRA/blob/main/loralib/layers.py
"""
def __init__(
self,
in_features: int,
out_features: int,
r: int = 0,
lora_alpha: int = 1,
lora_dropout: float = 0.,
fan_in_fan_out: bool = False, # Set this to True if the layer to replace stores weight like (fan_in, fan_out)
merge_weights: bool = False, # Not sure if this will affect saving/loading models so just set it to be False
**kwargs
):
nn.Linear.__init__(self, in_features, out_features, **kwargs)
self.r = r
self.lora_alpha = lora_alpha
# Optional dropout
if lora_dropout > 0.:
self.lora_dropout = nn.Dropout(p=lora_dropout)
else:
self.lora_dropout = lambda x: x
# Mark the weight as unmerged
self.merged = False
self.merge_weights = merge_weights
self.fan_in_fan_out = fan_in_fan_out
# Actual trainable parameters
if r > 0:
self.lora_A = nn.Parameter(self.weight.new_zeros((r, in_features)))
self.lora_B = nn.Parameter(self.weight.new_zeros((out_features, r)))
self.scaling = self.lora_alpha / self.r
# Freezing the pre-trained weight matrix
self.weight.requires_grad = False
self.reset_parameters()
if fan_in_fan_out:
self.weight.data = self.weight.data.transpose(0, 1)
def reset_parameters(self):
nn.Linear.reset_parameters(self)
if hasattr(self, 'lora_A'):
# initialize A the same way as the default for nn.Linear and B to zero
nn.init.kaiming_uniform_(self.lora_A, a=math.sqrt(5))
nn.init.zeros_(self.lora_B)
def train(self, mode: bool = True):
def T(w):
return w.transpose(0, 1) if self.fan_in_fan_out else w
nn.Linear.train(self, mode)
if mode:
if self.merge_weights and self.merged:
# Make sure that the weights are not merged
if self.r > 0:
self.weight.data -= T(self.lora_B @ self.lora_A) * self.scaling
self.merged = False
else:
if self.merge_weights and not self.merged:
# Merge the weights and mark it
if self.r > 0:
self.weight.data += T(self.lora_B @ self.lora_A) * self.scaling
self.merged = True
def forward(self, x: torch.Tensor):
def T(w):
return w.transpose(0, 1) if self.fan_in_fan_out else w
if self.r > 0 and not self.merged:
result = F.linear(x, T(self.weight), bias=self.bias)
if self.r > 0:
result += (self.lora_dropout(x) @ self.lora_A.transpose(0, 1) @ self.lora_B.transpose(0, 1)) * self.scaling
return result
else:
return F.linear(x, T(self.weight), bias=self.bias)
class LoRA:
def __init__(self, model, r, alpha, float16):
"""
Input:
r, alpha: LoRA hyperparameters
float16: Whether the model parameters are float16 or not
"""
self.model = model
self.hidden_dim = model.config.hidden_size
self.float16 = float16
if model.config.model_type == "opt":
attention_name = "attn"
elif model.config.model_type == "roberta":
attention_name = "attention"
else:
raise NotImplementedError
# Insert LoRA
for key, _ in model.named_modules():
if key[-len(attention_name):] == attention_name:
logger.info(f"Inject lora to: {key}")
_, _, attn = find_module(model, key)
if model.config.model_type == "opt":
original_q_weight = attn.q_proj.weight.data
original_q_bias = attn.q_proj.bias.data
original_v_weight= attn.v_proj.weight.data
original_v_bias = attn.v_proj.bias.data
attn.q_proj = LoRALinear(model.config.hidden_size, model.config.hidden_size, r=r, lora_alpha=alpha, bias=model.config.enable_bias).to(original_q_weight.device)
attn.v_proj = LoRALinear(model.config.hidden_size, model.config.hidden_size, r=r, lora_alpha=alpha, bias=model.config.enable_bias).to(original_v_weight.device)
if float16:
attn.q_proj.half()
attn.v_proj.half()
attn.q_proj.weight.data = original_q_weight
attn.q_proj.bias.data = original_q_bias
attn.v_proj.weight.data = original_v_weight
attn.v_proj.bias.data = original_v_bias
else:
raise NotImplementedError
# Freeze non-LoRA parameters
for n, p in model.named_parameters():
if "lora" not in n:
p.requires_grad = False
+78
View File
@@ -0,0 +1,78 @@
import numpy as np
import collections
import re
import string
from collections import Counter
def normalize_answer(s):
"""Lower text and remove punctuation, articles and extra whitespace."""
def remove_articles(text):
return re.sub(r'\b(a|an|the)\b', ' ', text)
def white_space_fix(text):
return ' '.join(text.split())
def remove_punc(text):
exclude = set(string.punctuation)
return ''.join(ch for ch in text if ch not in exclude)
def lower(text):
return text.lower()
return white_space_fix(remove_articles(remove_punc(lower(s))))
def calculate_metric(predictions, metric_name):
if metric_name == "accuracy":
if isinstance(predictions[0].correct_candidate, list):
return np.mean([pred.predicted_candidate in pred.correct_candidate for pred in predictions])
else:
return np.mean([pred.correct_candidate == pred.predicted_candidate for pred in predictions])
elif metric_name == "em":
# For question answering
return np.mean([any([normalize_answer(ans) == normalize_answer(pred.predicted_candidate) for ans in pred.correct_candidate]) for pred in predictions])
elif metric_name == "f1":
# For question answering
f1 = []
for pred in predictions:
all_f1s = []
if pred.correct_candidate[0] == "CANNOTANSWER" or pred.correct_candidate[0] == "no answer":
f1.append(int(normalize_answer(pred.correct_candidate[0]) == normalize_answer(pred.predicted_candidate)))
else:
for ans in pred.correct_candidate:
prediction_tokens = normalize_answer(pred.predicted_candidate).split()
ground_truth_tokens = normalize_answer(ans).split()
common = Counter(prediction_tokens) & Counter(ground_truth_tokens)
num_same = sum(common.values())
if num_same == 0:
all_f1s.append(0)
else:
precision = 1.0 * num_same / len(prediction_tokens)
recall = 1.0 * num_same / len(ground_truth_tokens)
all_f1s.append((2 * precision * recall) / (precision + recall))
f1.append(max(all_f1s))
return np.mean(f1)
def f1(pred, gold):
"""
This separate F1 function is used as non-differentiable metric for SQuAD
"""
if gold[0] == "CANNOTANSWER" or gold[0] == "no answer":
return int(normalize_answer(gold[0]) == normalize_answer(pred))
else:
all_f1s = []
for ans in gold:
prediction_tokens = normalize_answer(pred).split()
ground_truth_tokens = normalize_answer(ans).split()
common = Counter(prediction_tokens) & Counter(ground_truth_tokens)
num_same = sum(common.values())
if num_same == 0:
all_f1s.append(0)
else:
precision = 1.0 * num_same / len(prediction_tokens)
recall = 1.0 * num_same / len(ground_truth_tokens)
all_f1s.append((2 * precision * recall) / (precision + recall))
return np.max(all_f1s)
+200
View File
@@ -0,0 +1,200 @@
import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
import torch
from torch import nn
def find_module(root_module: nn.Module, key: str):
"""
Find a module with a specific name in a Transformer model
From OpenDelta https://github.com/thunlp/OpenDelta
"""
sub_keys = key.split(".")
parent_module = root_module
for sub_key in sub_keys[:-1]:
parent_module = getattr(parent_module, sub_key)
module = getattr(parent_module, sub_keys[-1])
return parent_module, sub_keys[-1], module
def attn_forward_hook(self, *args, **kwargs):
"""
Replace the original attention forward with this to enable prefix
"""
def _expand_bsz(x, bsz):
x = x.reshape(x.size(0), self.num_heads, -1).transpose(0,1) # (num_prefix, hidden) -> (num_head, num_prefix, hidden/num_head)
x = x.unsqueeze(0).expand(bsz, *x.shape) # -> (bsz, num_head, num_prefix, hidden/num_head)
return x
if "hidden_states" in kwargs:
hidden_states = kwargs["hidden_states"]
else:
hidden_states = args[0]
bsz = hidden_states.size(0)
if 'past_key_value' not in kwargs or kwargs['past_key_value'] is None:
if self.reparam:
prefix_keys = self.prefix_mlp_keys(self.prefix_input_embeds)
prefix_values = self.prefix_mlp_values(self.prefix_input_embeds)
else:
prefix_keys, prefix_values = self.prefix_keys, self.prefix_values
kwargs['past_key_value'] = (_expand_bsz(prefix_keys, bsz), _expand_bsz(prefix_values, bsz))
if 'attention_mask' in kwargs and kwargs['attention_mask'] is not None:
am = kwargs['attention_mask']
kwargs['attention_mask'] = torch.cat([-torch.zeros((*am.shape[:-1], self.num_prefix), dtype=am.dtype, device=am.device), am], dim=-1)
elif len(args) > 1: # attention mask is passed via positional argument
am = args[1]
am = torch.cat([-torch.zeros((*am.shape[:-1], self.num_prefix), dtype=am.dtype, device=am.device), am], dim=-1)
args = (args[0], am) + args[2:]
return self.original_forward(*args, **kwargs)
def prepare_inputs_for_generation(
self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs):
"""
Replace the original "prepare_inputs_for_generation" with this to pass prefix correctly
"""
original_input_len = input_ids.size(-1)
if past_key_values:
input_ids = input_ids[:, -1:]
# if `inputs_embeds` are passed, we only want to use them in the 1st generation step
if inputs_embeds is not None and past_key_values is None:
model_inputs = {"inputs_embeds": inputs_embeds}
else:
model_inputs = {"input_ids": input_ids}
if past_key_values is not None:
# Check if we should add extra to attention mask
if past_key_values[0][0].size(2) != attention_mask.size(1) - 1:
num_prefix = past_key_values[0][0].size(2) - (attention_mask.size(1) - 1)
attention_mask = torch.cat([torch.ones((attention_mask.size(0), num_prefix), dtype=attention_mask.dtype, device=attention_mask.device), attention_mask], dim=-1)
model_inputs.update(
{
"past_key_values": past_key_values,
"use_cache": kwargs.get("use_cache"),
"attention_mask": attention_mask,
}
)
return model_inputs
class PrefixTuning:
def __init__(self, model, num_prefix, reparam=True, embed_dim=512, mid_dim=512, float16=False, init_by_real_act=False):
"""
Inputs:
num_prefix: number of prefix tokens
reparam: use reparameterization trick (not used in MeZO)
embed_dim, mid_dim: hyperparameters for reparameterization trick (not used in MeZO)
float15: whether the model parameters are float15
init_by_real_act: init prefix tokens by real activations
"""
self.model = model
self.num_prefix = num_prefix
self.hidden_dim = model.config.hidden_size
self.float16 = float16
# Reparameterization
self.reparam = reparam
self.embed_dim = embed_dim
self.mid_dim = mid_dim
input_embeds = None # For reparameterization
if model.config.model_type == "opt":
attention_name = "attn"
first_layer_name = "layers.0"
layer_name = "layers."
elif model.config.model_type == "roberta":
attention_name = "attention"
first_layer_name = "layer.0"
layer_name = "layer."
elif model.config.model_type == "llama":
attention_name = "self_attn"
first_layer_name = "layers.0"
layer_name = "layers."
else:
raise NotImplementedError
if init_by_real_act:
# Initialize prefix with real words' activations
assert not reparam
# Randomly sample input tokens
input_tokens = torch.randint(low=0, high=model.config.vocab_size, size=(1, num_prefix), dtype=torch.long).cuda()
if model.config.model_type in ["opt", "llama"]:
with torch.no_grad():
# Get the real activations
real_key_values = model(input_ids=input_tokens, use_cache=True).past_key_values
else:
raise NotImplementedError
# Insert prefix
for key, _ in model.named_modules():
if key[-len(attention_name):] == attention_name:
layer_id = int(key.split(layer_name)[1].split(".")[0])
logger.info(f"Inject prefix to: {key}")
_, _, attn = find_module(model, key)
# Replace the old forward functions
attn.original_forward = attn.forward
attn.forward = attn_forward_hook.__get__(attn, type(attn))
if not hasattr(attn, "num_heads"):
attn.num_heads = model.config.num_attention_heads
first = first_layer_name in key
self.add_prefix(attn, first=first, input_embeds=input_embeds)
if first and self.reparam:
input_embeds = attn.prefix_input_embeds
if init_by_real_act:
logger.info(f"Reinitialize with actual activation: {key} (layer {layer_id})")
keys = real_key_values[layer_id][0].squeeze(0).transpose(0, 1).reshape(num_prefix, -1)
values = real_key_values[layer_id][1].squeeze(0).transpose(0, 1).reshape(num_prefix, -1)
attn.prefix_keys.data = keys.to(attn.prefix_keys.data.device)
attn.prefix_values.data = values.to(attn.prefix_values.data.device)
# Freeze non-prefix parameters
for n, p in model.named_parameters():
if "prefix" not in n:
p.requires_grad = False
# Replace the old prepare_inputs_for_generation function
model.prepare_inputs_for_generation = prepare_inputs_for_generation.__get__(model, type(model))
def add_prefix(self, module, first, input_embeds=None):
device = module.k_proj.weight.data.device
module.num_prefix = self.num_prefix
module.reparam = self.reparam
if self.reparam:
if first:
# For the first layer we inject the embeddings
logger.info("For prefix+reparameterization, inject the embeddings in the first layer.")
module.prefix_input_embeds = nn.Parameter(torch.randn(self.num_prefix, self.embed_dim, device=device, dtype=self.model.dtype), requires_grad=True)
else:
assert input_embeds is not None
module.prefix_input_embeds = input_embeds
module.prefix_mlp_keys = nn.Sequential(
nn.Linear(self.embed_dim, self.mid_dim),
nn.Tanh(),
nn.Linear(self.mid_dim, self.hidden_dim)
).to(device)
module.prefix_mlp_values = nn.Sequential(
nn.Linear(self.embed_dim, self.mid_dim),
nn.Tanh(),
nn.Linear(self.mid_dim, self.hidden_dim)
).to(device)
if self.float16:
module.prefix_mlp_keys = module.prefix_mlp_keys.half()
module.prefix_mlp_values = module.prefix_mlp_values.half()
else:
module.prefix_keys = nn.Parameter(torch.randn(self.num_prefix, self.hidden_dim, device=device, dtype=self.model.dtype), requires_grad=True)
module.prefix_values = nn.Parameter(torch.randn(self.num_prefix, self.hidden_dim, device=device, dtype=self.model.dtype), requires_grad=True)
+527
View File
@@ -0,0 +1,527 @@
import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
import argparse
import time
import tasks
from transformers import AutoConfig, AutoTokenizer, AutoModelForCausalLM, Trainer, HfArgumentParser, Trainer, TrainingArguments, DataCollatorWithPadding, DataCollatorForTokenClassification
from typing import Union, Optional
import torch
from torch.nn.parameter import Parameter
import numpy as np
from dataclasses import dataclass, is_dataclass, asdict
from tqdm import tqdm
from tasks import get_task
import json
import torch.nn.functional as F
from torch.utils.data import Dataset
from torch.distributed.fsdp.fully_sharded_data_parallel import FullyShardedDataParallel as FSDP
from metrics import calculate_metric
from utils import *
from trainer import OurTrainer
import random
@dataclass
class OurArguments(TrainingArguments):
# dataset and sampling strategy
task_name: str = "SST2" # task name should match the string before Dataset in the Dataset class name. We support the following task_name: SST2, RTE, CB, BoolQ, WSC, WIC, MultiRC, Copa, ReCoRD, SQuAD, DROP
# Number of examples
num_train: int = 0 # ICL mode: number of demonstrations; training mode: number of training samples
num_dev: int = None # (only enabled with training) number of development samples
num_eval: int = None # number of evaluation samples
num_train_sets: int = None # how many sets of training samples/demos to sample; if None and train_set_seed is None, then we will sample one set for each evaluation sample
train_set_seed: int = None # designated seed to sample training samples/demos
result_file: str = None # file name for saving performance; if None, then use the task name, model name, and config
# Model loading
model_name: str = "facebook/opt-125m" # HuggingFace model name
load_float16: bool = False # load model parameters as float16
load_bfloat16: bool = False # load model parameters as bfloat16
load_int8: bool = False # load model parameters as int8
max_length: int = 2048 # max length the model can take
no_auto_device: bool = False # do not load model by auto device; should turn this on when using FSDP
# Calibration
sfc: bool = False # whether to use SFC calibration
icl_sfc: bool = False # whether to use SFC calibration for ICL samples
# Training
trainer: str = "none"
## options
## - none: no training -- for zero-shot or in-context learning (ICL)
## - regular: regular huggingface trainer -- for fine-tuning
## - zo: zeroth-order (MeZO) training
only_train_option: bool = True # whether to only train the option part of the input
train_as_classification: bool = False # take the log likelihood of all options and train as classification
# MeZO
zo_eps: float = 1e-3 # eps in MeZO
# Prefix tuning
prefix_tuning: bool = False # whether to use prefix tuning
num_prefix: int = 5 # number of prefixes to use
no_reparam: bool = True # do not use reparameterization trick
prefix_init_by_real_act: bool = True # initialize prefix by real activations of random words
# LoRA
lora: bool = False # whether to use LoRA
lora_alpha: int = 16 # alpha in LoRA
lora_r: int = 8 # r in LoRA
# Generation
sampling: bool = False # whether to use sampling
temperature: float = 1.0 # temperature for generation
num_beams: int = 1 # number of beams for generation
top_k: int = None # top-k for generation
top_p: float = 0.95 # top-p for generation
max_new_tokens: int = 50 # max number of new tokens to generate
eos_token: str = "\n" # end of sentence token
# Saving
save_model: bool = False # whether to save the model
no_eval: bool = False # whether to skip evaluation
tag: str = "" # saving tag
# Linear probing
linear_probing: bool = False # whether to do linear probing
lp_early_stopping: bool = False # whether to do early stopping in linear probing
head_tuning: bool = False # head tuning: only tune the LM head
# Untie emb/lm_head weights
untie_emb: bool = False # untie the embeddings and LM head
# Display
verbose: bool = False # verbose output
# Non-diff objective
non_diff: bool = False # use non-differentiable objective (only support F1 for SQuAD for now)
# Auto saving when interrupted
save_on_interrupt: bool = False # save model when interrupted (useful for long training)
def parse_args():
parser = argparse.ArgumentParser()
parser = HfArgumentParser(OurArguments)
args = parser.parse_args_into_dataclasses()[0]
print(args)
return args
def set_seed(seed: int):
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
class Framework:
def __init__(self, args, task):
self.args = args
self.task = task
self.model, self.tokenizer = self.load_model()
def load_model(self):
"""
Load HuggingFace models
"""
with count_time("Loading model with FP%d" % (16 if self.args.load_float16 else 32)):
free_in_GB = int(torch.cuda.mem_get_info()[0]/1024**3)
config = AutoConfig.from_pretrained(self.args.model_name)
if self.args.untie_emb:
# Untie embeddings/LM head
logger.warn("Untie embeddings and LM head")
config.tie_word_embeddings = False
if self.args.head_tuning:
# Head tuning
from ht_opt import OPTForCausalLM
model = OPTForCausalLM.from_pretrained(
self.args.model_name,
config=config,
)
elif self.args.no_auto_device:
# No auto device (use for FSDP)
model = AutoModelForCausalLM.from_pretrained(
self.args.model_name,
config=config,
)
else:
# Auto device loading
torch_dtype = torch.float32
if self.args.load_float16:
torch_dtype = torch.float16
elif self.args.load_bfloat16:
torch_dtype = torch.bfloat16
model = AutoModelForCausalLM.from_pretrained(
self.args.model_name,
config=config,
device_map='auto',
torch_dtype=torch_dtype,
max_memory={i: f'{free_in_GB-5}GB' for i in range(torch.cuda.device_count())},
load_in_8bit=self.args.load_int8,
)
model.eval()
# Load tokenizer
tokenizer = AutoTokenizer.from_pretrained(self.args.model_name, use_fast=False)
# HF tokenizer bug fix
if "opt" in self.args.model_name:
tokenizer.bos_token_id = 0
if "llama" in self.args.model_name:
# LLaMA padding token
tokenizer.pad_token_id = 0 # technically <unk>
# Prefix tuning/LoRA
if self.args.prefix_tuning:
from prefix import PrefixTuning
PrefixTuning(model, num_prefix=self.args.num_prefix, reparam=not self.args.no_reparam, float16=self.args.load_float16, init_by_real_act=self.args.prefix_init_by_real_act)
if self.args.lora:
from lora import LoRA
LoRA(model, r=self.args.lora_r, alpha=self.args.lora_alpha, float16=self.args.load_float16)
if self.args.head_tuning:
if model.config.model_type == "opt":
head_name = "lm_head" if self.args.untie_emb else "embed_tokens"
else:
raise NotImplementedError
for n, p in model.named_parameters():
if head_name not in n:
p.requires_grad = False
else:
logger.info(f"Only tuning {n}")
return model, tokenizer
def forward(self, input_ids, option_len=None, generation=False):
"""
Given input_ids and the length of the option, return the log-likelihood of each token in the option.
For generation tasks, return the generated text.
This function is only for inference
"""
input_ids = torch.tensor([input_ids]).to(self.model.device)
if generation:
args = self.args
# Autoregressive generation
outputs = self.model.generate(
input_ids, do_sample=args.sampling, temperature=args.temperature,
num_beams=args.num_beams, top_p=args.top_p, top_k=args.top_k, max_new_tokens=min(args.max_new_tokens, args.max_length - input_ids.size(1)),
num_return_sequences=1, eos_token_id=[self.tokenizer.encode(args.eos_token, add_special_tokens=False)[-1], self.tokenizer.eos_token_id],
)
# For generation, directly return the text output
output_text = self.tokenizer.decode(outputs[0][input_ids.size(1):], skip_special_tokens=True).strip()
return output_text
else:
with torch.inference_mode():
self.model.eval()
logits = self.model(input_ids=input_ids).logits
labels = input_ids[0, 1:]
logits = logits[0, :-1]
log_probs = F.log_softmax(logits, dim=-1)
selected_log_probs = log_probs[torch.arange(len(labels)).to(labels.device), labels]
selected_log_probs = selected_log_probs.cpu().detach()
# Only return the option (candidate) part
return selected_log_probs[-option_len:]
def one_step_pred(self, train_samples, eval_sample, verbose=False):
"""
Return the prediction on the eval sample. In ICL, use train_samples as demonstrations
"""
verbose = verbose or self.args.verbose
if verbose:
logger.info("========= Example =========")
logger.info(f"Candidate: {eval_sample.candidates}")
logger.info(f"Correct candidate: {eval_sample.correct_candidate}")
# Encode (add prompt and tokenize) the sample; if multiple-choice/classification, encode all candidates (options)
encoded_candidates, option_lens = encode_prompt(
self.task, self.task.get_template(), train_samples, eval_sample, self.tokenizer, max_length=self.args.max_length,
generation=self.task.generation, max_new_tokens=self.args.max_new_tokens
)
# Calibration
if self.args.sfc or self.args.icl_sfc:
sfc_encoded_candidates, sfc_option_lens = encode_prompt(self.task, self.task.get_template(),
train_samples, eval_sample, self.tokenizer, max_length=self.args.max_length,
sfc=self.args.sfc, icl_sfc=self.args.icl_sfc, generation=self.task.generation,
max_new_tokens=self.args.max_new_tokens
)
outputs = []
if self.task.generation:
# For generation tasks, return the autoregressively-generated text
output_text = self.forward(encoded_candidates[0], generation=True)
if verbose:
logger.info("=== Prompt ===")
logger.info(self.tokenizer.decode(encoded_candidates[0]))
logger.info(f"Output: {output_text}")
return Prediction(correct_candidate=eval_sample.correct_candidate, predicted_candidate=output_text)
else:
# For classification/multiple-choice, calculate the probabilities of all candidates
for candidate_id, encoded_candidate in enumerate(encoded_candidates):
selected_log_probs = self.forward(encoded_candidate, option_len=option_lens[candidate_id])
if verbose:
if candidate_id == 0:
logger.info("=== Candidate %d ===" % candidate_id)
logger.info(self.tokenizer.decode(encoded_candidate))
else:
logger.info("=== Candidate %d (without context)===" % candidate_id)
logger.info(self.tokenizer.decode(encoded_candidate).split(self.task.train_sep)[-1])
logger.info(f"Log probabilities of the option tokens: {selected_log_probs}")
if self.args.sfc or self.args.icl_sfc:
sfc_selected_log_probs = self.forward(sfc_encoded_candidates[candidate_id], option_len=sfc_option_lens[candidate_id])
if verbose:
logger.info("=== Candidate %d (without context) SFC ===" % candidate_id)
logger.info(self.tokenizer.decode(sfc_encoded_candidates[candidate_id]).split(self.task.train_sep)[-1])
logger.info(f"Log probabilities of the option tokens: {sfc_selected_log_probs}")
outputs.append({"log_probs": selected_log_probs, "sfc_log_probs": sfc_selected_log_probs if self.args.sfc or self.args.icl_sfc else None})
if self.args.sfc or self.args.icl_sfc:
# Calibrated probabilities (surface form competition; https://arxiv.org/pdf/2104.08315.pdf)
# log p(candidate | input) = log p_lm(candidate | input) - log p_lm(candidate | sfc prompt)
scores = [x['log_probs'].sum().item() - x['sfc_log_probs'].sum().item() for x in outputs]
else:
# (Default) length-normalized log probabilities
# log p(candidate | input) = log p_lm(candidate | input) / |candidate #tokens|
scores = [x['log_probs'].mean().item() for x in outputs]
if verbose:
logger.info(f"Prediction scores: {scores}")
if isinstance(eval_sample.correct_candidate, list):
# For some datasets there are multiple correct answers
correct_candidate_id = [eval_sample.candidates.index(c) for c in eval_sample.correct_candidate]
else:
correct_candidate_id = eval_sample.candidates.index(eval_sample.correct_candidate)
return Prediction(correct_candidate=correct_candidate_id, predicted_candidate=int(np.argmax(scores)))
def evaluate(self, train_samples, eval_samples, one_train_set_per_eval_sample=False):
"""
Evaluate function. If one_train_set_per_eval_sample is True, then each eval sample has its own training (demonstration) set.
"""
if one_train_set_per_eval_sample:
logger.info(f"There are {len(eval_samples)} validation samples and one train set per eval sample")
else:
logger.info(f"There are {len(train_samples)} training samples and {len(eval_samples)} validation samples")
# Prediction loop
predictions = []
for eval_id, eval_sample in enumerate(tqdm(eval_samples)):
predictions.append(
self.one_step_pred(train_samples[eval_id] if one_train_set_per_eval_sample else train_samples, eval_sample, verbose=(eval_id < 3))
)
# Calculate metrics
metric_name = getattr(self.task, "metric_name", "accuracy")
metrics = {metric_name: calculate_metric(predictions, metric_name)}
return metrics
def train(self, train_samples, eval_samples):
"""
Training function
"""
# Set tokenizer to left padding (so that all the options are right aligned)
self.tokenizer.padding_side = "left"
class HFDataset(Dataset):
def __init__(self, data):
self.data = data
def __len__(self):
return len(self.data)
def __getitem__(self, idx):
return self.data[idx]
def _convert(samples):
"""
Convert samples to HF-compatible dataset
"""
data = []
for sample in samples:
encoded_candidates, option_lens = encode_prompt(
self.task, self.task.get_template(), [], sample, self.tokenizer,
max_length=self.args.max_length, generation=self.task.generation, generation_with_gold=True,
max_new_tokens=self.args.max_new_tokens
)
if self.task.generation:
correct_candidate_id = 0
elif isinstance(sample.correct_candidate, list):
correct_candidate_id = sample.candidates.index(sample.correct_candidate[0])
else:
correct_candidate_id = sample.candidates.index(sample.correct_candidate)
if self.args.non_diff:
# For non-differentiable objective, there is no teacher forcing thus the
# current answer part is removed
encoded_candidates[correct_candidate_id] = encoded_candidates[correct_candidate_id][:-option_lens[correct_candidate_id]]
if self.args.train_as_classification:
# For classification, we provide the label as the correct candidate id
data.append([{"input_ids": encoded_candidates[_i], "labels": correct_candidate_id, "option_len": option_lens[_i], "num_options": len(sample.candidates)} for _i in range(len(encoded_candidates))])
elif self.args.only_train_option:
# Otherwise, it is just LM-style teacher forcing
if self.args.non_diff:
# For non-differentiable objective, we need to provide the gold answer to calculate F1/acc
data.append({"input_ids": encoded_candidates[correct_candidate_id], "labels": encoded_candidates[correct_candidate_id], "option_len": option_lens[correct_candidate_id], "gold": sample.correct_candidate})
else:
data.append({"input_ids": encoded_candidates[correct_candidate_id], "labels": encoded_candidates[correct_candidate_id], "option_len": option_lens[correct_candidate_id]})
else:
data.append({"input_ids": encoded_candidates[correct_candidate_id], "labels": encoded_candidates[correct_candidate_id]})
return data
with count_time("Tokenizing training samples"):
train_dataset = HFDataset(_convert(train_samples))
eval_dataset = HFDataset(_convert(eval_samples))
if self.args.only_train_option and not self.args.non_diff:
# If --only_train_option and not with a non-differentiable objective, we wrap the forward function
self.model.original_forward = self.model.forward
self.model.forward = forward_wrap_with_option_len.__get__(self.model, type(self.model))
if self.args.non_diff:
collator = NondiffCollator
else:
collator = DataCollatorForTokenClassification
trainer = OurTrainer(
model=self.model,
args=self.args,
train_dataset=train_dataset,
eval_dataset=eval_dataset,
tokenizer=self.tokenizer,
data_collator=DataCollatorWithPaddingAndNesting(self.tokenizer, pad_to_multiple_of=8) if self.args.train_as_classification else collator(self.tokenizer, pad_to_multiple_of=8),
)
if self.args.save_on_interrupt:
trainer.add_callback(SIGUSR1Callback())
# Resume training from a last checkpoint
last_checkpoint = None
from transformers.trainer_utils import get_last_checkpoint
if os.path.isdir(self.args.output_dir) and not self.args.overwrite_output_dir:
last_checkpoint = get_last_checkpoint(self.args.output_dir)
if last_checkpoint is not None and self.args.resume_from_checkpoint is None:
logger.info(
f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change "
"the `--output_dir` or add `--overwrite_output_dir` to train from scratch."
)
if self.args.resume_from_checkpoint is not None:
last_checkpoint = self.args.resume_from_checkpoint
trainer.train(resume_from_checkpoint=last_checkpoint)
# Explicitly save the model
if self.args.save_model:
logger.warn("Save model..")
trainer.save_model()
# FSDP compatibility
self.model = trainer.model
# Reset the forward function for evaluation
if self.args.only_train_option and not self.args.non_diff:
if type(self.model) == FSDP:
logger.info("This is an FSDP model now. Be careful when assigning back the original forward function")
self.model._fsdp_wrapped_module.forward = self.model._fsdp_wrapped_module.original_forward
else:
self.model.forward = self.model.original_forward
def result_file_tag(args):
"""
Get the result file tag
"""
save_model_name = args.model_name.split("/")[-1]
sfc_tag = "-sfc" if args.sfc else ""
icl_sfc_tag = "-icl_sfc" if args.icl_sfc else ""
sample_eval_tag = "-sampleeval%d" % args.num_eval if args.num_eval is not None else ""
sample_train_tag = "-ntrain%d" % args.num_train if args.num_train > 0 else ""
sample_dev_tag = "-ndev%d" % args.num_dev if args.num_dev is not None else ""
customized_tag = f"-{args.tag}" if len(args.tag) > 0 else ""
return f"{args.task_name}-{save_model_name}" + sfc_tag + icl_sfc_tag + sample_eval_tag + sample_train_tag + sample_dev_tag + customized_tag
def main():
args = parse_args()
set_seed(args.seed)
task = get_task(args.task_name)
train_sets = task.sample_train_sets(num_train=args.num_train, num_dev=args.num_dev, num_eval=args.num_eval, num_train_sets=args.num_train_sets, seed=args.train_set_seed)
# Initialize trainer and load model
framework = Framework(args, task)
if args.train_set_seed is not None or args.num_train_sets is not None:
# Eval samples share one (or multiple) training set(s)
for train_set_id, train_samples in enumerate(train_sets):
train_set_seed = train_set_id if args.train_set_seed is None else args.train_set_seed
# Sample eval samples
if args.num_eval is not None:
eval_samples = task.sample_subset(data_split="valid", seed=train_set_seed, num=args.num_eval)
else:
eval_samples = task.valid_samples
if args.trainer != "none":
if args.num_dev is not None:
# Dev samples
dev_samples = train_samples[-args.num_dev:]
train_samples = train_samples[:-args.num_dev]
else:
dev_samples = None
# Training
framework.train(train_samples, dev_samples if dev_samples is not None else eval_samples)
if not args.no_eval:
metrics = framework.evaluate([], eval_samples) # No in-context learning if there is training
if dev_samples is not None:
dev_metrics = framework.evaluate([], dev_samples)
for m in dev_metrics:
metrics["dev_" + m] = dev_metrics[m]
else:
assert args.num_dev is None
# Zero-shot / in-context learning
metrics = framework.evaluate(train_samples, eval_samples)
if not args.no_eval:
logger.info("===== Train set %d =====" % train_set_seed)
logger.info(metrics)
if args.local_rank <= 0:
write_metrics_to_file(metrics, "result/" + result_file_tag(args) + f"-trainset{train_set_id}.json" if args.result_file is None else args.result_file)
else:
# For each eval sample, there is a training set. no training is allowed
# This is for in-context learning (ICL)
assert args.trainer == "none"
if args.num_eval is not None:
eval_samples = task.sample_subset(data_split="valid", seed=0, num=args.num_eval)
else:
eval_samples = task.valid_samples
metrics = framework.evaluate(train_sets, eval_samples, one_train_set_per_eval_sample=True)
logger.info(metrics)
if args.local_rank <= 0:
write_metrics_to_file(metrics, "result/" + result_file_tag(args) + "-onetrainpereval.json" if args.result_file is None else args.result_file)
if __name__ == "__main__":
main()
+425
View File
@@ -0,0 +1,425 @@
from templates import *
from utils import temp_seed
import json
import os
from datasets import load_dataset
from dataclasses import dataclass
from typing import List, Union
import string
import random
import datasets
import sys
import numpy as np
import logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
def get_task(task_name):
aa = task_name.split("__")
if len(aa) == 2:
task_group, subtask = aa
else:
task_group = aa[0]
subtask = None
class_ = getattr(sys.modules[__name__], f"{task_group}Dataset")
instance = class_(subtask)
return instance
@dataclass
class Sample:
id: int = None
data: dict = None
correct_candidate: Union[str, List[str]] = None
candidates: List[str] = None
class Dataset:
mixed_set = False
train_sep = "\n\n"
generation = False # whether this is a generation task
def __init__(self, subtask=None, **kwargs) -> None:
self.subtask = subtask
def get_task_name(self):
return self.subtask
def load_dataset():
raise NotImplementedError
def get_template(self, template_version=0):
templates = {0: Template}
return templates[template_version]
def build_sample(self, example):
return
def sample_train_sets(self, num_train=32, num_dev=None, num_eval=None, num_train_sets=None, seed=None):
if seed is not None:
# one train/demo set using the designated seed
seeds = [seed]
elif num_train_sets is not None:
# num_train_sets train/demo sets
seeds = list(range(num_train_sets))
else:
# one train/demo set per evaluation sample
assert num_dev is None # not supported
len_valid_samples = len(self.samples["valid"]) if num_eval is None else num_eval
with temp_seed(0):
seeds = np.random.randint(0, 10000, len_valid_samples)
train_samples = []
for i, set_seed in enumerate(seeds):
if self.mixed_set:
raise NotImplementedError
train_samples.append(self.sample_subset(data_split="valid", seed=set_seed, num=num_train, exclude=i))
else:
if num_dev is not None:
train_samples.append(self.sample_subset(data_split="train", seed=set_seed, num=num_train+num_dev)) # dev set is included at the end of train set
if num_train + num_dev > len(self.samples["train"]):
logger.warn("num_train + num_dev > available training examples")
else:
train_samples.append(self.sample_subset(data_split="train", seed=set_seed, num=num_train))
if num_dev is not None:
logger.info(f"Sample train set {len(train_samples[-1])}/{len(self.samples['train'])}")
logger.info(f"... including dev set {num_dev} samples")
return train_samples
def sample_subset(self, data_split="train", seed=0, num=100, exclude=None):
with temp_seed(seed):
samples = self.samples[data_split]
lens = len(samples)
index = np.random.permutation(lens).tolist()[:num if exclude is None else num+1]
if exclude is not None and exclude in index:
index.remove(exclude)
else:
index = index[:num]
return [samples[i] for i in index]
@property
def valid_samples(self):
return self.samples["valid"]
class SST2Dataset(Dataset):
train_sep = "\n\n"
def __init__(self, subtask=None, **kwargs) -> None:
self.load_dataset(subtask, **kwargs)
def load_dataset(self, path, **kwargs):
d = load_dataset('glue', 'sst2')
train_d = d["train"]
validation_d = d["validation"]
train_samples = [self.build_sample(example) for example in train_d]
valid_samples = [self.build_sample(example) for example in validation_d]
self.samples = {"train": train_samples, "valid": valid_samples}
# for generative tasks, candidates are []
def build_sample(self, example):
label = int(example["label"])
return Sample(id=example["idx"], data=example, correct_candidate=label, candidates=[0, 1])
def get_template(self, template_version=0):
return {0: SST2Template}[template_version]()
class CopaDataset(Dataset):
train_sep = "\n\n"
mixed_set = False
def __init__(self, subtask=None, **kwargs) -> None:
self.load_dataset(subtask, **kwargs)
def load_dataset(self, path, **kwargs):
train_examples = load_dataset('super_glue', "copa")["train"]
valid_examples = load_dataset('super_glue', "copa")["validation"]
train_samples = [self.build_sample(example) for example in train_examples]
valid_samples = [self.build_sample(example) for example in valid_examples]
self.samples = {"train": train_samples, "valid": valid_samples}
# for generative tasks, candidates are []
def build_sample(self, example):
sample = \
Sample(
id=example["idx"],
data=example,
candidates=[example["choice1"], example["choice2"]],
correct_candidate=example[f"choice{example['label'] + 1}"],
)
return sample
def get_template(self, template_version=0):
return {0: CopaTemplate}[template_version]()
class BoolQDataset(Dataset):
def __init__(self, subtask=None, **kwargs) -> None:
self.load_dataset(subtask, **kwargs)
def load_dataset(self, path, **kwargs):
d = load_dataset("boolq")
train_set = d["train"]
valid_set = d["validation"]
train_samples = [self.build_sample(example) for example in train_set]
valid_samples = [self.build_sample(example) for example in valid_set]
self.samples = {"train": train_samples, "valid": valid_samples}
def build_sample(self, example):
sample = \
Sample(
data=example,
candidates=["Yes", "No"],
correct_candidate="Yes" if example["answer"] else "No",
)
return sample
def get_template(self, template_version=2):
return {0: BoolQTemplate, 1: BoolQTemplateV2, 2: BoolQTemplateV3}[template_version]()
class MultiRCDataset(Dataset):
def __init__(self, subtask=None, **kwargs) -> None:
self.load_dataset(subtask, **kwargs)
def load_dataset(self, path, **kwargs):
d = load_dataset("super_glue", "multirc")
train_set = d["train"]
valid_set = d["validation"]
train_samples = [self.build_sample(example) for example in train_set]
valid_samples = [self.build_sample(example) for example in valid_set]
self.samples = {"train": train_samples, "valid": valid_samples}
def build_sample(self, example):
sample = \
Sample(
data=example,
candidates=[0, 1],
correct_candidate=example['label']
)
return sample
def get_template(self, template_version=0):
return {0: MultiRCTemplate}[template_version]()
class CBDataset(Dataset):
def __init__(self, subtask=None, **kwargs) -> None:
self.load_dataset(subtask, **kwargs)
def load_dataset(self, path, **kwargs):
d = load_dataset("super_glue", "cb")
train_set = d["train"]
valid_set = d["validation"]
train_samples = [self.build_sample(example) for example in train_set]
valid_samples = [self.build_sample(example) for example in valid_set]
self.samples = {"train": train_samples, "valid": valid_samples}
def build_sample(self, example):
sample = \
Sample(
data=example,
candidates=[0, 1, 2],
correct_candidate=example['label']
)
return sample
def get_template(self, template_version=0):
return {0: CBTemplate}[template_version]()
class WICDataset(Dataset):
def __init__(self, subtask=None, **kwargs) -> None:
self.load_dataset(subtask, **kwargs)
def load_dataset(self, path, **kwargs):
d = load_dataset("super_glue", "wic")
train_set = d["train"]
valid_set = d["validation"]
train_samples = [self.build_sample(example) for example in train_set]
valid_samples = [self.build_sample(example) for example in valid_set]
self.samples = {"train": train_samples, "valid": valid_samples}
def build_sample(self, example):
sample = \
Sample(
data=example,
candidates=[0, 1],
correct_candidate=example['label']
)
return sample
def get_template(self, template_version=0):
return {0: WICTemplate}[template_version]()
class WSCDataset(Dataset):
def __init__(self, subtask=None, **kwargs) -> None:
self.load_dataset(subtask, **kwargs)
def load_dataset(self, path, **kwargs):
d = load_dataset("super_glue", "wsc.fixed")
train_set = d["train"]
valid_set = d["validation"]
train_samples = [self.build_sample(example) for example in train_set]
valid_samples = [self.build_sample(example) for example in valid_set]
self.samples = {"train": train_samples, "valid": valid_samples}
def build_sample(self, example):
sample = \
Sample(
data=example,
candidates=[0, 1],
correct_candidate=example['label']
)
return sample
def get_template(self, template_version=0):
return {0: WSCTemplate}[template_version]()
class ReCoRDDataset(Dataset):
def __init__(self, subtask=None, **kwargs) -> None:
self.load_dataset(subtask, **kwargs)
def load_dataset(self, path, **kwargs):
d = load_dataset("super_glue", "record")
train_set = d["train"]
valid_set = d["validation"]
train_samples = [self.build_sample(example) for example in train_set]
valid_samples = [self.build_sample(example) for example in valid_set]
self.samples = {"train": train_samples, "valid": valid_samples}
def build_sample(self, example):
sample = \
Sample(
data=example,
candidates=example['entities'],
correct_candidate=example['answers']
)
return sample
def get_template(self, template_version=0):
return {0: ReCoRDTemplateGPT3}[template_version]()
class RTEDataset(Dataset):
def __init__(self, subtask=None, **kwargs) -> None:
self.load_dataset(subtask, **kwargs)
def load_dataset(self, path, **kwargs):
d = load_dataset("super_glue", "rte")
train_set = d["train"]
valid_set = d["validation"]
train_samples = [self.build_sample(example) for example in train_set]
valid_samples = [self.build_sample(example) for example in valid_set]
self.samples = {"train": train_samples, "valid": valid_samples}
def build_sample(self, example):
sample = \
Sample(
data=example,
candidates=[0, 1],
correct_candidate=example['label']
)
return sample
def get_template(self, template_version=0):
return {0: RTETemplate}[template_version]()
class SQuADDataset(Dataset):
metric_name = "f1"
generation = True
def __init__(self, subtask=None, **kwargs) -> None:
self.load_dataset()
def load_dataset(self):
dataset = load_dataset("squad")
train_examples = dataset["train"]
valid_examples = dataset["validation"]
train_samples = [self.build_sample(example, idx) for idx, example in enumerate(train_examples)]
valid_samples = [self.build_sample(example, idx) for idx, example in enumerate(valid_examples)]
self.samples = {"train": train_samples, "valid": valid_samples}
# for generative tasks, candidates are []
def build_sample(self, example, idx):
answers = example['answers']['text']
assert len(answers) > 0
return Sample(
id=idx,
data={
"title": example['title'],
"context": example['context'],
"question": example['question'],
"answers": answers
},
candidates=None,
correct_candidate=answers
)
def get_template(self, template_version=0):
return {0: SQuADv2Template}[template_version]()
class DROPDataset(Dataset):
metric_name = "f1"
generation = True
def __init__(self, subtask=None, **kwargs) -> None:
self.load_dataset()
def load_dataset(self):
dataset = load_dataset("drop")
train_examples = dataset["train"]
valid_examples = dataset["validation"]
train_samples = [self.build_sample(example, idx) for idx, example in enumerate(train_examples)]
valid_samples = [self.build_sample(example, idx) for idx, example in enumerate(valid_examples)]
self.samples = {"train": train_samples, "valid": valid_samples}
# for generative tasks, candidates are []
def build_sample(self, example, idx):
answers = example['answers_spans']['spans']
assert len(answers) > 0
return Sample(
id=idx,
data={
"context": example['passage'],
"question": example['question'],
"answers": answers
},
candidates=None,
correct_candidate=answers
)
def get_template(self, template_version=0):
return {0: DROPTemplate}[template_version]()
+379
View File
@@ -0,0 +1,379 @@
class Template:
def encode(self, sample):
"""
Return prompted version of the example (without the answer/candidate)
"""
raise NotImplementedError
def verbalize(self, sample, candidate):
"""
Return the prompted version of the example (with the answer/candidate)
"""
return candidate
def encode_sfc(self, sample):
"""
Same as encode, but for SFC (calibration) -- this usually means the input is not included
"""
return "<mask>"
def verbalize_sfc(self, sample, candidate):
"""
Same as verbalize, but for SFC (calibration) -- this usually means the input is not included
"""
return candidate
class SST2Template(Template):
verbalizer = {0: "terrible", 1: "great"}
def encode(self, sample):
text = sample.data["sentence"].strip()
return f"{text} It was"
def verbalize(self, sample, candidate):
text = sample.data["sentence"].strip()
return f"{text} It was {self.verbalizer[candidate]}"
def encode_sfc(self, sample):
return f" It was"
def verbalize_sfc(self, sample, candidate):
return f" It was {self.verbalizer[candidate]}"
class CopaTemplate(Template):
capitalization: str = "correct"
effect_conj: str = " so "
cause_conj: str = " because "
def get_conjucture(self, sample):
if sample.data["question"] == "effect":
conjunction = self.effect_conj
elif sample.data["question"] == "cause":
conjunction = self.cause_conj
else:
raise NotImplementedError
return conjunction
def get_prompt(self, sample):
premise = sample.data["premise"].rstrip()
if premise.endswith("."): # TODO Add other scripts with different punctuation
premise = premise[:-1]
conjunction = self.get_conjucture(sample)
prompt = premise + conjunction
if self.capitalization == "upper":
prompt = prompt.upper()
elif self.capitalization == "lower":
prompt = prompt.lower()
return prompt
def encode(self, sample):
prompt = self.get_prompt(sample)
return prompt
def capitalize(self, c):
if self.capitalization == "correct":
words = c.split(" ")
if words[0] != "I":
words[0] = words[0].lower()
return " ".join(words)
elif self.capitalization == "bug":
return c
elif self.capitalization == "upper":
return c.upper()
elif self.capitalization == "lower":
return c.lower()
else:
raise NotImplementedError
def verbalize(self, sample, candidate):
prompt = self.get_prompt(sample)
return prompt + self.capitalize(candidate)
def encode_sfc(self, sample):
conjunction = self.get_conjucture(sample)
return conjunction.strip()
def verbalize_sfc(self, sample, candidate):
conjunction = self.get_conjucture(sample)
sfc_prompt = conjunction.strip() + " " + self.capitalize(candidate)
return sfc_prompt
class BoolQTemplate(Template):
def encode(self, sample):
passage = sample.data["passage"]
question = sample.data["question"]
if not question.endswith("?"):
question = question + "?"
question = question[0].upper() + question[1:]
return f"{passage} {question}"
def verbalize(self, sample, candidate):
passage = sample.data["passage"]
question = sample.data["question"]
if not question.endswith("?"):
question = question + "?"
question = question[0].upper() + question[1:]
return f"{passage} {question} {candidate}"
def encode_sfc(self, sample):
return ""
def verbalize_sfc(self, sample, candidate):
return candidate
class BoolQTemplateV2(Template):
def encode(self, sample):
passage = sample.data["passage"]
question = sample.data["question"]
if not question.endswith("?"):
question = question + "?"
question = question[0].upper() + question[1:]
return f"{passage} {question}\\n\\n"
def verbalize(self, sample, candidate):
passage = sample.data["passage"]
question = sample.data["question"]
if not question.endswith("?"):
question = question + "?"
question = question[0].upper() + question[1:]
return f"{passage} {question}\\n\\n{candidate}"
def encode_sfc(self, sample):
return ""
def verbalize_sfc(self, sample, candidate):
return candidate
class BoolQTemplateV3(Template):
def encode(self, sample):
passage = sample.data["passage"]
question = sample.data["question"]
if not question.endswith("?"):
question = question + "?"
question = question[0].upper() + question[1:]
return f"{passage} {question}\n"
def verbalize(self, sample, candidate):
passage = sample.data["passage"]
question = sample.data["question"]
if not question.endswith("?"):
question = question + "?"
question = question[0].upper() + question[1:]
return f"{passage} {question}\n{candidate}"
def encode_sfc(self, sample):
return ""
def verbalize_sfc(self, sample, candidate):
return candidate
class MultiRCTemplate(Template):
# From PromptSource 1
verbalizer = {0: "No", 1: "Yes"}
def encode(self, sample):
paragraph = sample.data["paragraph"]
question = sample.data["question"]
answer = sample.data["answer"]
return f"{paragraph}\nQuestion: {question}\nI found this answer \"{answer}\". Is that correct? Yes or No?\n"
def verbalize(self, sample, candidate):
paragraph = sample.data["paragraph"]
question = sample.data["question"]
answer = sample.data["answer"]
return f"{paragraph}\nQuestion: {question}\nI found this answer \"{answer}\". Is that correct? Yes or No?\n{self.verbalizer[candidate]}"
def encode_sfc(self, sample):
return f""
def verbalize_sfc(self, sample, candidate):
return f"{self.verbalizer[candidate]}"
class CBTemplate(Template):
# From PromptSource 1
verbalizer = {0: "Yes", 1: "No", 2: "Maybe"}
def encode(self, sample):
premise = sample.data["premise"]
hypothesis = sample.data["hypothesis"]
return f"Suppose {premise} Can we infer that \"{hypothesis}\"? Yes, No, or Maybe?\n"
def verbalize(self, sample, candidate):
premise = sample.data["premise"]
hypothesis = sample.data["hypothesis"]
return f"Suppose {premise} Can we infer that \"{hypothesis}\"? Yes, No, or Maybe?\n{self.verbalizer[candidate]}"
def encode_sfc(self, sample):
return f""
def verbalize_sfc(self, sample, candidate):
return f"{self.verbalizer[candidate]}"
class WICTemplate(Template):
# From PromptSource 1
verbalizer = {0: "No", 1: "Yes"}
def encode(self, sample):
sent1 = sample.data["sentence1"]
sent2 = sample.data["sentence2"]
word = sample.data["word"]
return f"Does the word \"{word}\" have the same meaning in these two sentences? Yes, No?\n{sent1}\n{sent2}\n"
def verbalize(self, sample, candidate):
sent1 = sample.data["sentence1"]
sent2 = sample.data["sentence2"]
word = sample.data["word"]
return f"Does the word \"{word}\" have the same meaning in these two sentences? Yes, No?\n{sent1}\n{sent2}\n{self.verbalizer[candidate]}"
def encode_sfc(self, sample):
return f""
def verbalize_sfc(self, sample, candidate):
return f"{self.verbalizer[candidate]}"
class WSCTemplate(Template):
# From PromptSource 1
verbalizer = {0: "No", 1: "Yes"}
def encode(self, sample):
text = sample.data['text']
span1 = sample.data['span1_text']
span2 = sample.data['span2_text']
return f"{text}\nIn the previous sentence, does the pronoun \"{span2.lower()}\" refer to {span1}? Yes or No?\n"
def verbalize(self, sample, candidate):
text = sample.data['text']
span1 = sample.data['span1_text']
span2 = sample.data['span2_text']
return f"{text}\nIn the previous sentence, does the pronoun \"{span2.lower()}\" refer to {span1}? Yes or No?\n{self.verbalizer[candidate]}"
def encode_sfc(self, sample):
return f""
def verbalize_sfc(self, sample, candidate):
return f"{self.verbalizer[candidate]}"
class ReCoRDTemplate(Template):
# From PromptSource 1 but modified
def encode(self, sample):
passage = sample.data['passage']
query = sample.data['query']
return f"{passage}\n{query}\nQuestion: what is the \"@placeholder\"\nAnswer:"
def verbalize(self, sample, candidate):
passage = sample.data['passage']
query = sample.data['query']
return f"{passage}\n{query}\nQuestion: what is the \"@placeholder\"\nAnswer: {candidate}"
def encode_sfc(self, sample):
return f"Answer:"
def verbalize_sfc(self, sample, candidate):
return f"Answer: {candidate}"
class ReCoRDTemplateGPT3(Template):
# From PromptSource 1 but modified
def encode(self, sample):
passage = sample.data['passage'].replace("@highlight\n", "- ")
return f"{passage}\n-"
def verbalize(self, sample, candidate):
passage = sample.data['passage'].replace("@highlight\n", "- ")
query = sample.data['query'].replace("@placeholder", candidate[0] if isinstance(candidate, list) else candidate)
return f"{passage}\n- {query}"
# passage = sample.data['passage']
# query = sample.data['query']
# return f"{passage}\n{query}\nQuestion: what is the \"@placeholder\"\nAnswer: {candidate}"
def encode_sfc(self, sample):
return f"-"
def verbalize_sfc(self, sample, candidate):
query = sample.data['query'].replace("@placeholder", candidate[0] if isinstance(candidate, list) else candidate)
return f"- {query}"
class RTETemplate(Template):
# From PromptSource 1
verbalizer={0: "Yes", 1: "No"}
def encode(self, sample):
premise = sample.data['premise']
hypothesis = sample.data['hypothesis']
return f"{premise}\nDoes this mean that \"{hypothesis}\" is true? Yes or No?\n"
def verbalize(self, sample, candidate):
premise = sample.data['premise']
hypothesis = sample.data['hypothesis']
return f"{premise}\nDoes this mean that \"{hypothesis}\" is true? Yes or No?\n{self.verbalizer[candidate]}"
def encode_sfc(self, sample):
return f""
def verbalize_sfc(self, sample, candidate):
return f"{self.verbalizer[candidate]}"
class SQuADv2Template(Template):
def encode(self, sample):
question = sample.data['question'].strip()
title = sample.data['title']
context = sample.data['context']
answer = sample.data['answers'][0] # there are multiple answers. for the prompt we only take the first one
return f"Title: {title}\nContext: {context}\nQuestion: {question}\nAnswer:"
def verbalize(self, sample, candidate):
question = sample.data['question'].strip()
title = sample.data['title']
context = sample.data['context']
answer = sample.data['answers'][0] # there are multiple answers. for the prompt we only take the first one
return f"Title: {title}\nContext: {context}\nQuestion: {question}\nAnswer: {answer}\n"
def encode_sfc(self, sample):
raise NotImplementedError
def verbalize_sfc(self, sample, candidate):
raise NotImplementedError
class DROPTemplate(Template):
def encode(self, sample):
question = sample.data['question'].strip()
# title = sample.data['title']
context = sample.data['context']
answer = sample.data['answers'][0] # there are multiple answers. for the prompt we only take the first one
return f"Passage: {context}\nQuestion: {question}\nAnswer:"
def verbalize(self, sample, candidate):
question = sample.data['question'].strip()
# title = sample.data['title']
context = sample.data['context']
answer = sample.data['answers'][0] # there are multiple answers. for the prompt we only take the first one
return f"Passage: {context}\nQuestion: {question}\nAnswer: {answer}\n"
def encode_sfc(self, sample):
raise NotImplementedError
def verbalize_sfc(self, sample, candidate):
raise NotImplementedError
+893
View File
@@ -0,0 +1,893 @@
# coding=utf-8
# Copyright 2020-present the HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
The Trainer class, to easily train a 🤗 Transformers from scratch or finetune it on a new task.
"""
import contextlib
import functools
import glob
import inspect
import math
import os
import random
import re
import shutil
import sys
import time
import warnings
from collections.abc import Mapping
from pathlib import Path
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple, Union
import copy
from metrics import f1
import numpy as np
from tqdm.auto import tqdm
from transformers import Trainer
from sklearn.linear_model import LinearRegression, LogisticRegression, LogisticRegressionCV
# Integrations must be imported before ML frameworks:
from transformers.integrations import ( # isort: split
default_hp_search_backend,
get_reporting_integration_callbacks,
hp_params,
is_fairscale_available,
is_optuna_available,
is_ray_tune_available,
is_sigopt_available,
is_wandb_available,
run_hp_search_optuna,
run_hp_search_ray,
run_hp_search_sigopt,
run_hp_search_wandb,
)
import numpy as np
import torch
import torch.distributed as dist
from packaging import version
from torch import nn
from torch.utils.data import DataLoader, Dataset, RandomSampler, SequentialSampler
from torch.utils.data.distributed import DistributedSampler
from huggingface_hub import Repository
from transformers import __version__
from transformers.configuration_utils import PretrainedConfig
from transformers.data.data_collator import DataCollator, DataCollatorWithPadding, default_data_collator
from transformers.debug_utils import DebugOption, DebugUnderflowOverflow
from transformers.deepspeed import deepspeed_init, is_deepspeed_zero3_enabled
from transformers.dependency_versions_check import dep_version_check
from transformers.modelcard import TrainingSummary
from transformers.modeling_utils import PreTrainedModel, load_sharded_checkpoint, unwrap_model
from transformers.models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES, MODEL_MAPPING_NAMES
from transformers.optimization import Adafactor, get_scheduler
from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS, is_torch_greater_or_equal_than_1_10, is_torch_less_than_1_11
from transformers.tokenization_utils_base import PreTrainedTokenizerBase
from transformers.trainer_callback import (
CallbackHandler,
DefaultFlowCallback,
PrinterCallback,
ProgressCallback,
TrainerCallback,
TrainerControl,
TrainerState,
)
from transformers.trainer_pt_utils import (
DistributedLengthGroupedSampler,
DistributedSamplerWithLoop,
DistributedTensorGatherer,
IterableDatasetShard,
LabelSmoother,
LengthGroupedSampler,
SequentialDistributedSampler,
ShardSampler,
distributed_broadcast_scalars,
distributed_concat,
find_batch_size,
get_module_class_from_name,
get_parameter_names,
nested_concat,
nested_detach,
nested_numpify,
nested_truncate,
nested_xla_mesh_reduce,
reissue_pt_warnings,
)
from transformers.trainer_utils import (
PREFIX_CHECKPOINT_DIR,
BestRun,
EvalLoopOutput,
EvalPrediction,
FSDPOption,
HPSearchBackend,
HubStrategy,
IntervalStrategy,
PredictionOutput,
RemoveColumnsCollator,
ShardedDDPOption,
TrainerMemoryTracker,
TrainOutput,
default_compute_objective,
default_hp_space,
denumpify_detensorize,
enable_full_determinism,
find_executable_batch_size,
get_last_checkpoint,
has_length,
number_of_arguments,
seed_worker,
set_seed,
speed_metrics,
)
from transformers.training_args import OptimizerNames, ParallelMode, TrainingArguments
from transformers.utils import (
CONFIG_NAME,
WEIGHTS_INDEX_NAME,
WEIGHTS_NAME,
find_labels,
get_full_repo_name,
is_apex_available,
is_datasets_available,
is_in_notebook,
is_ipex_available,
is_sagemaker_dp_enabled,
is_sagemaker_mp_enabled,
is_torch_tensorrt_fx_available,
is_torch_tpu_available,
is_torchdynamo_available,
logging,
)
from transformers.utils.generic import ContextManagers
_is_native_cpu_amp_available = is_torch_greater_or_equal_than_1_10
DEFAULT_CALLBACKS = [DefaultFlowCallback]
DEFAULT_PROGRESS_CALLBACK = ProgressCallback
if is_in_notebook():
from .utils.notebook import NotebookProgressCallback
DEFAULT_PROGRESS_CALLBACK = NotebookProgressCallback
if is_apex_available():
from apex import amp
if is_datasets_available():
import datasets
if is_torch_tpu_available(check_device=False):
import torch_xla.core.xla_model as xm
import torch_xla.debug.metrics as met
import torch_xla.distributed.parallel_loader as pl
if is_fairscale_available():
dep_version_check("fairscale")
import fairscale
from fairscale.nn.data_parallel import FullyShardedDataParallel as FullyShardedDDP
from fairscale.nn.data_parallel import ShardedDataParallel as ShardedDDP
from fairscale.nn.wrap import auto_wrap
from fairscale.optim import OSS
from fairscale.optim.grad_scaler import ShardedGradScaler
if is_sagemaker_mp_enabled():
import smdistributed.modelparallel.torch as smp
from smdistributed.modelparallel import __version__ as SMP_VERSION
IS_SAGEMAKER_MP_POST_1_10 = version.parse(SMP_VERSION) >= version.parse("1.10")
from .trainer_pt_utils import smp_forward_backward, smp_forward_only, smp_gather, smp_nested_concat
else:
IS_SAGEMAKER_MP_POST_1_10 = False
if TYPE_CHECKING:
import optuna
logger = logging.get_logger(__name__)
# Name of the files used for checkpointing
TRAINING_ARGS_NAME = "training_args.bin"
TRAINER_STATE_NAME = "trainer_state.json"
OPTIMIZER_NAME = "optimizer.pt"
SCHEDULER_NAME = "scheduler.pt"
SCALER_NAME = "scaler.pt"
class OurTrainer(Trainer):
from transformers.trainer_pt_utils import _get_learning_rate, log_metrics, metrics_format, save_metrics, save_state
def _inner_training_loop(
self, batch_size=None, args=None, resume_from_checkpoint=None, trial=None, ignore_keys_for_eval=None
):
"""
We overload the original training loop to add linear probing and MeZO. Search key word "MeZO added"
for those updates.
"""
self._train_batch_size = batch_size
# Data loader and number of training steps
train_dataloader = self.get_train_dataloader()
# MeZO added: Linear probing
if self.args.linear_probing:
def _get_token_prediction_layer(model):
if model.config.model_type == "opt":
return model.lm_head
else:
raise NotImplementedError(model.config.model_type)
def _extract_features(model, *args, **kwargs):
"""some magic for getting features pre last layer"""
features = {}
def __hook(model_, input_, output_):
features["features"] = input_[0].detach()
_get_token_prediction_layer(model).register_forward_hook(__hook)
model.forward(*args, **kwargs)
return features["features"]
logger.info("Linear probing")
logger.info("Starting to get features for training dataset")
targets = []
features = []
with torch.inference_mode():
for step, inputs in enumerate(tqdm(train_dataloader)):
for k, v in inputs.items():
if isinstance(v, torch.Tensor):
inputs[k] = v.to(self.model.device)
feature = _extract_features(self.model, **inputs)
target = inputs["labels"]
# Shift the target (bc it's autoregressive LM) and add the corresponding part
assert not self.args.train_as_classification and self.args.only_train_option
feature, target = feature[:, :-1], target[:, 1:]
for _i, _len in enumerate(inputs["option_len"]):
features.append(feature[_i, -_len:])
targets.append(target[_i, -_len:])
logger.info("Finished getting features for training dataset")
features = torch.cat(features, dim=0).cpu().numpy()
targets = torch.cat(targets, dim=0).cpu().numpy()
# Whether to use bias
if self.model.config.model_type in ["opt", "gpt2"]:
use_bias = False
else:
raise NotImplementedError
# Set early stopping
tol = 0.01 if self.args.lp_early_stopping else 1e-4 # 1e-4 is scipy default
max_iter = 1000 if self.args.lp_early_stopping else 5000
logger.info("Fitting logistic regression...")
reg = LogisticRegressionCV(max_iter=max_iter, fit_intercept=use_bias, multi_class="multinomial", random_state=0, tol=tol, n_jobs=-1).fit(features, targets)
logger.info("Done")
logger.info("Assigning weights to model")
decoder = _get_token_prediction_layer(self.model)
coef_torch = torch.tensor(reg.coef_, device=decoder.weight.device, dtype=decoder.weight.dtype)
if use_bias:
bias_torch = torch.tensor(reg.intercept_, device=decoder.weight.device, dtype=decoder.weight.dtype)
if coef_torch.shape[0] == 1: # The regressor only detects two classes
assert len(reg.classes_) == 2
coef_torch = torch.cat([-coef_torch / 2, coef_torch / 2], dim=0)
if use_bias:
bias_torch = torch.cat([-bias_torch / 2, bias_torch / 2], dim=0)
for _i, token_id in enumerate(reg.classes_):
decoder.weight.data[token_id] = coef_torch[_i]
if use_bias:
decoder.bias.data[token_id] = bias_torch[_i]
return None
# Setting up training control variables:
# number of training epochs: num_train_epochs
# number of training steps per epoch: num_update_steps_per_epoch
# total number of training steps to execute: max_steps
total_train_batch_size = args.train_batch_size * args.gradient_accumulation_steps * args.world_size
len_dataloader = None
if has_length(train_dataloader):
len_dataloader = len(train_dataloader)
num_update_steps_per_epoch = len_dataloader // args.gradient_accumulation_steps
num_update_steps_per_epoch = max(num_update_steps_per_epoch, 1)
num_examples = self.num_examples(train_dataloader)
if args.max_steps > 0:
max_steps = args.max_steps
num_train_epochs = args.max_steps // num_update_steps_per_epoch + int(
args.max_steps % num_update_steps_per_epoch > 0
)
# May be slightly incorrect if the last batch in the training dataloader has a smaller size but it's
# the best we can do.
num_train_samples = args.max_steps * total_train_batch_size
else:
max_steps = math.ceil(args.num_train_epochs * num_update_steps_per_epoch)
num_train_epochs = math.ceil(args.num_train_epochs)
num_train_samples = self.num_examples(train_dataloader) * args.num_train_epochs
elif args.max_steps > 0: # Rely on max_steps when dataloader does not have a working size
max_steps = args.max_steps
# Setting a very large number of epochs so we go as many times as necessary over the iterator.
num_train_epochs = sys.maxsize
num_update_steps_per_epoch = max_steps
num_examples = total_train_batch_size * args.max_steps
num_train_samples = args.max_steps * total_train_batch_size
else:
raise ValueError(
"args.max_steps must be set to a positive value if dataloader does not have a length, was"
f" {args.max_steps}"
)
if DebugOption.UNDERFLOW_OVERFLOW in self.args.debug:
if self.args.n_gpu > 1:
# nn.DataParallel(model) replicates the model, creating new variables and module
# references registered here no longer work on other gpus, breaking the module
raise ValueError(
"Currently --debug underflow_overflow is not supported under DP. Please use DDP"
" (torch.distributed.launch)."
)
else:
debug_overflow = DebugUnderflowOverflow(self.model) # noqa
delay_optimizer_creation = (
self.sharded_ddp is not None
and self.sharded_ddp != ShardedDDPOption.SIMPLE
or is_sagemaker_mp_enabled()
or self.fsdp is not None
)
if args.deepspeed:
deepspeed_engine, optimizer, lr_scheduler = deepspeed_init(
self, num_training_steps=max_steps, resume_from_checkpoint=resume_from_checkpoint
)
self.model = deepspeed_engine.module
self.model_wrapped = deepspeed_engine
self.deepspeed = deepspeed_engine
self.optimizer = optimizer
self.lr_scheduler = lr_scheduler
elif not delay_optimizer_creation:
self.create_optimizer_and_scheduler(num_training_steps=max_steps)
self.state = TrainerState()
self.state.is_hyper_param_search = trial is not None
# Activate gradient checkpointing if needed
if args.gradient_checkpointing:
self.model.gradient_checkpointing_enable()
model = self._wrap_model(self.model_wrapped)
if is_sagemaker_mp_enabled() and resume_from_checkpoint is not None:
self._load_from_checkpoint(resume_from_checkpoint, model)
# for the rest of this function `model` is the outside model, whether it was wrapped or not
if model is not self.model:
self.model_wrapped = model
if delay_optimizer_creation:
self.create_optimizer_and_scheduler(num_training_steps=max_steps)
# Check if saved optimizer or scheduler states exist
self._load_optimizer_and_scheduler(resume_from_checkpoint)
# important: at this point:
# self.model is the Transformers Model
# self.model_wrapped is DDP(Transformers Model), Deepspeed(Transformers Model), etc.
# Train!
logger.info("***** Running training *****")
logger.info(f" Num examples = {num_examples}")
logger.info(f" Num Epochs = {num_train_epochs}")
logger.info(f" Instantaneous batch size per device = {args.per_device_train_batch_size}")
logger.info(f" Total train batch size (w. parallel, distributed & accumulation) = {total_train_batch_size}")
logger.info(f" Gradient Accumulation steps = {args.gradient_accumulation_steps}")
logger.info(f" Total optimization steps = {max_steps}")
logger.info(
f" Number of trainable parameters = {sum(p.numel() for p in model.parameters() if p.requires_grad)}"
)
self.state.epoch = 0
start_time = time.time()
epochs_trained = 0
steps_trained_in_current_epoch = 0
steps_trained_progress_bar = None
# Check if continuing training from a checkpoint
if resume_from_checkpoint is not None and os.path.isfile(
os.path.join(resume_from_checkpoint, TRAINER_STATE_NAME)
):
self.state = TrainerState.load_from_json(os.path.join(resume_from_checkpoint, TRAINER_STATE_NAME))
epochs_trained = self.state.global_step // num_update_steps_per_epoch
if not args.ignore_data_skip:
steps_trained_in_current_epoch = self.state.global_step % (num_update_steps_per_epoch)
steps_trained_in_current_epoch *= args.gradient_accumulation_steps
else:
steps_trained_in_current_epoch = 0
logger.info(" Continuing training from checkpoint, will skip to saved global_step")
logger.info(f" Continuing training from epoch {epochs_trained}")
logger.info(f" Continuing training from global step {self.state.global_step}")
if not args.ignore_data_skip:
logger.info(
f" Will skip the first {epochs_trained} epochs then the first {steps_trained_in_current_epoch} "
"batches in the first epoch. If this takes a lot of time, you can add the `--ignore_data_skip` "
"flag to your launch command, but you will resume the training on data already seen by your model."
)
if self.is_local_process_zero() and not args.disable_tqdm:
steps_trained_progress_bar = tqdm(total=steps_trained_in_current_epoch)
steps_trained_progress_bar.set_description("Skipping the first batches")
# Update the references
self.callback_handler.model = self.model
self.callback_handler.optimizer = self.optimizer
self.callback_handler.lr_scheduler = self.lr_scheduler
self.callback_handler.train_dataloader = train_dataloader
if self.hp_name is not None and self._trial is not None:
# use self._trial because the SigOpt/Optuna hpo only call `_hp_search_setup(trial)` instead of passing trial
# parameter to Train when using DDP.
self.state.trial_name = self.hp_name(self._trial)
if trial is not None:
assignments = trial.assignments if self.hp_search_backend == HPSearchBackend.SIGOPT else trial
self.state.trial_params = hp_params(assignments)
else:
self.state.trial_params = None
# This should be the same if the state has been saved but in case the training arguments changed, it's safer
# to set this after the load.
self.state.max_steps = max_steps
self.state.num_train_epochs = num_train_epochs
self.state.is_local_process_zero = self.is_local_process_zero()
self.state.is_world_process_zero = self.is_world_process_zero()
# tr_loss is a tensor to avoid synchronization of TPUs through .item()
tr_loss = torch.tensor(0.0).to(args.device)
# _total_loss_scalar is updated everytime .item() has to be called on tr_loss and stores the sum of all losses
self._total_loss_scalar = 0.0
self._globalstep_last_logged = self.state.global_step
model.zero_grad()
self.control = self.callback_handler.on_train_begin(args, self.state, self.control)
# Skip the first epochs_trained epochs to get the random state of the dataloader at the right point.
if not args.ignore_data_skip:
for epoch in range(epochs_trained):
is_random_sampler = hasattr(train_dataloader, "sampler") and isinstance(
train_dataloader.sampler, RandomSampler
)
if is_torch_less_than_1_11 or not is_random_sampler:
# We just need to begin an iteration to create the randomization of the sampler.
# That was before PyTorch 1.11 however...
for _ in train_dataloader:
break
else:
# Otherwise we need to call the whooooole sampler cause there is some random operation added
# AT THE VERY END!
_ = list(train_dataloader.sampler)
for epoch in range(epochs_trained, num_train_epochs):
if isinstance(train_dataloader, DataLoader) and isinstance(train_dataloader.sampler, DistributedSampler):
train_dataloader.sampler.set_epoch(epoch)
elif hasattr(train_dataloader, "dataset") and isinstance(train_dataloader.dataset, IterableDatasetShard):
train_dataloader.dataset.set_epoch(epoch)
if is_torch_tpu_available():
parallel_loader = pl.ParallelLoader(train_dataloader, [args.device]).per_device_loader(args.device)
epoch_iterator = parallel_loader
else:
epoch_iterator = train_dataloader
# Reset the past mems state at the beginning of each epoch if necessary.
if args.past_index >= 0:
self._past = None
steps_in_epoch = (
len(epoch_iterator)
if len_dataloader is not None
else args.max_steps * args.gradient_accumulation_steps
)
self.control = self.callback_handler.on_epoch_begin(args, self.state, self.control)
if epoch == epochs_trained and resume_from_checkpoint is not None and steps_trained_in_current_epoch == 0:
self._load_rng_state(resume_from_checkpoint)
step = -1
for step, inputs in enumerate(epoch_iterator):
# Skip past any already trained steps if resuming training
if steps_trained_in_current_epoch > 0:
steps_trained_in_current_epoch -= 1
if steps_trained_progress_bar is not None:
steps_trained_progress_bar.update(1)
if steps_trained_in_current_epoch == 0:
self._load_rng_state(resume_from_checkpoint)
continue
elif steps_trained_progress_bar is not None:
steps_trained_progress_bar.close()
steps_trained_progress_bar = None
if step % args.gradient_accumulation_steps == 0:
self.control = self.callback_handler.on_step_begin(args, self.state, self.control)
# MeZO added: estimate gradient
if args.trainer == "zo":
tr_loss_step = self.zo_step(model, inputs)
else:
if (
((step + 1) % args.gradient_accumulation_steps != 0)
and args.local_rank != -1
and args._no_sync_in_gradient_accumulation
):
# Avoid unnecessary DDP synchronization since there will be no backward pass on this example.
with model.no_sync():
tr_loss_step = self.training_step(model, inputs)
else:
tr_loss_step = self.training_step(model, inputs)
if (
args.logging_nan_inf_filter
and not is_torch_tpu_available()
and (torch.isnan(tr_loss_step) or torch.isinf(tr_loss_step))
):
# if loss is nan or inf simply add the average of previous logged losses
tr_loss += tr_loss / (1 + self.state.global_step - self._globalstep_last_logged)
else:
tr_loss += tr_loss_step
self.current_flos += float(self.floating_point_ops(inputs))
# Optimizer step for deepspeed must be called on every step regardless of the value of gradient_accumulation_steps
if self.deepspeed:
self.deepspeed.step()
if (step + 1) % args.gradient_accumulation_steps == 0 or (
# last step in epoch but step is always smaller than gradient_accumulation_steps
steps_in_epoch <= args.gradient_accumulation_steps
and (step + 1) == steps_in_epoch
):
# MeZO added: update model with the estimated gradient
if args.trainer == "zo":
self.zo_update(model)
else:
# Gradient clipping
if args.max_grad_norm is not None and args.max_grad_norm > 0 and not self.deepspeed:
# deepspeed does its own clipping
if self.do_grad_scaling:
# Reduce gradients first for XLA
if is_torch_tpu_available():
gradients = xm._fetch_gradients(self.optimizer)
xm.all_reduce("sum", gradients, scale=1.0 / xm.xrt_world_size())
# AMP: gradients need unscaling
self.scaler.unscale_(self.optimizer)
if is_sagemaker_mp_enabled() and args.fp16:
self.optimizer.clip_master_grads(args.max_grad_norm)
elif hasattr(self.optimizer, "clip_grad_norm"):
# Some optimizers (like the sharded optimizer) have a specific way to do gradient clipping
self.optimizer.clip_grad_norm(args.max_grad_norm)
elif hasattr(model, "clip_grad_norm_"):
# Some models (like FullyShardedDDP) have a specific way to do gradient clipping
model.clip_grad_norm_(args.max_grad_norm)
else:
# Revert to normal clipping otherwise, handling Apex or full precision
nn.utils.clip_grad_norm_(
amp.master_params(self.optimizer) if self.use_apex else model.parameters(),
args.max_grad_norm,
)
# Optimizer step
optimizer_was_run = True
if self.deepspeed:
pass # called outside the loop
elif is_torch_tpu_available():
if self.do_grad_scaling:
self.scaler.step(self.optimizer)
self.scaler.update()
else:
xm.optimizer_step(self.optimizer)
elif self.do_grad_scaling:
scale_before = self.scaler.get_scale()
self.scaler.step(self.optimizer)
self.scaler.update()
scale_after = self.scaler.get_scale()
optimizer_was_run = scale_before <= scale_after
else:
self.optimizer.step()
if optimizer_was_run and not self.deepspeed:
self.lr_scheduler.step()
model.zero_grad()
self.state.global_step += 1
self.state.epoch = epoch + (step + 1) / steps_in_epoch
self.control = self.callback_handler.on_step_end(args, self.state, self.control)
self._maybe_log_save_evaluate(tr_loss, model, trial, epoch, ignore_keys_for_eval)
else:
self.control = self.callback_handler.on_substep_end(args, self.state, self.control)
if self.control.should_epoch_stop or self.control.should_training_stop:
break
if step < 0:
logger.warning(
"There seems to be not a single sample in your epoch_iterator, stopping training at step"
f" {self.state.global_step}! This is expected if you're using an IterableDataset and set"
f" num_steps ({max_steps}) higher than the number of available samples."
)
self.control.should_training_stop = True
self.control = self.callback_handler.on_epoch_end(args, self.state, self.control)
self._maybe_log_save_evaluate(tr_loss, model, trial, epoch, ignore_keys_for_eval)
if DebugOption.TPU_METRICS_DEBUG in self.args.debug:
if is_torch_tpu_available():
# tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.)
xm.master_print(met.metrics_report())
else:
logger.warning(
"You enabled PyTorch/XLA debug metrics but you don't have a TPU "
"configured. Check your training configuration if this is unexpected."
)
if self.control.should_training_stop:
break
if args.past_index and hasattr(self, "_past"):
# Clean the state at the end of training
delattr(self, "_past")
logger.info("\n\nTraining completed. Do not forget to share your model on huggingface.co/models =)\n\n")
if args.load_best_model_at_end and self.state.best_model_checkpoint is not None:
# Wait for everyone to get here so we are sur the model has been saved by process 0.
if is_torch_tpu_available():
xm.rendezvous("load_best_model_at_end")
elif args.local_rank != -1:
dist.barrier()
elif is_sagemaker_mp_enabled():
smp.barrier()
self._load_best_model()
# add remaining tr_loss
self._total_loss_scalar += tr_loss.item()
train_loss = self._total_loss_scalar / self.state.global_step
metrics = speed_metrics("train", start_time, num_samples=num_train_samples, num_steps=self.state.max_steps)
self.store_flos()
metrics["total_flos"] = self.state.total_flos
metrics["train_loss"] = train_loss
self.is_in_train = False
self._memory_tracker.stop_and_update_metrics(metrics)
self.log(metrics)
run_dir = self._get_output_dir(trial)
checkpoints_sorted = self._sorted_checkpoints(use_mtime=False, output_dir=run_dir)
# Delete the last checkpoint when save_total_limit=1 if it's different from the best checkpoint.
if self.state.best_model_checkpoint is not None and self.args.save_total_limit == 1:
for checkpoint in checkpoints_sorted:
if checkpoint != self.state.best_model_checkpoint:
logger.info(f"Deleting older checkpoint [{checkpoint}] due to args.save_total_limit")
shutil.rmtree(checkpoint)
self.control = self.callback_handler.on_train_end(args, self.state, self.control)
return TrainOutput(self.state.global_step, train_loss, metrics)
############## MeZO ##############
def zo_perturb_parameters(self, random_seed=None, scaling_factor=1):
"""
Perturb the parameters with random vector z.
Input:
- random_seed: random seed for MeZO in-place perturbation (if it's None, we will use self.zo_random_seed)
- scaling_factor: theta = theta + scaling_factor * z * eps
"""
# Set the random seed to ensure that we sample the same z for perturbation/update
torch.manual_seed(random_seed if random_seed is not None else self.zo_random_seed)
for name, param in self.named_parameters_to_optim:
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 * z * self.args.zo_eps
def zo_forward(self, model, inputs):
"""
Get (no gradient) loss from the model. Dropout is turned off too.
"""
model.eval()
if self.args.non_diff:
# Non-differentiable objective (may require autoregressive generation)
return self.zo_forward_nondiff(model, inputs)
with torch.inference_mode():
inputs = self._prepare_inputs(inputs)
with self.compute_loss_context_manager():
loss = self.compute_loss(model, inputs)
if self.args.n_gpu > 1:
# Warning: this is copied from the original Huggingface Trainer. Untested.
loss = loss.mean() # mean() to average on multi-gpu parallel training
return loss.detach()
def zo_forward_nondiff(self, model, inputs):
"""
Get (no gradient) non-diffiable loss from the model.
"""
model.eval()
assert self.args.task_name == "SQuAD", "Non differentiable objective only supports SQuAD for now."
with torch.inference_mode():
inputs = self._prepare_inputs(inputs)
args = self.args
outputs = self.model.generate(
inputs["input_ids"], do_sample=args.sampling, temperature=args.temperature,
num_beams=args.num_beams, top_p=args.top_p, top_k=args.top_k, max_new_tokens=min(args.max_new_tokens, args.max_length - inputs["input_ids"].size(1)),
num_return_sequences=1, eos_token_id=[self.tokenizer.encode(args.eos_token, add_special_tokens=False)[-1], self.tokenizer.eos_token_id],
)
output_text = []
for i in range(len(outputs)):
output_text.append(self.tokenizer.decode(outputs[i][inputs["input_ids"].size(1):], skip_special_tokens=True).strip())
f1s = [f1(output_text[i], inputs['gold'][i]) for i in range(len(output_text))]
return -torch.tensor(np.mean(f1s), dtype=torch.float32)
def zo_step(self, model, inputs):
"""
Estimate gradient by MeZO. Return the loss from f(theta + z)
"""
args = self.args
# What parameters to optimize
self.named_parameters_to_optim = []
for name, param in model.named_parameters():
if param.requires_grad:
self.named_parameters_to_optim.append((name, param))
# Sample the random seed for sampling z
self.zo_random_seed = np.random.randint(1000000000)
# First function evaluation
self.zo_perturb_parameters(scaling_factor=1)
loss1 = self.zo_forward(model, inputs)
# Second function evaluation
self.zo_perturb_parameters(scaling_factor=-2)
loss2 = self.zo_forward(model, inputs)
self.projected_grad = ((loss1 - loss2) / (2 * self.args.zo_eps)).item()
# No gradient accumulation support
assert self.args.gradient_accumulation_steps == 1
# Reset model back to its parameters at start of step
self.zo_perturb_parameters(scaling_factor=1)
return loss1
def zo_update(self, model):
"""
Update the parameters with the estimated gradients.
"""
args = self.args
# Reset the random seed for sampling zs
torch.manual_seed(self.zo_random_seed)
for name, param in self.named_parameters_to_optim:
# Resample z
z = torch.normal(mean=0, std=1, size=param.data.size(), device=param.data.device, dtype=param.data.dtype)
if "bias" not in name and "layer_norm" not in name and "layernorm" not in name:
param.data = param.data - self._get_learning_rate() * (self.projected_grad * z + args.weight_decay * param.data)
else:
param.data = param.data - self._get_learning_rate() * (self.projected_grad * z)
self.lr_scheduler.step()
############## Misc overload functions ##############
def _set_signature_columns_if_needed(self):
"""
We overload this function for non-differentiable objective training to pass "gold" -- the gold text for the task
"""
if self._signature_columns is None:
# Inspect model forward signature to keep only the arguments it accepts.
signature = inspect.signature(self.model.forward)
self._signature_columns = list(signature.parameters.keys())
# Labels may be named label or label_ids, the default data collator handles that.
self._signature_columns += list(set(["label", "label_ids"] + self.label_names))
self._signature_columns += ["gold"]
def save_model(self, output_dir: Optional[str] = None, _internal_call: bool = False):
"""
We overload this function to fix an FSDP saving bug (before fix, it will likely cause OOM)
"""
if output_dir is None:
output_dir = self.args.output_dir
if is_torch_tpu_available():
self._save_tpu(output_dir)
elif is_sagemaker_mp_enabled():
# Calling the state_dict needs to be done on the wrapped model and on all processes.
os.makedirs(output_dir, exist_ok=True)
state_dict = self.model_wrapped.state_dict()
if self.args.should_save:
self._save(output_dir, state_dict=state_dict)
if IS_SAGEMAKER_MP_POST_1_10:
# 'user_content.pt' indicates model state_dict saved with smp >= 1.10
Path(os.path.join(output_dir, "user_content.pt")).touch()
elif (
ShardedDDPOption.ZERO_DP_2 in self.args.sharded_ddp
or ShardedDDPOption.ZERO_DP_3 in self.args.sharded_ddp
or self.fsdp is not None
):
from torch.distributed.fsdp import FullyShardedDataParallel as FSDP, StateDictType, FullStateDictConfig
full_state_dict_config = FullStateDictConfig(offload_to_cpu=True, rank0_only=True)
# Fix the FSDP loading bug
with FSDP.state_dict_type(self.model, StateDictType.FULL_STATE_DICT, full_state_dict_config):
state_dict = self.model.state_dict()
# state_dict = self.model.state_dict()
if self.args.should_save:
self._save(output_dir, state_dict=state_dict)
elif self.deepspeed:
# this takes care of everything as long as we aren't under zero3
if self.args.should_save:
self._save(output_dir)
if is_deepspeed_zero3_enabled():
# It's too complicated to try to override different places where the weights dump gets
# saved, so since under zero3 the file is bogus, simply delete it. The user should
# either user deepspeed checkpoint to resume or to recover full weights use
# zero_to_fp32.py stored in the checkpoint.
if self.args.should_save:
file = os.path.join(output_dir, WEIGHTS_NAME)
if os.path.isfile(file):
# logger.info(f"deepspeed zero3: removing {file}, see zero_to_fp32.py to recover weights")
os.remove(file)
# now save the real model if stage3_gather_16bit_weights_on_model_save=True
# if false it will not be saved.
# This must be called on all ranks
if not self.deepspeed.save_16bit_model(output_dir, WEIGHTS_NAME):
logger.warning(
"deepspeed.save_16bit_model didn't save the model, since"
" stage3_gather_16bit_weights_on_model_save=false. Saving the full checkpoint instead, use"
" zero_to_fp32.py to recover weights"
)
self.deepspeed.save_checkpoint(output_dir)
elif self.args.should_save:
self._save(output_dir)
# Push to the Hub when `save_model` is called by the user.
if self.args.push_to_hub and not _internal_call:
self.push_to_hub(commit_message="Model save")
+355
View File
@@ -0,0 +1,355 @@
import json
import os
import contextlib
from typing import Optional, Union
import numpy as np
from dataclasses import dataclass, is_dataclass, asdict
import logging
import time
from torch.nn import CrossEntropyLoss
import torch.nn.functional as F
from transformers.modeling_outputs import CausalLMOutputWithPast
import torch
from transformers.utils import PaddingStrategy
from transformers import PreTrainedTokenizerBase
from transformers.data.data_collator import DataCollatorMixin
import transformers
from typing import Optional, Union, List, Dict, Any
import signal
from subprocess import call
from collections.abc import Mapping
from typing import Any, Callable, Dict, List, NewType, Optional, Tuple, Union
InputDataClass = NewType("InputDataClass", Any)
from dataclasses import dataclass
from transformers.tokenization_utils_base import PreTrainedTokenizerBase
logger = logging.getLogger(__name__)
def forward_wrap_with_option_len(self, input_ids=None, labels=None, option_len=None, num_options=None, return_dict=None, **kwargs):
"""
This is to replace the original forward function of Transformer models to enable:
(1) Partial target sequence: loss will only be calculated on part of the sequence
(2) Classification-style training: a classification loss (CE) will be calculated over several options
Input:
- input_ids, labels: same as the original forward function
- option_len: a list of int indicating the option lengths, and loss will be calculated only on the
last option_len tokens
- num_options: a list of int indicating the number of options for each example (this will be #label
words for classification tasks and #choices for multiple choice tasks), and a classification loss
will be calculated.
"""
outputs = self.original_forward(input_ids=input_ids, **kwargs)
if labels is None:
return outputs
logits = outputs.logits
loss = None
# Shift so that tokens < n predict n
shift_logits = logits[..., :-1, :].contiguous()
# Here we use input_ids (which should always = labels) bc sometimes labels are correct candidate IDs
shift_labels = torch.clone(input_ids)[..., 1:].contiguous()
shift_labels[shift_labels == self.config.pad_token_id] = -100
# Apply option len (do not calculate loss on the non-option part)
for _i, _len in enumerate(option_len):
shift_labels[_i, :-_len] = -100
# Calculate the loss
loss_fct = CrossEntropyLoss(ignore_index=-100)
if num_options is not None:
# Train as a classification tasks
log_probs = F.log_softmax(shift_logits, dim=-1)
mask = shift_labels != -100 # Option part
shift_labels[~mask] = 0 # So that it doesn't mess up with indexing
selected_log_probs = torch.gather(log_probs, dim=-1, index=shift_labels.unsqueeze(-1)).squeeze(-1) # (bsz x num_options, len)
selected_log_probs = (selected_log_probs * mask).sum(-1) / mask.sum(-1) # (bsz x num_options)
if any([x != num_options[0] for x in num_options]):
# Multi choice tasks with different number of options
loss = 0
start_id = 0
count = 0
while start_id < len(num_options):
end_id = start_id + num_options[start_id]
_logits = selected_log_probs[start_id:end_id].unsqueeze(0) # (1, num_options)
_labels = labels[start_id:end_id][0].unsqueeze(0) # (1)
loss = loss_fct(_logits, _labels) + loss
count += 1
start_id = end_id
loss = loss / count
else:
num_options = num_options[0]
selected_log_probs = selected_log_probs.view(-1, num_options) # (bsz, num_options)
labels = labels.view(-1, num_options)[:, 0] # Labels repeat so we only take the first one
loss = loss_fct(selected_log_probs, labels)
else:
loss = loss_fct(shift_logits.view(-1, self.config.vocab_size), shift_labels.view(-1))
if not return_dict:
output = (logits,) + outputs[1:]
return (loss,) + output if loss is not None else output
return CausalLMOutputWithPast(
loss=loss,
logits=logits,
past_key_values=outputs.past_key_values,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
def encode_prompt(task, template, train_samples, eval_sample, tokenizer, max_length, sfc=False, icl_sfc=False, generation=False, generation_with_gold=False, max_new_tokens=None):
"""
Encode prompts for eval_sample
Input:
- task, template: task and template class
- train_samples, eval_sample: demonstrations and the actual sample
- tokenizer, max_length: tokenizer and max length
- sfc: generate prompts for calibration (surface form competition; https://arxiv.org/abs/2104.08315)
- icl_sfc: generate prompts for ICL version calibration
- generation: whether it is an generation task
- generation_with_gold: whether to include the generation-task gold answers (for training)
- max_new_tokens: max number of new tokens to generate so that we can save enough space
(only for generation tasks)
Output:
- encodings: a list of N lists of tokens. N is the number of options for classification/multiple-choice.
- option_lens: a list of N integers indicating the number of option tokens.
"""
# Demonstrations for ICL
train_prompts = [template.verbalize(sample, sample.correct_candidate).strip() for sample in train_samples]
train_prompts = task.train_sep.join(train_prompts).strip()
# sfc or icl_sfc indicates that this example is used for calibration
if sfc or icl_sfc:
encode_fn = template.encode_sfc; verbalize_fn = template.verbalize_sfc
else:
encode_fn = template.encode; verbalize_fn = template.verbalize
unverbalized_eval_prompt = encode_fn(eval_sample).strip(' ')
if not generation:
# We generate one prompt for each candidate (different classes in classification)
# or different choices in multiple-choice tasks
verbalized_eval_prompts = [verbalize_fn(eval_sample, cand).strip(' ') for cand in eval_sample.candidates]
unverbalized_eval_prompt_length = len(tokenizer.encode(unverbalized_eval_prompt))
option_lens = [(len(tokenizer.encode(verbalized_eval_prompt)) - unverbalized_eval_prompt_length) for verbalized_eval_prompt in verbalized_eval_prompts]
if sfc:
# Without demonstrations
final_prompts = verbalized_eval_prompts
else:
# With demonstrations
final_prompts = [(train_prompts + task.train_sep + eval_prompt).lstrip().strip(' ') for eval_prompt in verbalized_eval_prompts]
else:
assert not sfc and not icl_sfc, "Generation tasks do not support SFC"
if generation_with_gold:
verbalized_eval_prompts = [verbalize_fn(eval_sample, eval_sample.correct_candidate)]
unverbalized_eval_prompt_length = len(tokenizer.encode(unverbalized_eval_prompt))
option_lens = [(len(tokenizer.encode(verbalized_eval_prompt)) - unverbalized_eval_prompt_length) for verbalized_eval_prompt in verbalized_eval_prompts]
final_prompts = [(train_prompts + task.train_sep + eval_prompt).lstrip().strip(' ') for eval_prompt in verbalized_eval_prompts]
else:
option_lens = [0]
final_prompts = [(train_prompts + task.train_sep + unverbalized_eval_prompt).lstrip().strip(' ')]
# Tokenize
encodings = [tokenizer.encode(final_prompt) for final_prompt in final_prompts]
# Truncate (left truncate as demonstrations are less important)
if generation and max_new_tokens is not None:
max_length = max_length - max_new_tokens
if any([len(encoding) > max_length for encoding in encodings]):
logger.warn("Exceed max length")
if tokenizer.add_bos_token:
encodings = [encoding[0:1] + encoding[1:][-(max_length-1):] for encoding in encodings]
else:
encodings = [encoding[-max_length:] for encoding in encodings]
return encodings, option_lens
@dataclass
class ICLCollator:
"""
Collator for ICL
"""
tokenizer: PreTrainedTokenizerBase
def __call__(self, features: List[Dict[str, Any]]) -> Dict[str, Any]:
if not isinstance(features[0], Mapping):
features = [vars(f) for f in features]
first = features[0]
batch = {}
pad_id = self.tokenizer.pad_token_id
pad_ids = {"input_ids": pad_id, "attention_mask": 0, "sfc_input_ids": pad_id, "sfc_attention_mask": 0, "labels": pad_id}
for key in first:
pp = pad_ids[key]
lens = [len(f[key]) for f in features]
max_len = max(lens)
feature = np.stack([np.pad(f[key], (0, max_len - lens[i]), "constant", constant_values=(0, pp)) for i, f in enumerate(features)])
padded_feature = torch.from_numpy(feature).long()
batch[key] = padded_feature
return batch
@dataclass
class DataCollatorWithPaddingAndNesting:
"""
Collator for training
"""
tokenizer: PreTrainedTokenizerBase
padding: Union[bool, str, PaddingStrategy] = True
max_length: Optional[int] = None
pad_to_multiple_of: Optional[int] = None
return_tensors: str = "pt"
def __call__(self, features: List[Dict[str, Any]]) -> Dict[str, Any]:
features = [ff for f in features for ff in f]
batch = self.tokenizer.pad(
features,
padding=self.padding,
max_length=self.max_length,
pad_to_multiple_of=self.pad_to_multiple_of,
return_tensors=self.return_tensors,
)
if "label" in batch:
batch["labels"] = batch["label"]
del batch["label"]
if "label_ids" in batch:
batch["labels"] = batch["label_ids"]
del batch["label_ids"]
return batch
@dataclass
class NondiffCollator(DataCollatorMixin):
"""
Collator for non-differentiable objectives
"""
tokenizer: PreTrainedTokenizerBase
padding: Union[bool, str, PaddingStrategy] = True
max_length: Optional[int] = None
pad_to_multiple_of: Optional[int] = None
label_pad_token_id: int = -100
return_tensors: str = "pt"
def torch_call(self, features):
import torch
label_name = "label" if "label" in features[0].keys() else "labels"
labels = [feature[label_name] for feature in features] if label_name in features[0].keys() else None
no_labels_features = [{k: v for k, v in feature.items() if k != label_name and k != "gold"} for feature in features]
batch = self.tokenizer.pad(
no_labels_features,
padding=self.padding,
max_length=self.max_length,
pad_to_multiple_of=self.pad_to_multiple_of,
return_tensors="pt",
)
if labels is None:
return batch
sequence_length = batch["input_ids"].shape[1]
padding_side = self.tokenizer.padding_side
def to_list(tensor_or_iterable):
if isinstance(tensor_or_iterable, torch.Tensor):
return tensor_or_iterable.tolist()
return list(tensor_or_iterable)
if padding_side == "right":
batch[label_name] = [
to_list(label) + [self.label_pad_token_id] * (sequence_length - len(label)) for label in labels
]
else:
batch[label_name] = [
[self.label_pad_token_id] * (sequence_length - len(label)) + to_list(label) for label in labels
]
batch[label_name] = torch.tensor(batch[label_name], dtype=torch.int64)
if "gold" in features[0]:
batch["gold"] = [feature["gold"] for feature in features]
return batch
class SIGUSR1Callback(transformers.TrainerCallback):
"""
This callback is used to save the model when a SIGUSR1 signal is received
(SLURM stop signal or a keyboard interruption signal).
"""
def __init__(self) -> None:
super().__init__()
self.signal_received = False
signal.signal(signal.SIGUSR1, self.handle_signal)
signal.signal(signal.SIGINT, self.handle_signal)
logger.warn("Handler registered")
def handle_signal(self, signum, frame):
self.signal_received = True
logger.warn("Signal received")
def on_step_end(self, args, state, control, **kwargs):
if self.signal_received:
control.should_save = True
control.should_training_stop = True
def on_train_end(self, args, state, control, **kwargs):
if self.signal_received:
exit(0)
@dataclass
class Prediction:
correct_candidate: Union[int, str]
predicted_candidate: Union[int, str]
@contextlib.contextmanager
def count_time(name):
logger.info("%s..." % name)
start_time = time.time()
try:
yield
finally:
logger.info("Done with %.2fs" % (time.time() - start_time))
@contextlib.contextmanager
def temp_seed(seed):
state = np.random.get_state()
np.random.seed(seed)
try:
yield
finally:
np.random.set_state(state)
class EnhancedJSONEncoder(json.JSONEncoder):
def default(self, o):
if is_dataclass(o):
return asdict(o)
return super().default(o)
def write_predictions_to_file(final_preds, output):
with open(output, "w") as f:
for pred in final_preds:
f.write(json.dumps(pred, cls=EnhancedJSONEncoder) + "\n")
def write_metrics_to_file(metrics, output):
json.dump(metrics, open(output, "w"), cls=EnhancedJSONEncoder, indent=4)
+81
View File
@@ -0,0 +1,81 @@
# MeZO on Medium-sized Masked Language Models
This part of the code is for MeZO experiments on RoBERTa-large. It is based on [LM-Kernel-FT](https://github.com/princeton-nlp/LM-Kernel-FT) and [LM-BFF](https://github.com/princeton-nlp/LM-BFF).
## Installation
Please install the latest versions of PyTorch (`pytorch` following [https://pytorch.org](https://pytorch.org)) and Transformers (`transformers`). This code is tested on `torch==2.1.0.dev20230514+cu118` and `transformers==4.28.1` with Python 3.9.7, but should work with older/later versions of these packages too.
## Prepare the data
We pack the datasets [here](https://nlp.cs.princeton.edu/projects/lm-bff/datasets.tar). Please download it and extract the files to `./data/original`, or run the following commands:
```bash
cd data
bash download_dataset.sh
```
Then use the following command (in the `medium_models` folder) to generate the data we need:
```bash
for K in 16 512; do
# Generate k-shot splits for seeds 13,21,42,87,100 with a maximum of 1k test examples in data/k-shot-1k-test,
# where k is the number of training/validation examples per label
python tools/generate_k_shot_data.py --mode k-shot-1k-test --k $K
done
```
See `tools/generate_k_shot_data.py` for more options. For results in the paper, we use the default options: we take `K=16` and `K=512` and take 5 different seeds of 13, 21, 42, 87, 100. The few-shot data will be generated to `data/k-shot-1k-test`. In the directory of each dataset, there will be folders named as `$K-$SEED` indicating different dataset samples.
## Usage
Use `run.py` for all functions and refer to `run.py` for the usage of all arguments.
```bash
python run.py {ARGUMENTS}
```
To reproduce our results in the paper, we also provide two example files `finetune.sh` (for all fine-tuning experiments) and `mezo.sh` (for all MeZO experiments). You can run them directly with the following commands (we use the following six datasets in our experiments -- `SST-2`, `sst-5`, `SNLI`, `MNLI`, `RTE`, and `trec`):
```bash
# Adam fine-tuning
TASK=SST-2 K=16 SEED=42 BS=8 LR=1e-5 MODEL=roberta-large bash finetune.sh
# Adam fine-tuning + prefix-tuning
TASK=SST-2 K=16 SEED=42 BS=8 LR=1e-2 MODEL=roberta-large EXTRA_TAG=prefix bash finetune.sh --prefix_tuning --num_prefix 5 --no_reparam --prefix_init_by_real_act
# Adam fine-tuning + LoRA
TASK=SST-2 K=16 SEED=42 BS=8 LR=1e-4 MODEL=roberta-large EXTRA_TAG=lora bash finetune.sh --apply_lora --lora_r 8 --lora_alpha 16
# MeZO
TASK=SST-2 K=16 SEED=42 BS=64 LR=1e-6 EPS=1e-3 MODEL=roberta-large bash mezo.sh
# MeZO + prefix-tuning
TASK=SST-2 K=16 SEED=42 BS=64 LR=1e-2 EPS=1e-1 MODEL=roberta-large EXTRA_TAG=prefix bash mezo.sh --prefix_tuning --num_prefix 5 --no_reparam --prefix_init_by_real_act
# MeZO + LoRA
TASK=SST-2 K=16 SEED=42 BS=64 LR=1e-4 EPS=1e-3 MODEL=roberta-large EXTRA_TAG=lora bash mezo.sh --apply_lora --lora_r 8 --lora_alpha 16
```
You can designate different hyperparameters by passing different environment variables as shown above. You can also directly add arguments at the end of the command to override the default ones. For all the hyperparameters you can control via environment variables, please refer to `finetune.sh` and `mezo.sh`. For the hyperparameters we used in our experiments, please refer to Appendix D of our paper.
## Gather results
All the results will be stored in `./log`. To analyze the results (for example, examine the grid search), use the following command
```bash
python tools/gather_result.py --condition "{'tag': 'k16-roberta-large-ft', 'task_name': 'sst-2'}"
```
Then the program will find all the trials that satisfy the condition in `./log`, and print the mean/std of the final results. Note that the task names are all lower-cased here.
## Ablations
RoBERTa-large models can be fine-tuned on most single GPUs, so we did not yet implement all of the memory-efficient ZO variants discussed in Appendix B. For now, if you want to run ablations other ZO ablations, you can add the flag `--zero_order_use_trainer_optim`, which will store the ZO gradients in the `param.grad` buffer and then use a PyTorch optimizer as usual. This causes the total memory consumption for ZO to be twice that of inference, which is still substantially less than that of backpropagation. The ablations can then be run with the additional following flags:
- ZO-Adam: `--optimizer "adam"`
- ZO-Momentum: `--momentum <beta>`
- $n$-SPSA with $n>1$: `--zero_order_sample <n>` and you can add a linear or constant scheduler on it with `--zero_order_sample_scheduler {"linear", "constant"}`
- No prompt: `--few_shot_type finetune`
Appendix B discusses variants of ZO that modify the expectation and the variance. To run those one can use the following flags.
- Modify variance: `--zo_variant {"grad_norm", "param_norm"}`
- Recompute the control variate at the start of each epoch: `--recmopute_norms`
- Modify expectation: `--change_grad_estimate`
File diff suppressed because it is too large. Load diff
+695
View File
@@ -0,0 +1,695 @@
"""Dataset utils for different data settings for GLUE."""
import os
import logging
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
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:
logger.info("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])
logger.info("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:
logger.info("There are %d templates. Multiply num_sample by %d" % (len(args.template_list), len(args.template_list)))
self.num_sample *= len(args.template_list)
logger.info("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,
),
)
logger.info(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)
logger.info(
f"Loading features from cached file {cached_features_file} [took %.3f s]", time.time() - start
)
else:
logger.info(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.
logger.info(
"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)))
logger.info("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:
logger.info("*** 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:
logger.info("*** Example ***")
logger.info("guid: %s" % (example.guid))
logger.info("features: %s" % features)
logger.info("text: %s" % self.tokenizer.decode(features.input_ids))
return features
@@ -0,0 +1,298 @@
from transformers.utils import logging
import torch
import torch.nn.functional as F
from sklearn.svm import SVC, SVR
from sklearn.linear_model import LogisticRegressionCV
logger = logging.get_logger(__name__)
class BaseKernelSolver:
def __init__(self, args):
self.args = args
# initialized with fit()
self.num_labels = None
self.kernel_dtype = None
def get_regularized_kernel(self, kernel):
if self.args.kernel_regularization:
_, S, _ = torch.svd(kernel)
op_norm = S.max()
reg = (self.args.kernel_regularization * op_norm).to(kernel.dtype)
identity = torch.eye(kernel.shape[1], dtype=kernel.dtype).unsqueeze(0)
return kernel + identity * reg
else:
return kernel
def metrics(self):
return {}
def get_target_coords(self, targets):
if self.num_labels == 1: # Regression
return targets.flatten().to(self.kernel_dtype).unsqueeze(1)
else:
return torch.nn.functional.one_hot(targets.flatten(), self.num_labels).to(self.kernel_dtype)
def loss(self, preds, targets):
targets_coords = self.get_target_coords(targets)
return 1/targets_coords.shape[0] * ((preds - targets_coords)**2).sum().item()
def fit(self, train_kernel, train_targets, train_logits=None):
raise NotImplementedError("BaseKernelSolver is just the abstract base class")
def predict(self, eval_kernel, eval_targets, eval_logits=None):
raise NotImplementedError("BaseKernelSolver is just the abstract base class")
class LstsqKernelSolver(BaseKernelSolver):
def __init__(self, args):
super().__init__(args)
# initialized with fit()
self.kernel_solution = None
self.residual = None
self.rank = None
def metrics(self):
metrics_dict = super().metrics()
if self.rank is not None:
if self.rank.numel() > 1:
for i,r in enumerate(self.rank.tolist()):
metrics_dict["rank{}".format(i)] = r
else:
metrics_dict["rank0"] = self.rank.item()
return metrics_dict
def fit(self, train_kernel, train_targets, train_logits=None):
self.num_labels = train_kernel.size(0)
self.kernel_dtype = train_kernel.dtype
kernel = self.get_regularized_kernel(train_kernel)
train_targets_coords = self.get_target_coords(train_targets)
if train_logits is not None and self.args.f0_scaling > 0:
train_targets_coords -= train_logits / self.args.f0_scaling
self.kernel_solution, self.residuals, self.rank, _ = torch.linalg.lstsq(kernel, train_targets_coords.t())
def predict(self, eval_kernel, eval_targets, eval_logits=None, **unused_kwargs):
assert self.kernel_solution is not None, "Must call fit() before predict()"
assert eval_kernel.size(0) == self.num_labels, "Number of labels in eval_kernel must match fit()"
eval_preds = torch.bmm(
eval_kernel.transpose(1, 2),
self.kernel_solution.unsqueeze(2)
).squeeze(2).transpose(0, 1) # shape [#dataset_outer, #classes]
if eval_logits is not None and self.args.f0_scaling > 0:
eval_preds += eval_logits / self.args.f0_scaling
eval_loss = self.loss(eval_preds, eval_targets)
return eval_loss, eval_preds
class AsymmetricLstsqKernelSolver(LstsqKernelSolver):
def __init__(self, args):
super().__init__(args)
self.N = None
self.train_targets = None
def fit(self, train_kernel, train_targets, train_logits=None):
self.num_labels = train_kernel.size(0)
self.kernel_dtype = train_kernel.dtype
assert self.num_labels == 1, "SVMKernelSolver only works for regression tasks or binary_classification"
kernel = self.get_regularized_kernel(train_kernel)
train_targets_coords = self.get_target_coords(train_targets)
if train_logits is not None and self.args.f0_scaling > 0:
train_targets_coords -= train_logits / self.args.f0_scaling
kernel = kernel.squeeze()
H = torch.zeros(kernel.shape)
Y = train_targets_coords.squeeze()
N = H.shape[0]
for i in range(N):
for j in range(N):
H[i,j] = Y[i] * (kernel[i,j]* Y[j])
# # system with biases
# A = torch.zeros(2*N + 2, 2*N + 2, dtype=self.kernel_dtype)
# A[0, 2:2+N] = Y
# A[1, 2+N:] = Y
# A[2:2+N, 0] = Y
# A[2+N:, 1] = Y
# A[2:2+N, 2:2+N] = torch.eye(N) / self.args.kernel_gamma # scale by 1/gamma later
# A[2:2+N, 2+N:] = H
# A[2+N:, 2:2+N] = H.T
# A[2+N:, 2+N:] = torch.eye(N) / self.args.kernel_gamma # scale by 1/gamma later
# B = torch.zeros(2*N+2, dtype=self.kernel_dtype)
# B[2:] = 1
# system without biases
A = torch.zeros(2*N, 2*N, dtype=self.kernel_dtype)
A[:N, :N] = torch.eye(N) / self.args.kernel_gamma # scale by 1/gamma later
A[:N, N:] = H
A[N:, :N] = H.T
A[N:, N:] = torch.eye(N) / self.args.kernel_gamma # scale by 1/gamma later
B = torch.ones(2*N, dtype=self.kernel_dtype)
self.N = N
self.Y = Y
self.kernel_solution, self.residuals, self.rank, _ = torch.linalg.lstsq(A, B)
def predict(self, eval_kernel, eval_targets, eval_logits=None, eval_kernel_flipped=None, **unused_kwargs):
assert self.kernel_solution is not None, "Must call fit() before predict()"
assert eval_kernel.size(0) == self.num_labels, "Number of labels in eval_kernel must match fit()"
N = self.N
# beta_bias = self.kernel_solution[0]
# alpha_bias = self.kernel_solution[1]
# alpha = self.kernel_solution[2:2+N].unsqueeze(0)
# beta = self.kernel_solution[2+N:].unsqueeze(0)
alpha = self.kernel_solution[:N].unsqueeze(0)
beta = self.kernel_solution[N:].unsqueeze(0)
omega = torch.bmm(
eval_kernel.transpose(1, 2),
(alpha*self.Y).unsqueeze(2)
).squeeze(2).transpose(0, 1) #+ alpha_bias
nu = torch.bmm(
eval_kernel_flipped.transpose(1, 2),
(beta*self.Y).unsqueeze(2)
).squeeze(2).transpose(0, 1) #+ beta_bias
eval_preds = (self.args.kernel_lambda * omega + (1-self.args.kernel_lambda) * nu)
if eval_logits is not None and self.args.f0_scaling > 0:
eval_preds += eval_logits / self.args.f0_scaling
eval_loss = self.loss(eval_preds, eval_targets)
return eval_loss, eval_preds
class SVRKernelSolver(BaseKernelSolver):
def __init__(self, args):
super().__init__(args)
self.svms = None
def fit(self, train_kernel, train_targets, train_logits=None):
self.num_labels = train_kernel.size(0)
self.kernel_dtype = train_kernel.dtype
kernel = self.get_regularized_kernel(train_kernel)
train_targets_coords = self.get_target_coords(train_targets)
if train_logits is not None and self.args.f0_scaling > 0:
train_targets_coords -= train_logits / self.args.f0_scaling
self.svms = []
for k in range(self.num_labels):
svm = SVR(kernel='precomputed')
svm.fit(kernel[k].cpu().numpy(), train_targets_coords[:,k].cpu().t().numpy())
self.svms.append(svm)
def predict(self, eval_kernel, eval_targets, eval_logits=None, **unused_kwargs):
assert self.svms is not None, "Must call fit() before predict()"
assert eval_kernel.size(0) == self.num_labels, "Number of labels in eval_kernel must match fit()"
eval_preds = []
for k in range(self.num_labels):
predict_k = self.svms[k].predict(eval_kernel[k].cpu().t().numpy())
eval_preds.append(torch.tensor(predict_k, dtype=self.kernel_dtype, device=eval_kernel.device))
eval_preds = torch.stack(eval_preds, dim=1)
print(eval_preds, eval_targets)
if eval_logits is not None and self.args.f0_scaling > 0:
eval_preds += eval_logits / self.args.f0_scaling
eval_loss = self.loss(eval_preds, eval_targets)
return eval_loss, eval_preds
class SVCKernelSolver(BaseKernelSolver):
def __init__(self, args):
super().__init__(args)
self.svms = None
def fit(self, train_kernel, train_targets, train_logits=None):
self.num_labels = train_kernel.size(0)
self.kernel_dtype = train_kernel.dtype
assert self.num_labels == 1, "SVMKernelSolver only works for binary_classification"
assert train_logits is None, "SVMKernelSolver does not support train_logits"
kernel = self.get_regularized_kernel(train_kernel)
train_targets = ((train_targets + 1) / 2).int() # convert back from {-1, 1} to {0, 1}
self.svms = []
for k in range(self.num_labels):
svm = SVC(kernel='precomputed')
svm.fit(kernel[k].cpu().numpy(), train_targets.cpu().numpy())
self.svms.append(svm)
def predict(self, eval_kernel, eval_targets, eval_logits=None, **unused_kwargs):
assert self.svms is not None, "Must call fit() before predict()"
assert eval_kernel.size(0) == self.num_labels, "Number of labels in eval_kernel must match fit()"
assert eval_logits is None, "SVMKernelSolver does not support train_logits"
eval_preds = []
for k in range(self.num_labels):
predict_k = self.svms[k].predict(eval_kernel[k].cpu().t().numpy())
eval_preds.append(torch.tensor(predict_k, dtype=self.kernel_dtype, device=eval_kernel.device))
eval_preds = torch.stack(eval_preds, dim=1)
eval_preds = (eval_preds * 2 - 1) # convert back from {0, 1} to {-1, 1}
eval_loss = self.loss(eval_preds, eval_targets)
return eval_loss, eval_preds
class LogisticKernelSolver(BaseKernelSolver):
def __init__(self, args):
super().__init__(args)
self.logistic_model = None
def fit(self, train_kernel, train_targets, train_logits=None):
self.num_labels = train_kernel.size(0)
self.kernel_dtype = train_kernel.dtype
assert self.num_labels == 1, "SVMKernelSolver only works for binary_classification"
kernel = self.get_regularized_kernel(train_kernel).squeeze(0)
train_targets = ((train_targets + 1) / 2).int() # convert back from {-1, 1} to {0, 1}
self.logistic_model = LogisticRegressionCV(max_iter=10000, random_state=0)
self.logistic_model.fit(kernel.cpu().numpy(), train_targets.cpu().numpy())
def predict(self, eval_kernel, eval_targets, eval_logits=None, **unused_kwargs):
assert self.logistic_model is not None, "Must call fit() before predict()"
assert eval_kernel.size(0) == self.num_labels, "Number of labels in eval_kernel must match fit()"
log_proba = self.logistic_model.predict_log_proba(eval_kernel.cpu().squeeze().t().numpy())
log_proba = torch.tensor(log_proba, dtype=self.kernel_dtype, device=eval_kernel.device)
eval_loss = self.loss(log_proba, eval_targets)
eval_preds = (log_proba[:,1] - log_proba[:,0]).unsqueeze(1)
return eval_loss, eval_preds
def loss(self, preds, targets):
targets = ((targets + 1) / 2).long() # convert back from {-1, 1} to {0, 1}
return F.cross_entropy(preds, targets).item()
SOLVERS = {
"lstsq": LstsqKernelSolver,
"svr": SVRKernelSolver,
"svc": SVCKernelSolver,
"asym": AsymmetricLstsqKernelSolver,
"logistic": LogisticKernelSolver
}
@@ -0,0 +1,471 @@
########## The following part was originally copied from Transformers' trainer (3.4.0) and then changed heavily to compute eNTKs. ##########
# coding=utf-8
# Copyright 2020-present the HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
The trainer for computing eNTKs
"""
import os
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
import re
import torch
import torch.nn as nn
from torch.utils.data.dataloader import DataLoader
from torch.utils.data.dataset import Dataset
from torch.utils.data.sampler import SequentialSampler
from functorch import vmap, jvp, jacrev, make_functional_with_buffers
import transformers
from transformers.data.data_collator import DataCollator
from transformers.file_utils import is_torch_tpu_available
from transformers.modeling_utils import PreTrainedModel
from transformers.training_args import TrainingArguments
from transformers.trainer import SequentialDistributedSampler
from transformers.trainer_utils import PredictionOutput, EvalPrediction
from transformers.utils import logging
if is_torch_tpu_available():
import torch_xla.core.xla_model as xm
import gc
from transformers.trainer_utils import TrainOutput
from src.linearhead_trainer import varsize_tensor_all_gather, LinearHeadTrainer
import numpy as np
from tqdm import tqdm
from src.kernel_solvers import SOLVERS
logger = logging.get_logger(__name__)
class LogitModelWrapper(nn.Module):
def __init__(self, model, binary_classification):
super().__init__()
self.model = model
self.binary_classification = binary_classification
def forward(self, input_ids, attention_mask, mask_pos):
logits = self.model(input_ids, attention_mask, mask_pos=mask_pos)[0] # don't provide labels
if self.binary_classification:
assert logits.size(1) == 2, "--binary_classification should have 2 logits"
logits = (logits[:,1] - logits[:,0]).unsqueeze(-1)
return logits
# label = (label * 2 - 1).float() # convert from {0, 1} to {-1, 1}
def param_to_buffer(module, module_name, predicate):
"""Turns all parameters of a module into buffers."""
modules = module.named_modules(prefix=str(module_name))
next(modules) # Skip itself
params = []
for name, param in module.named_parameters(recurse=False, prefix=str(module_name)):
if predicate(name):
params.append((name.split(".")[-1], param))
for name, param in params:
delattr(module, name) # Unregister parameter
module.register_buffer(name, param)
for name, module in modules:
param_to_buffer(module, name, predicate)
class KernelTrainerFunc(LinearHeadTrainer):
"""
Adding some functions based on Transformers' Trainer class.
"""
def __init__(
self,
model: PreTrainedModel,
args: TrainingArguments,
data_collator: Optional[DataCollator] = None,
train_dataset: Optional[Dataset] = None,
eval_dataset: Optional[Dataset] = None,
*posargs,
**kwargs
):
super().__init__(model, args, data_collator, train_dataset, eval_dataset, *posargs, **kwargs)
self.grad_dim = None
self.train_train_kernel = None
self.train_targets = None
self.num_labels = None
self.kernel_formula = args.kernel_formula
def convert_to_buffer(name):
if args.exclude_embeddings:
if "embed" in name:
logger.info("Excluding {}".format(name))
return True
if args.exclude_head:
if "head" in name:
logger.info("Excluding {}".format(name))
return True
if args.only_biases:
if "bias" not in name:
logger.info("Excluding {}".format(name))
return True
if args.exclude_first_layers != -1:
if 'layers' in name:
layer_num = re.search('layers.(.+?).[a-z]', name).group(1)
if int(layer_num) < args.exclude_first_layers:
return True
else:
return False
elif 'embed_tokens' in name or 'embed_positions' in name:
return True
if model.model_args.apply_lora:
if name.startswith('roberta') and "lora" not in name:
logger.info("Excluding {}".format(name))
return True
return False
param_to_buffer(self.model, "", convert_to_buffer)
def get_unshuffled_dataloader(self, dataset: Optional[Dataset] = None, sharded: bool = False, batch_size: Optional[int] = -1):
if sharded and is_torch_tpu_available():
sampler = SequentialDistributedSampler(
dataset, num_replicas=xm.xrt_world_size(), rank=xm.get_ordinal()
)
elif sharded and self.args.local_rank != -1:
sampler = SequentialDistributedSampler(dataset)
else:
sampler = SequentialSampler(dataset)
bs = self.args.per_device_eval_batch_size if batch_size == -1 else batch_size
data_loader = DataLoader(
dataset,
sampler=sampler,
batch_size=bs,
collate_fn=self.data_collator,
drop_last=self.args.dataloader_drop_last,
)
return data_loader
def profile_memory(self):
import gc
for obj in gc.get_objects():
try:
if torch.is_tensor(obj) or (hasattr(obj, 'data') and torch.is_tensor(obj.data)):
print(type(obj), obj.size())
except:
pass
def compute_kernel_inner(self, curried_fn, curried_jacobian_fn, grads_outer, dataset_inner):
# Use per_device_eval_batch_size for outer loop (which is always the training dataset
dataloader_inner = self.get_unshuffled_dataloader(dataset_inner, sharded=False, batch_size=self.args.per_device_eval_batch_size)
kernel_blocks = []
targets_inner = []
for inputs_inner in tqdm(dataloader_inner, desc="Computing kernel inner"):
for k, v in inputs_inner.items():
if isinstance(v, torch.Tensor):
inputs_inner[k] = v.to(self.args.device)
def get_ntk_slice(tangents):
_, jvps = curried_fn(inputs_inner.get("input_ids"), inputs_inner.get("attention_mask"), inputs_inner.get("mask_pos"), tangents)
return jvps
if self.args.kernel_formula == "signgd":
grads_inner = curried_jacobian_fn(inputs_inner.get("input_ids"), inputs_inner.get("attention_mask"), inputs_inner.get("mask_pos"))
block = sum(torch.einsum('olw,ikw->olik', j1.sign().flatten(2).to(torch.float64), j2.sign().flatten(2).to(torch.float64)).cpu() for j1, j2 in zip(grads_outer, grads_inner))
else:
block = vmap(vmap(get_ntk_slice))(grads_outer).to(torch.float64).cpu() # N_outer x C_outer x N_inner x C_inner
kernel_blocks.append(block.detach())
label = inputs_inner.get("labels")
if self.args.binary_classification:
label = (label * 2 - 1).float() # convert from {0, 1} to {-1, 1}
targets_inner.append(label)
# del grads_inner
del block
del inputs_inner
torch.cuda.empty_cache()
gc.collect()
return (
torch.cat(kernel_blocks, dim=2) if kernel_blocks else torch.tensor([]),
torch.cat(targets_inner, dim=0) if targets_inner else torch.tensor([])
)
def compute_kernel_outer(self, dataset_outer, dataset_inner):
# Use train_batch_size for outer loop (which is always the training dataset)
dataloader_outer = self.get_unshuffled_dataloader(dataset_outer, sharded=True, batch_size=self.args.per_device_train_batch_size)
model_wrapper = LogitModelWrapper(self.model, self.args.binary_classification)
model_wrapper.eval()
for param in model_wrapper.parameters():
param.requires_grad_(True)
model_fn, params, buffers = make_functional_with_buffers(model_wrapper)
jacobian_fn = jacrev(model_fn)
def curried_jacobian_fn(input_ids, attention_mask, mask_pos):
return jacobian_fn(params, buffers, input_ids, attention_mask, mask_pos)
def curried_fn(input_ids, attention_mask, mask_pos, tangent):
def curried_model_fn(params_):
return model_fn(params_, buffers, input_ids, attention_mask, mask_pos)
return jvp(curried_model_fn, (params,), (tangent,))
kernel_rows = []
inner_targets = None
for inputs_outer in tqdm(dataloader_outer, desc="Computing kernel outer"):
for k, v in inputs_outer.items():
if isinstance(v, torch.Tensor):
inputs_outer[k] = v.to(self.args.device)
grads_outer = curried_jacobian_fn(inputs_outer.get("input_ids"), inputs_outer.get("attention_mask"), inputs_outer.get("mask_pos"))
if self.args.kernel_formula == 'asymmetric_signgd':
grads_outer = tuple(g.sign() for g in grads_outer)
# assert len(tuple(model_wrapper.model.named_parameters())) == len(grads_outer)
# for (name,param), grad in zip(model_wrapper.named_parameters(), grads_outer):
# print(name, grad[(grad != 0).all(-1)])
# assert param.shape == grad.shape[2:], f"{name} {param.shape} {grad[2:].shape}"
# if (grad == 0).all():
# print(name, param.numel())
if self.grad_dim is None:
self.grad_dim = sum(np.prod(x.shape[2:]) for x in grads_outer)
# assert self.grad_dim == num_params, "gradient dim not constant: {} and {}".format(self.grad_dim, num_params)
kernel_blocks, inner_targets = (
self.compute_kernel_inner(curried_fn, curried_jacobian_fn, grads_outer, dataset_inner))
kernel_rows.append(kernel_blocks)
del grads_outer
del inputs_outer
del kernel_blocks
torch.cuda.empty_cache()
gc.collect()
kernel = torch.cat(kernel_rows, dim=0)
return (
kernel,
inner_targets
)
def compute_kernel_sharded(self, dataset_outer, dataset_inner):
assert self.kernel_formula in ["sgd", "asymmetric_signgd", "signgd"], "only sgd and asymmetric_signgd are supported by torchfunc for now"
with torch.no_grad():
kernel, inner_targets = self.compute_kernel_outer(dataset_outer, dataset_inner)
if self.args.local_rank != -1:
logger.info("Starting to gather kernel across GPUs")
kernel = varsize_tensor_all_gather(kernel.to(self.args.device), torch.distributed.get_world_size())
logger.info("Finished gathering kernel across GPUs")
return kernel, inner_targets
def compute_model_logits_cached(self, eval_dataset):
if self.args.load_kernels is not None:
output_dir = self.args.load_kernels
else:
output_dir = self.args.output_dir
logit_file_name = f"{eval_dataset.mode}_logits_{eval_dataset.task_name}.pt"
logit_path = os.path.join(output_dir, logit_file_name)
if os.path.exists(logit_path) and not self.args.overwrite_kernels:
logger.info(f"Starting to load logits from {logit_path}.")
logits, targets = torch.load(logit_path)
logger.info(f"Finished loading logits from {logit_path}.")
else:
logger.info(f"Starting to compute the {eval_dataset.mode} logits.")
dataloader = self.get_unshuffled_dataloader(eval_dataset)
model_wrapper = LogitModelWrapper(self.model, self.args.binary_classification)
model_wrapper.eval()
logits = []
targets = []
with torch.no_grad():
for inputs in dataloader:
for k, v in inputs.items():
if isinstance(v, torch.Tensor):
inputs[k] = v.to(self.args.device)
label = inputs.get("labels")
if self.args.binary_classification:
label = (label * 2 - 1).float() # convert from {0, 1} to {-1, 1}
preds = model_wrapper(inputs.get("input_ids"), inputs.get("attention_mask"), inputs.get("mask_pos"))
logits.append(preds.detach().cpu())
targets.append(label.cpu())
logits = torch.cat(logits, dim=0)
targets = torch.cat(targets, dim=0)
logger.info(f"Finished computing the {eval_dataset.mode} logits.")
if self.is_world_process_zero():
torch.save((logits, targets), logit_path)
return logits, targets
def reshape_kernel_and_targets(self, kernel, targets):
# reshape kernel to previous format
if self.num_labels is None:
self.num_labels = kernel.shape[1]
assert self.num_labels == kernel.shape[1], "label dim not constant: {} and {}".format(self.num_labels, kernel.shape[1])
assert self.num_labels == kernel.shape[3], "label dim not constant: {} and {}".format(self.num_labels, kernel.shape[3])
if self.num_labels > 1: # multi logit
targets = torch.nn.functional.one_hot(targets.squeeze(), self.num_labels)
size1 = kernel.shape[0] * kernel.shape[1]
size2 = kernel.shape[2] * kernel.shape[3]
# kernel = kernel.transpose(0, 1).transpose(2, 3)
return kernel.reshape(1, size1, size2), targets.reshape(-1)
def compute_kernel_cached(self, eval_dataset):
kernel_file_name = f"{eval_dataset.mode}_kernels_{eval_dataset.task_name}.pt"
kernel_path = os.path.join(self.args.output_dir, kernel_file_name)
if os.path.exists(kernel_path) and not self.args.overwrite_kernels:
logger.info(f"Starting to load kernels from {kernel_path}.")
(train_eval_kernel, eval_targets) = torch.load(kernel_path)
logger.info(f"Finished loading kernels from {kernel_path}.")
else:
logger.info(f"Starting to compute the train-{eval_dataset.mode} kernel.")
train_eval_kernel, eval_targets = self.compute_kernel_sharded(
self.train_dataset, eval_dataset,
)
logger.info(f"Finshed computing the train-{eval_dataset.mode} kernel.")
train_eval_kernel = train_eval_kernel.cpu()
eval_targets = eval_targets.cpu()
if self.args.kernel_formula == 'asymmetric_signgd':
logger.info(f"Starting to compute the flipped train-{eval_dataset.mode} kernel.")
if eval_dataset == self.train_dataset:
train_eval_kernel_flipped = train_eval_kernel
else:
train_eval_kernel_flipped, _ = self.compute_kernel_sharded(
eval_dataset, self.train_dataset,
)
logger.info(f"Finshed computing the flipped train-{eval_dataset.mode} kernel.")
train_eval_kernel_flipped = train_eval_kernel_flipped.cpu()
train_eval_kernel_flipped = train_eval_kernel_flipped.permute(2, 3, 0, 1)
train_eval_kernel = torch.stack([train_eval_kernel, train_eval_kernel_flipped], dim=0)
if self.is_world_process_zero():
torch.save((train_eval_kernel, eval_targets), kernel_path)
return train_eval_kernel, eval_targets
def train(self, model_path=None, dev_objective=None):
if self.args.from_linearhead and model_path is None:
super().train(model_path, dev_objective) # Train output layer using LinearHeadTrainer
if self.args.load_kernels is None:
eval_dataset = self.train_dataset
self.train_train_kernel, self.train_targets = self.compute_kernel_cached(eval_dataset)
return TrainOutput(0, 0.0, {}), None
def evaluate(self, eval_dataset: Optional[Dataset] = None) -> Dict[str, float]:
if eval_dataset is None:
eval_dataset = self.eval_dataset
if self.args.load_kernels is not None:
logger.info(f"Starting to load kernels from {self.args.load_kernels}.")
kernel_file_name = f"{eval_dataset.mode}_kernels_{eval_dataset.task_name}.pt"
load_kernel_path = os.path.join(self.args.load_kernels, kernel_file_name)
(train_eval_kernel, eval_targets) = torch.load(load_kernel_path)
kernel_file_name = f"{self.train_dataset.mode}_kernels_{self.train_dataset.task_name}.pt"
load_kernel_path = os.path.join(self.args.load_kernels, kernel_file_name)
(self.train_train_kernel, self.train_targets) = torch.load(load_kernel_path)
logger.info(f"Finished loading kernels from {self.args.load_kernels}.")
else:
assert self.train_train_kernel is not None, "train_train_kernel is None, did you forget to call train()?"
train_eval_kernel, eval_targets = self.compute_kernel_cached(eval_dataset)
if self.args.kernel_formula == 'asymmetric_signgd':
train_eval_kernel_flipped = train_eval_kernel[1]
train_eval_kernel_flipped, _ = self.reshape_kernel_and_targets(train_eval_kernel_flipped, eval_targets)
train_eval_kernel = train_eval_kernel[0]
train_train_kernel = self.train_train_kernel[0]
else:
train_eval_kernel_flipped = None
train_train_kernel = self.train_train_kernel
train_train_kernel, train_targets = self.reshape_kernel_and_targets(train_train_kernel, self.train_targets)
train_eval_kernel, eval_targets = self.reshape_kernel_and_targets(train_eval_kernel, eval_targets)
# get train and test logits
if self.args.adjust_for_init:
train_logits, _ = self.compute_model_logits_cached(self.train_dataset)
eval_logits, _ = self.compute_model_logits_cached(eval_dataset)
train_logits = train_logits.reshape(-1, 1)
eval_logits = eval_logits.reshape(-1, 1)
else:
train_logits, eval_logits = None, None
metrics = {}
solver = SOLVERS[self.args.kernel_solver](self.args)
solver.fit(train_train_kernel, train_targets, train_logits)
eval_error, eval_preds = solver.predict(train_eval_kernel, eval_targets, eval_logits, eval_kernel_flipped=train_eval_kernel_flipped)
eval_preds = eval_preds.reshape(-1, self.num_labels)
if self.num_labels > 1:
eval_targets = eval_targets.reshape(-1, self.num_labels).argmax(-1)
if self.args.binary_classification: # Make sure to compute loss before this transformation!
eval_preds = torch.cat([-eval_preds, eval_preds], dim=-1) # convert back to two logits
eval_targets = ((eval_targets + 1) / 2).long() # convert back from {-1, 1} to {0, 1}
if self.compute_metrics is not None:
metrics = self.compute_metrics(EvalPrediction(predictions=eval_preds.numpy(), label_ids=eval_targets.numpy()))
# Prefix all keys with eval_
for key in list(metrics.keys()):
if not key.startswith("eval_"):
metrics[f"eval_{key}"] = metrics.pop(key)
metrics["eval_loss"] = eval_error
metrics.update(solver.metrics())
metrics["grad_dim"] = self.grad_dim
output = PredictionOutput(predictions=eval_preds.numpy(), label_ids=eval_targets.numpy(), metrics=metrics)
self.log(output.metrics)
return output
@@ -0,0 +1,232 @@
########## The following part was originally copied from Transformers' trainer (3.4.0) and then changed heavily for linear head probing. ##########
# coding=utf-8
# Copyright 2020-present the HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
A trainer for finding linear probing solutions
"""
import collections
from src.models import MODEL_TYPES
import torch
import torch.nn.functional as F
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
from sklearn.linear_model import LinearRegression, LogisticRegression, LogisticRegressionCV
import transformers
from torch.utils.data.dataset import Dataset
from transformers.trainer_utils import TrainOutput
from transformers.utils import logging
logger = logging.get_logger(__name__)
def tensor_all_gather(tensor: torch.Tensor, distributed_world_size: int):
tensor_list = [torch.zeros_like(tensor) for _ in range(distributed_world_size)]
torch.distributed.all_gather(tensor_list=tensor_list, tensor=tensor)
return torch.cat(tensor_list, dim=0)
def varsize_tensor_all_gather(tensor: torch.Tensor, distributed_world_size: int):
tensor = tensor.contiguous()
dim_tensor = torch.tensor([tensor.size(0)], dtype=torch.int64, device=tensor.device)
dim_tensor = tensor_all_gather(dim_tensor, distributed_world_size).cpu()
max_size = dim_tensor.max()
padded = torch.empty(max_size, *tensor.shape[1:],
dtype=tensor.dtype,
device=tensor.device)
padded[:tensor.shape[0]] = tensor
ag = tensor_all_gather(padded, distributed_world_size)
slices = []
for i, sz in enumerate(dim_tensor):
start_idx = i * max_size
end_idx = start_idx + sz.item()
if end_idx > start_idx:
slices.append(ag[start_idx:end_idx])
return torch.cat(slices, dim=0)
def get_token_prediction_layer(model):
if isinstance(model, tuple(MODEL_TYPES.values())):
if model.label_word_list is not None:
lm_head = model.get_lm_head_fn()
if model.model_type == "roberta":
return lm_head.decoder
elif model.model_type == "bert":
return lm_head.predictions.decoder
elif model.model_type == "gpt2" or model.model_type == 'opt':
return lm_head # TODO: has no bias so linear regression with bias will fail right now
else:
return model.classifier
elif isinstance(model, transformers.RobertaForSequenceClassification):
return model.classifier.out_proj
elif isinstance(model, transformers.BertForSequenceClassification):
return model.classifier
else:
raise NotImplementedError(model.__class__)
def extract_features(model, *args, **kwargs):
"""some magic for getting features pre last layer"""
features = {}
def hook(model_, input_, output_):
features["features"] = input_[0].detach()
get_token_prediction_layer(model).register_forward_hook(hook)
model.forward(*args, **kwargs)
return features["features"]
def extract_features_prob(model, *args, **kwargs):
"""some magic for getting all logits"""
output = model.forward(*args, **kwargs)
return F.softmax(output[1].detach(), -1)
class LinearHeadTrainer(transformers.Trainer):
"""
Adding some functions based on Transformers' Trainer class.
"""
def train(self, model_path=None, dev_objective=None):
"""
Main training entry point.
The training logic is directly borrowed from transformers.Trainer (version 3.0.2).
Add early stopping.
"""
self.best_dir = None
self.objective = -float("inf")
model = self.model
model.eval()
train_dataloader = self.get_train_dataloader()
targets = []
features = []
logger.info("Starting to get features for training dataset")
with torch.no_grad():
for step, inputs in enumerate(train_dataloader):
for k, v in inputs.items():
if isinstance(v, torch.Tensor):
inputs[k] = v.to(self.args.device)
if self.args.prob_as_feature:
features.append(extract_features_prob(model, **inputs))
else:
features.append(extract_features(model, **inputs))
targets.append(inputs["labels"])
logger.info("Finished getting features for training dataset")
features = torch.cat(features, dim=0)
targets = torch.cat(targets, dim=0)
if self.args.local_rank != -1:
logger.info("Starting to gather features across workers")
features = varsize_tensor_all_gather(features, torch.distributed.get_world_size())
targets = varsize_tensor_all_gather(targets, torch.distributed.get_world_size())
logger.info("Finished gathering features across workers")
features = features.cpu()
targets = targets.cpu()
if model.num_labels == 1: # Regression
targets_coords = targets.squeeze().unsqueeze(-1).float()
reg = LinearRegression().fit(features.numpy(), targets_coords.numpy())
else:
use_bias = (model.model_type != 'opt' and model.model_type != 'gpt2') or self.args.prob_as_feature
tol = 0.01 if self.args.lp_early_stopping else 1e-4 # 1e-4 is scipy default
max_iter = 1000 if self.args.lp_early_stopping else 5000
reg = LogisticRegressionCV(max_iter=max_iter, fit_intercept=use_bias, multi_class="multinomial", random_state=0, tol=tol).fit(features.numpy(), targets.numpy())
# targets_coords = torch.nn.functional.one_hot(targets.squeeze(), model.num_labels).float()
logger.info("Fitting linear regression")
logger.info("Assigning weights to model")
# print(head.out_proj.weight.shape, head.out_proj.bias.shape)
# print(reg.coef_.shape, reg.intercept_.shape)
decoder = get_token_prediction_layer(model)
coef_torch = torch.tensor(reg.coef_, device=decoder.weight.device, dtype=decoder.weight.dtype)
if use_bias:
bias_torch = torch.tensor(reg.intercept_, device=decoder.weight.device, dtype=decoder.weight.dtype)
if model.num_labels == 2 and coef_torch.size(0) == 1:
coef_torch = torch.cat([-coef_torch / 2, coef_torch / 2], dim=0)
if use_bias:
bias_torch = torch.cat([-bias_torch / 2, bias_torch / 2], dim=0)
if decoder.weight.shape[0] == model.num_labels:
decoder.weight.data = coef_torch
if use_bias:
decoder.bias.data = bias_torch
else:
if self.args.prob_as_feature:
model.lr_weight = coef_torch
if use_bias:
model.lr_bias = bias_torch
else:
decoder.weight.data[model.label_word_list,:] = coef_torch
if use_bias:
decoder.bias.data[model.label_word_list] = bias_torch
if model.num_labels == 1: # Regression
logits = torch.tensor(reg.predict(features.numpy()))
train_loss = torch.nn.functional.mse_loss(logits, targets_coords, reduction="none")
else:
logits = torch.tensor(reg.predict_log_proba(features.numpy()))
train_loss = torch.nn.functional.cross_entropy(logits, targets.squeeze(), reduction="none")
return TrainOutput(0, train_loss, {}), self.objective
"""
Difference compared to original implementation: return output instead of output.metrics (so there is also the logits)
"""
def evaluate(self, eval_dataset: Optional[Dataset] = None) -> Dict[str, float]:
"""
Run evaluation and returns metrics.
The calling script will be responsible for providing a method to compute metrics, as they are
task-dependent (pass it to the init :obj:`compute_metrics` argument).
You can also subclass and override this method to inject custom behavior.
Args:
eval_dataset (:obj:`Dataset`, `optional`):
Pass a dataset if you wish to override :obj:`self.eval_dataset`. If it is an :obj:`datasets.Dataset`,
columns not accepted by the ``model.forward()`` method are automatically removed. It must implement
the :obj:`__len__` method.
Returns:
A dictionary containing the evaluation loss and the potential metrics computed from the predictions.
"""
if eval_dataset is not None and not isinstance(eval_dataset, collections.abc.Sized):
raise ValueError("eval_dataset must implement __len__")
eval_dataloader = self.get_eval_dataloader(eval_dataset)
output = self.prediction_loop(eval_dataloader, description="Evaluation")
self.log(output.metrics)
if self.args.tpu_metrics_debug or self.args.debug:
# tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.)
xm.master_print(met.metrics_report())
return output
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+482
View File
@@ -0,0 +1,482 @@
"""Custom models for few-shot learning specific operations."""
from socket import ntohl
import torch
import torch.nn as nn
import torch.nn.functional as F
from transformers.models.bert.modeling_bert import BertPreTrainedModel, BertModel, BertOnlyMLMHead
# from transformers.models.roberta.modeling_roberta import RobertaPreTrainedModel, RobertaModel, RobertaLMHead
from .modeling_roberta import RobertaPreTrainedModel, RobertaModel, RobertaLMHead
# from transformers.models.opt.modeling_opt import OPTPreTrainedModel, OPTModel, OPTDecoder
from .modeling_opt import OPTPreTrainedModel, OPTModel, OPTDecoder, OPTForCausalLM
from transformers.models.gpt2.modeling_gpt2 import GPT2PreTrainedModel, GPT2Model, GPT2LMHeadModel
from transformers.modeling_outputs import BaseModelOutputWithPast
from typing import Callable, Dict, Optional, Union, List, Tuple
import random
import logging
logger = logging.getLogger(__name__)
def resize_token_type_embeddings(model, new_num_types: int, random_segment: bool):
"""
Resize the segment (token type) embeddings for BERT
"""
if hasattr(model, 'bert'):
old_token_type_embeddings = model.bert.embeddings.token_type_embeddings
else:
raise NotImplementedError
new_token_type_embeddings = nn.Embedding(new_num_types, old_token_type_embeddings.weight.size(1))
if not random_segment:
new_token_type_embeddings.weight.data[:old_token_type_embeddings.weight.size(0)] = old_token_type_embeddings.weight.data
model.config.type_vocab_size = new_num_types
if hasattr(model, 'bert'):
model.bert.embeddings.token_type_embeddings = new_token_type_embeddings
else:
raise NotImplementedError
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:
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))
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 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,
)
MODEL_TYPES = {
"bert": BertModelForPromptFinetuning,
"roberta": RobertaModelForPromptFinetuning,
"opt": OPTModelForPromptFinetuning,
"gpt2": GPT2ModelForPromptFinetuning,
}
+162
View File
@@ -0,0 +1,162 @@
import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
import torch
from torch import nn
def find_module(root_module: nn.Module, key: str):
"""From OpenDelta"""
sub_keys = key.split(".")
parent_module = root_module
for sub_key in sub_keys[:-1]:
parent_module = getattr(parent_module, sub_key)
module = getattr(parent_module, sub_keys[-1])
return parent_module, sub_keys[-1], module
def attn_forward_hook(self, *args, **kwargs):
def _expand_bsz(x, bsz):
x = x.reshape(x.size(0), self.num_heads, -1).transpose(0,1) # (num_prefix, hidden) -> (num_head, num_prefix, hidden/num_head)
x = x.unsqueeze(0).expand(bsz, *x.shape) # -> (bsz, num_head, num_prefix, hidden/num_head)
return x
if "hidden_states" in kwargs:
hidden_states = kwargs["hidden_states"]
else:
hidden_states = args[0]
bsz = hidden_states.size(0)
if 'past_key_value' not in kwargs or kwargs['past_key_value'] is None:
if self.reparam:
prefix_keys = self.prefix_mlp_keys(self.prefix_input_embeds)
prefix_values = self.prefix_mlp_values(self.prefix_input_embeds)
else:
prefix_keys, prefix_values = self.prefix_keys, self.prefix_values
kwargs['past_key_value'] = (_expand_bsz(prefix_keys, bsz), _expand_bsz(prefix_values, bsz))
if 'attention_mask' in kwargs and kwargs['attention_mask'] is not None:
am = kwargs['attention_mask']
kwargs['attention_mask'] = torch.cat([-torch.zeros((*am.shape[:-1], self.num_prefix), dtype=am.dtype, device=am.device), am], dim=-1)
elif len(args) > 1: # attention mask is passed via positional argument
am = args[1]
am = torch.cat([-torch.zeros((*am.shape[:-1], self.num_prefix), dtype=am.dtype, device=am.device), am], dim=-1)
args = (args[0], am) + args[2:]
return self.original_forward(*args, **kwargs)
class PrefixTuning:
def __init__(self, model, num_prefix, reparam=True, embed_dim=512, mid_dim=512, float16=False, init_by_real_act=False):
self.model = model
self.num_prefix = num_prefix
self.hidden_dim = model.config.hidden_size
self.float16 = float16
# Reparameterization
self.reparam = reparam
self.embed_dim = embed_dim
self.mid_dim = mid_dim
input_embeds = None # For reparameterization
if model.config.model_type == "opt":
attention_name = "attn"
first_layer_name = "layers.0"
layer_name = "layers."
elif model.config.model_type == "roberta":
attention_name = "attention"
first_layer_name = "layer.0"
layer_name = "layer."
else:
raise NotImplementedError
if init_by_real_act:
# Initialize prefix with real words' activations
assert not reparam
# Move the model to GPU first?
model = model.cuda()
input_tokens = torch.randint(low=0, high=model.config.vocab_size, size=(1, num_prefix), dtype=torch.long).cuda()
if model.config.model_type == "roberta":
with torch.no_grad():
# real_key_values = model(input_ids=input_tokens, use_cache=True).past_key_values
real_key_values = model.roberta(input_ids=input_tokens, use_cache=True).past_key_values
elif model.config.model_type == "opt":
with torch.no_grad():
real_key_values = model.model(input_ids=input_tokens, use_cache=True).past_key_values
else:
raise NotImplementedError
for key, _ in model.named_modules():
if key[-len(attention_name):] == attention_name:
layer_id = int(key.split(layer_name)[1].split(".")[0])
logger.info(f"Inject prefix to: {key}")
_, _, attn = find_module(model, key)
attn.original_forward = attn.forward
attn.forward = attn_forward_hook.__get__(attn, type(attn))
if not hasattr(attn, "num_heads"):
attn.num_heads = model.config.num_attention_heads
first = first_layer_name in key
self.add_prefix(attn, first=first, input_embeds=input_embeds)
if first and self.reparam:
input_embeds = attn.prefix_input_embeds
if init_by_real_act:
logger.info(f"Reinitialize with actual activation: {key} (layer {layer_id})")
keys = real_key_values[layer_id][0].squeeze(0).transpose(0, 1).reshape(num_prefix, -1)
values = real_key_values[layer_id][1].squeeze(0).transpose(0, 1).reshape(num_prefix, -1)
attn.prefix_keys.data = keys
attn.prefix_values.data = values
for n, p in model.named_parameters():
if "prefix" not in n:
# logger.info(f"Freeze {n}")
p.requires_grad = False
def add_prefix(self, module, first, input_embeds=None):
module.num_prefix = self.num_prefix
module.reparam = self.reparam
if self.reparam:
if first:
logger.info("For prefix+reparameterization, inject the embeddings in the first layer.")
module.prefix_input_embeds = nn.Parameter(torch.randn(self.num_prefix, self.embed_dim, device=self.model.device, dtype=self.model.dtype), requires_grad=True)
else:
assert input_embeds is not None
module.prefix_input_embeds = input_embeds
module.prefix_mlp_keys = nn.Sequential(
nn.Linear(self.embed_dim, self.mid_dim),
nn.Tanh(),
nn.Linear(self.mid_dim, self.hidden_dim)
).to(self.model.device)
module.prefix_mlp_values = nn.Sequential(
nn.Linear(self.embed_dim, self.mid_dim),
nn.Tanh(),
nn.Linear(self.mid_dim, self.hidden_dim)
).to(self.model.device)
if self.float16:
module.prefix_mlp_keys = module.prefix_mlp_keys.half()
module.prefix_mlp_values = module.prefix_mlp_values.half()
else:
module.prefix_keys = nn.Parameter(torch.randn(self.num_prefix, self.hidden_dim, device=self.model.device, dtype=self.model.dtype), requires_grad=True)
module.prefix_values = nn.Parameter(torch.randn(self.num_prefix, self.hidden_dim, device=self.model.device, dtype=self.model.dtype), requires_grad=True)
def test():
from transformers import AutoTokenizer
from modeling_roberta import RobertaModel
model = RobertaModel.from_pretrained("roberta-base")
tokenizer = AutoTokenizer.from_pretrained("roberta-base")
model.cuda()
PrefixTuning(model, num_prefix=5, reparam=False, init_by_real_act=True)
inputs = tokenizer("Hello, my dog is", return_tensors="pt").to(model.device)
o = model(**inputs)
# print(o)
if __name__ == "__main__":
test()
@@ -0,0 +1,611 @@
"""Dataset utils for different data settings for GLUE."""
import os
import logging
from transformers import DataProcessor, InputExample
from transformers.data.processors.glue import *
from transformers.data.metrics import glue_compute_metrics
import pandas as pd
import logging
logger = logging.getLogger(__name__)
class MrpcProcessor(DataProcessor):
"""Processor for the MRPC data set (GLUE version)."""
def get_example_from_tensor_dict(self, tensor_dict):
"""See base class."""
return InputExample(
tensor_dict["idx"].numpy(),
tensor_dict["sentence1"].numpy().decode("utf-8"),
tensor_dict["sentence2"].numpy().decode("utf-8"),
str(tensor_dict["label"].numpy()),
)
def get_train_examples(self, data_dir):
"""See base class."""
logger.info("LOOKING AT {}".format(os.path.join(data_dir, "train.tsv")))
return self._create_examples(self._read_tsv(os.path.join(data_dir, "train.tsv")), "train")
def get_dev_examples(self, data_dir):
"""See base class."""
return self._create_examples(self._read_tsv(os.path.join(data_dir, "dev.tsv")), "dev")
def get_test_examples(self, data_dir):
"""See base class."""
return self._create_examples(self._read_tsv(os.path.join(data_dir, "test.tsv")), "test")
def get_labels(self):
"""See base class."""
return ["0", "1"]
def _create_examples(self, lines, set_type):
"""Creates examples for the training, dev and test sets."""
examples = []
for (i, line) in enumerate(lines):
if i == 0:
continue
guid = "%s-%s" % (set_type, i)
text_a = line[3]
text_b = line[4]
label = line[0]
examples.append(InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))
return examples
class MnliProcessor(DataProcessor):
"""Processor for the MultiNLI data set (GLUE version)."""
def get_example_from_tensor_dict(self, tensor_dict):
"""See base class."""
return InputExample(
tensor_dict["idx"].numpy(),
tensor_dict["premise"].numpy().decode("utf-8"),
tensor_dict["hypothesis"].numpy().decode("utf-8"),
str(tensor_dict["label"].numpy()),
)
def get_train_examples(self, data_dir):
"""See base class."""
return self._create_examples(self._read_tsv(os.path.join(data_dir, "train.tsv")), "train")
def get_dev_examples(self, data_dir):
"""See base class."""
return self._create_examples(self._read_tsv(os.path.join(data_dir, "dev_matched.tsv")), "dev_matched")
def get_test_examples(self, data_dir):
"""See base class."""
return self._create_examples(self._read_tsv(os.path.join(data_dir, "test_matched.tsv")), "test_matched")
def get_labels(self):
"""See base class."""
return ["contradiction", "entailment", "neutral"]
def _create_examples(self, lines, set_type):
"""Creates examples for the training, dev and test sets."""
examples = []
for (i, line) in enumerate(lines):
if i == 0:
continue
guid = "%s-%s" % (set_type, line[0])
text_a = line[8]
text_b = line[9]
label = line[-1]
examples.append(InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))
return examples
class MnliMismatchedProcessor(MnliProcessor):
"""Processor for the MultiNLI Mismatched data set (GLUE version)."""
def get_dev_examples(self, data_dir):
"""See base class."""
return self._create_examples(self._read_tsv(os.path.join(data_dir, "dev_mismatched.tsv")), "dev_mismatched")
def get_test_examples(self, data_dir):
"""See base class."""
return self._create_examples(self._read_tsv(os.path.join(data_dir, "test_mismatched.tsv")), "test_mismatched")
class SnliProcessor(DataProcessor):
"""Processor for the MultiNLI data set (GLUE version)."""
def get_example_from_tensor_dict(self, tensor_dict):
"""See base class."""
return InputExample(
tensor_dict["idx"].numpy(),
tensor_dict["premise"].numpy().decode("utf-8"),
tensor_dict["hypothesis"].numpy().decode("utf-8"),
str(tensor_dict["label"].numpy()),
)
def get_train_examples(self, data_dir):
"""See base class."""
return self._create_examples(self._read_tsv(os.path.join(data_dir, "train.tsv")), "train")
def get_dev_examples(self, data_dir):
"""See base class."""
return self._create_examples(self._read_tsv(os.path.join(data_dir, "dev.tsv")), "dev")
def get_test_examples(self, data_dir):
"""See base class."""
return self._create_examples(self._read_tsv(os.path.join(data_dir, "test.tsv")), "test")
def get_labels(self):
"""See base class."""
return ["contradiction", "entailment", "neutral"]
def _create_examples(self, lines, set_type):
"""Creates examples for the training, dev and test sets."""
examples = []
for (i, line) in enumerate(lines):
if i == 0:
continue
guid = "%s-%s" % (set_type, line[0])
text_a = line[7]
text_b = line[8]
label = line[-1]
examples.append(InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))
return examples
class ColaProcessor(DataProcessor):
"""Processor for the CoLA data set (GLUE version)."""
def get_example_from_tensor_dict(self, tensor_dict):
"""See base class."""
return InputExample(
tensor_dict["idx"].numpy(),
tensor_dict["sentence"].numpy().decode("utf-8"),
None,
str(tensor_dict["label"].numpy()),
)
def get_train_examples(self, data_dir):
"""See base class."""
return self._create_examples(self._read_tsv(os.path.join(data_dir, "train.tsv")), "train")
def get_dev_examples(self, data_dir):
"""See base class."""
return self._create_examples(self._read_tsv(os.path.join(data_dir, "dev.tsv")), "dev")
def get_test_examples(self, data_dir):
"""See base class."""
return self._create_examples(self._read_tsv(os.path.join(data_dir, "test.tsv")), "test")
def get_labels(self):
"""See base class."""
return ["0", "1"]
def _create_examples(self, lines, set_type):
"""Creates examples for the training, dev and test sets."""
test_mode = set_type == "test"
text_index = 3
examples = []
for (i, line) in enumerate(lines):
guid = "%s-%s" % (set_type, i)
text_a = line[text_index]
label = line[1]
examples.append(InputExample(guid=guid, text_a=text_a, text_b=None, label=label))
return examples
class Sst2Processor(DataProcessor):
"""Processor for the SST-2 data set (GLUE version)."""
def get_example_from_tensor_dict(self, tensor_dict):
"""See base class."""
return InputExample(
tensor_dict["idx"].numpy(),
tensor_dict["sentence"].numpy().decode("utf-8"),
None,
str(tensor_dict["label"].numpy()),
)
def get_train_examples(self, data_dir):
"""See base class."""
return self._create_examples(self._read_tsv(os.path.join(data_dir, "train.tsv")), "train")
def get_dev_examples(self, data_dir):
"""See base class."""
return self._create_examples(self._read_tsv(os.path.join(data_dir, "dev.tsv")), "dev")
def get_test_examples(self, data_dir):
"""See base class."""
return self._create_examples(self._read_tsv(os.path.join(data_dir, "test.tsv")), "test")
def get_labels(self):
"""See base class."""
return ["0", "1"]
def _create_examples(self, lines, set_type):
"""Creates examples for the training, dev and test sets."""
examples = []
text_index = 0
for (i, line) in enumerate(lines):
if i == 0:
continue
guid = "%s-%s" % (set_type, i)
text_a = line[text_index]
label = line[1]
examples.append(InputExample(guid=guid, text_a=text_a, text_b=None, label=label))
return examples
class StsbProcessor(DataProcessor):
"""Processor for the STS-B data set (GLUE version)."""
def get_example_from_tensor_dict(self, tensor_dict):
"""See base class."""
return InputExample(
tensor_dict["idx"].numpy(),
tensor_dict["sentence1"].numpy().decode("utf-8"),
tensor_dict["sentence2"].numpy().decode("utf-8"),
str(tensor_dict["label"].numpy()),
)
def get_train_examples(self, data_dir):
"""See base class."""
return self._create_examples(self._read_tsv(os.path.join(data_dir, "train.tsv")), "train")
def get_dev_examples(self, data_dir):
"""See base class."""
return self._create_examples(self._read_tsv(os.path.join(data_dir, "dev.tsv")), "dev")
def get_test_examples(self, data_dir):
"""See base class."""
return self._create_examples(self._read_tsv(os.path.join(data_dir, "test.tsv")), "test")
def get_labels(self):
"""See base class."""
return [None]
def _create_examples(self, lines, set_type):
"""Creates examples for the training, dev and test sets."""
examples = []
for (i, line) in enumerate(lines):
if i == 0:
continue
guid = "%s-%s" % (set_type, line[0])
text_a = line[7]
text_b = line[8]
label = line[-1]
examples.append(InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))
return examples
class QqpProcessor(DataProcessor):
"""Processor for the QQP data set (GLUE version)."""
def get_example_from_tensor_dict(self, tensor_dict):
"""See base class."""
return InputExample(
tensor_dict["idx"].numpy(),
tensor_dict["question1"].numpy().decode("utf-8"),
tensor_dict["question2"].numpy().decode("utf-8"),
str(tensor_dict["label"].numpy()),
)
def get_train_examples(self, data_dir):
"""See base class."""
return self._create_examples(self._read_tsv(os.path.join(data_dir, "train.tsv")), "train")
def get_dev_examples(self, data_dir):
"""See base class."""
return self._create_examples(self._read_tsv(os.path.join(data_dir, "dev.tsv")), "dev")
def get_test_examples(self, data_dir):
"""See base class."""
return self._create_examples(self._read_tsv(os.path.join(data_dir, "test.tsv")), "test")
def get_labels(self):
"""See base class."""
return ["0", "1"]
def _create_examples(self, lines, set_type):
"""Creates examples for the training, dev and test sets."""
test_mode = set_type == "test"
q1_index = 3
q2_index = 4
examples = []
for (i, line) in enumerate(lines):
if i == 0:
continue
guid = "%s-%s" % (set_type, line[0])
try:
text_a = line[q1_index]
text_b = line[q2_index]
label = line[5]
except IndexError:
continue
examples.append(InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))
return examples
class QnliProcessor(DataProcessor):
"""Processor for the QNLI data set (GLUE version)."""
def get_example_from_tensor_dict(self, tensor_dict):
"""See base class."""
return InputExample(
tensor_dict["idx"].numpy(),
tensor_dict["question"].numpy().decode("utf-8"),
tensor_dict["sentence"].numpy().decode("utf-8"),
str(tensor_dict["label"].numpy()),
)
def get_train_examples(self, data_dir):
"""See base class."""
return self._create_examples(self._read_tsv(os.path.join(data_dir, "train.tsv")), "train")
def get_dev_examples(self, data_dir):
"""See base class."""
return self._create_examples(self._read_tsv(os.path.join(data_dir, "dev.tsv")), "dev")
def get_test_examples(self, data_dir):
"""See base class."""
return self._create_examples(self._read_tsv(os.path.join(data_dir, "test.tsv")), "test")
def get_labels(self):
"""See base class."""
return ["entailment", "not_entailment"]
def _create_examples(self, lines, set_type):
"""Creates examples for the training, dev and test sets."""
examples = []
for (i, line) in enumerate(lines):
if i == 0:
continue
guid = "%s-%s" % (set_type, line[0])
text_a = line[1]
text_b = line[2]
label = line[-1]
examples.append(InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))
return examples
class RteProcessor(DataProcessor):
"""Processor for the RTE data set (GLUE version)."""
def get_example_from_tensor_dict(self, tensor_dict):
"""See base class."""
return InputExample(
tensor_dict["idx"].numpy(),
tensor_dict["sentence1"].numpy().decode("utf-8"),
tensor_dict["sentence2"].numpy().decode("utf-8"),
str(tensor_dict["label"].numpy()),
)
def get_train_examples(self, data_dir):
"""See base class."""
return self._create_examples(self._read_tsv(os.path.join(data_dir, "train.tsv")), "train")
def get_dev_examples(self, data_dir):
"""See base class."""
return self._create_examples(self._read_tsv(os.path.join(data_dir, "dev.tsv")), "dev")
def get_test_examples(self, data_dir):
"""See base class."""
return self._create_examples(self._read_tsv(os.path.join(data_dir, "test.tsv")), "test")
def get_labels(self):
"""See base class."""
return ["entailment", "not_entailment"]
def _create_examples(self, lines, set_type):
"""Creates examples for the training, dev and test sets."""
examples = []
for (i, line) in enumerate(lines):
if i == 0:
continue
guid = "%s-%s" % (set_type, line[0])
text_a = line[1]
text_b = line[2]
label = line[-1]
examples.append(InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))
return examples
class WnliProcessor(DataProcessor):
"""Processor for the WNLI data set (GLUE version)."""
def get_example_from_tensor_dict(self, tensor_dict):
"""See base class."""
return InputExample(
tensor_dict["idx"].numpy(),
tensor_dict["sentence1"].numpy().decode("utf-8"),
tensor_dict["sentence2"].numpy().decode("utf-8"),
str(tensor_dict["label"].numpy()),
)
def get_train_examples(self, data_dir):
"""See base class."""
return self._create_examples(self._read_tsv(os.path.join(data_dir, "train.tsv")), "train")
def get_dev_examples(self, data_dir):
"""See base class."""
return self._create_examples(self._read_tsv(os.path.join(data_dir, "dev.tsv")), "dev")
def get_test_examples(self, data_dir):
"""See base class."""
return self._create_examples(self._read_tsv(os.path.join(data_dir, "test.tsv")), "test")
def get_labels(self):
"""See base class."""
return ["0", "1"]
def _create_examples(self, lines, set_type):
"""Creates examples for the training, dev and test sets."""
examples = []
for (i, line) in enumerate(lines):
if i == 0:
continue
guid = "%s-%s" % (set_type, line[0])
text_a = line[1]
text_b = line[2]
label = line[-1]
examples.append(InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))
return examples
class TextClassificationProcessor(DataProcessor):
"""
Data processor for text classification datasets (mr, sst-5, subj, trec, cr, mpqa).
"""
def __init__(self, task_name):
self.task_name = task_name
def get_example_from_tensor_dict(self, tensor_dict):
"""See base class."""
return InputExample(
tensor_dict["idx"].numpy(),
tensor_dict["sentence"].numpy().decode("utf-8"),
None,
str(tensor_dict["label"].numpy()),
)
def get_train_examples(self, data_dir):
"""See base class."""
return self._create_examples(pd.read_csv(os.path.join(data_dir, "train.csv"), header=None).values.tolist(), "train")
def get_dev_examples(self, data_dir):
"""See base class."""
return self._create_examples(pd.read_csv(os.path.join(data_dir, "dev.csv"), header=None).values.tolist(), "dev")
def get_test_examples(self, data_dir):
"""See base class."""
return self._create_examples(pd.read_csv(os.path.join(data_dir, "test.csv"), header=None).values.tolist(), "test")
def get_labels(self):
"""See base class."""
if self.task_name == "mr":
return list(range(2))
elif self.task_name == "sst-5":
return list(range(5))
elif self.task_name == "subj":
return list(range(2))
elif self.task_name == "trec":
return list(range(6))
elif self.task_name == "cr":
return list(range(2))
elif self.task_name == "mpqa":
return list(range(2))
else:
raise Exception("task_name not supported.")
def _create_examples(self, lines, set_type):
"""Creates examples for the training, dev and test sets."""
examples = []
for (i, line) in enumerate(lines):
guid = "%s-%s" % (set_type, i)
if self.task_name == "ag_news":
examples.append(InputExample(guid=guid, text_a=line[1] + '. ' + line[2], short_text=line[1] + ".", label=line[0]))
elif self.task_name == "yelp_review_full":
examples.append(InputExample(guid=guid, text_a=line[1], short_text=line[1], label=line[0]))
elif self.task_name == "yahoo_answers":
text = line[1]
if not pd.isna(line[2]):
text += ' ' + line[2]
if not pd.isna(line[3]):
text += ' ' + line[3]
examples.append(InputExample(guid=guid, text_a=text, short_text=line[1], label=line[0]))
elif self.task_name in ['mr', 'sst-5', 'subj', 'trec', 'cr', 'mpqa']:
examples.append(InputExample(guid=guid, text_a=line[1], label=line[0]))
else:
raise Exception("Task_name not supported.")
return examples
def text_classification_metrics(task_name, preds, labels):
return {"acc": (preds == labels).mean()}
# Add your task to the following mappings
processors_mapping = {
"cola": ColaProcessor(),
"mnli": MnliProcessor(),
"mnli-mm": MnliMismatchedProcessor(),
"mrpc": MrpcProcessor(),
"sst-2": Sst2Processor(),
"sts-b": StsbProcessor(),
"qqp": QqpProcessor(),
"qnli": QnliProcessor(),
"rte": RteProcessor(),
"wnli": WnliProcessor(),
"snli": SnliProcessor(),
"mr": TextClassificationProcessor("mr"),
"sst-5": TextClassificationProcessor("sst-5"),
"subj": TextClassificationProcessor("subj"),
"trec": TextClassificationProcessor("trec"),
"cr": TextClassificationProcessor("cr"),
"mpqa": TextClassificationProcessor("mpqa")
}
num_labels_mapping = {
"cola": 2,
"mnli": 3,
"mrpc": 2,
"sst-2": 2,
"sts-b": 1,
"qqp": 2,
"qnli": 2,
"rte": 2,
"wnli": 2,
"snli": 3,
"mr": 2,
"sst-5": 5,
"subj": 2,
"trec": 6,
"cr": 2,
"mpqa": 2
}
output_modes_mapping = {
"cola": "classification",
"mnli": "classification",
"mnli-mm": "classification",
"mrpc": "classification",
"sst-2": "classification",
"sts-b": "regression",
"qqp": "classification",
"qnli": "classification",
"rte": "classification",
"wnli": "classification",
"snli": "classification",
"mr": "classification",
"sst-5": "classification",
"subj": "classification",
"trec": "classification",
"cr": "classification",
"mpqa": "classification"
}
# Return a function that takes (task_name, preds, labels) as inputs
compute_metrics_mapping = {
"cola": glue_compute_metrics,
"mnli": glue_compute_metrics,
"mnli-mm": glue_compute_metrics,
"mrpc": glue_compute_metrics,
"sst-2": glue_compute_metrics,
"sts-b": glue_compute_metrics,
"qqp": glue_compute_metrics,
"qnli": glue_compute_metrics,
"rte": glue_compute_metrics,
"wnli": glue_compute_metrics,
"snli": text_classification_metrics,
"mr": text_classification_metrics,
"sst-5": text_classification_metrics,
"subj": text_classification_metrics,
"trec": text_classification_metrics,
"cr": text_classification_metrics,
"mpqa": text_classification_metrics,
}
# For regression task only: median
median_mapping = {
"sts-b": 2.5
}
bound_mapping = {
"sts-b": (0, 5)
}
+867
View File
@@ -0,0 +1,867 @@
########## The following part is copied from Transformers' trainer (3.4.0) and later ported to be compatible with v4.4.2 and to support initialization from linear head probing. ##########
# coding=utf-8
# Copyright 2020-present the HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
The Trainer class, to easily train a 🤗 Transformers from scratch or finetune it on a new task.
"""
import collections
import inspect
import math
import os
import re
import shutil
import warnings
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
import numpy as np
import torch
from packaging import version
from torch import nn
from torch.utils.data.dataloader import DataLoader
from torch.utils.data.dataset import Dataset
from torch.utils.data.distributed import DistributedSampler
from torch.utils.data.sampler import RandomSampler, SequentialSampler
from torch.optim.lr_scheduler import LambdaLR
import math
import time
import transformers
from transformers.file_utils import is_datasets_available, is_in_notebook, is_torch_tpu_available
from transformers.integrations import (
is_comet_available,
is_optuna_available,
is_ray_available,
is_tensorboard_available,
is_wandb_available,
)
from transformers.optimization import AdamW, get_linear_schedule_with_warmup, get_scheduler
from transformers.trainer_callback import (
DefaultFlowCallback,
ProgressCallback,
)
from transformers.trainer_utils import (
default_compute_objective,
)
from transformers.training_args import TrainingArguments
from transformers.utils import logging
from transformers.trainer_utils import TrainOutput
from tqdm import tqdm, trange
from torch.optim import SGD
import torch.nn.functional as F
from src.linearhead_trainer import LinearHeadTrainer
from transformers.trainer_callback import TrainerState
import copy
_use_native_amp = False
_use_apex = False
DEFAULT_CALLBACKS = [DefaultFlowCallback]
DEFAULT_PROGRESS_CALLBACK = ProgressCallback
if is_in_notebook():
from transformers.utils.notebook import NotebookProgressCallback
DEFAULT_PROGRESS_CALLBACK = NotebookProgressCallback
# Check if Pytorch version >= 1.6 to switch between Native AMP and Apex
if version.parse(torch.__version__) < version.parse("1.6"):
from transformers.file_utils import is_apex_available
if is_apex_available():
from apex import amp
_use_apex = True
else:
_use_native_amp = True
from torch.cuda.amp import autocast
if version.parse(torch.__version__) < version.parse("1.2"):
_use_ddp_no_sync = False
else:
_use_ddp_no_sync = True
if is_datasets_available():
import datasets
if is_torch_tpu_available():
import torch_xla.core.xla_model as xm
import torch_xla.debug.metrics as met
import torch_xla.distributed.parallel_loader as pl
if is_tensorboard_available():
from transformers.integrations import TensorBoardCallback
DEFAULT_CALLBACKS.append(TensorBoardCallback)
if is_wandb_available():
from transformers.integrations import WandbCallback
DEFAULT_CALLBACKS.append(WandbCallback)
if is_comet_available():
from transformers.integrations import CometCallback
DEFAULT_CALLBACKS.append(CometCallback)
if is_optuna_available():
import optuna
if is_ray_available():
from ray import tune
logger = logging.get_logger(__name__)
logger.setLevel(logging.INFO)
########## The above part is copied from Transformers' trainer (3.4.0) ##########
def default_dev_objective(metrics):
"""
Objective used for picking the best model on development sets
"""
if "eval_mnli/acc" in metrics:
return metrics["eval_mnli/acc"]
elif "eval_mnli-mm/acc" in metrics:
return metrics["eval_mnli-mm/acc"]
elif "eval_f1" in metrics:
return metrics["eval_f1"]
elif "eval_mcc" in metrics:
return metrics["eval_mcc"]
elif "eval_pearson" in metrics:
return metrics["eval_pearson"]
elif "eval_acc" in metrics:
return metrics["eval_acc"]
raise Exception("No metric founded for {}".format(metrics))
class Trainer(LinearHeadTrainer):
"""
Adding some functions based on Transformers' Trainer class.
"""
def create_optimizer_and_scheduler(self, num_training_steps: int):
"""
Based on Transformers' default one, we add fixing layer option where the bottom n layers' parameters
are fixed and only the top layers are further fine-tuned.
"""
if self.args.hf_inference_model:
return
if self.optimizer is None:
params = {}
for n, p in self.model.named_parameters():
if self.args.fix_layers > 0:
if 'encoder.layer' in n:
try:
layer_num = int(n[n.find('encoder.layer') + 14:].split('.')[0])
except:
print(n)
raise Exception("")
if layer_num >= self.args.fix_layers:
print('yes', n)
params[n] = p
else:
print('no ', n)
elif 'embeddings' in n:
print('no ', n)
else:
print('yes', n)
params[n] = p
else:
params[n] = p
no_decay = ["bias", "LayerNorm.weight"]
optimizer_grouped_parameters = [
{
"params": [p for n, p in params.items() if not any(nd in n for nd in no_decay)],
"weight_decay": self.args.weight_decay,
},
{
"params": [p for n, p in params.items() if any(nd in n for nd in no_decay)],
"weight_decay": 0.0,
},
]
if self.args.optimizer == 'adam':
self.optimizer = AdamW(
optimizer_grouped_parameters,
lr=self.args.learning_rate,
betas=(self.args.adam_beta1, self.args.adam_beta2),
eps=self.args.adam_epsilon,
)
elif self.args.optimizer == 'sgd':
self.optimizer = SGD(
optimizer_grouped_parameters,
lr=self.args.learning_rate
)
else:
raise NotImplementedError
if self.lr_scheduler is None:
self.lr_scheduler = get_scheduler(
self.args.lr_scheduler_type,
optimizer=self.optimizer,
num_warmup_steps=self.args.get_warmup_steps(num_training_steps),
num_training_steps=num_training_steps,
)
def should_optim(self, name, param):
return (not self.args.layer_wise_optim or f".{self.state.global_step % self.model.config.num_hidden_layers}." in name) and param.requires_grad
def zo_forward(self, model: nn.Module, inputs: Dict[str, Union[torch.Tensor, Any]]) -> torch.Tensor:
model.eval()
inputs = self._prepare_inputs(inputs)
if self.args.optimize_acc:
loss, logits = model(**inputs)
preds = F.softmax(logits, dim=-1)
acc = torch.sum(torch.argmax(preds, 1) == inputs['labels']) / len(preds)
loss = -acc
else:
with self.compute_loss_context_manager():
loss = self.compute_loss(model, inputs)
if self.args.n_gpu > 1:
loss = loss.mean() # mean() to average on multi-gpu parallel training
self.state.zo_forward_step += 1
return loss.detach()
def efficient_perturb_parameters(self, model: nn.Module, random_seed: int, scaling_factor=1):
torch.manual_seed(random_seed)
for name, param in self.named_parameters_to_optim:
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 * z * self.args.zero_order_eps
return model
def norm_perturb_parameters(self, model: nn.Module, random_vector=None, scaling_factor=1):
if random_vector is None:
random_vector = {}
for name, param in self.named_parameters_to_optim:
if name in random_vector:
z = random_vector[name]
else:
z = torch.normal(mean=0, std=1, size=param.data.size(), device=param.data.device, dtype=param.data.dtype)
random_vector[name] = z
cname = self.retrieve_c(name)
if cname in self.cs:
z = z / self.cs[cname]
param.data = param.data + scaling_factor * z * self.args.zero_order_eps
return model, random_vector
def perturb_parameters(self, model: nn.Module, random_vector=None, scaling_factor=1):
if random_vector is None:
random_vector = {}
for name, param in self.named_parameters_to_optim:
if name in random_vector:
z = random_vector[name]
else:
z = torch.normal(mean=0, std=1, size=param.data.size(), device=param.data.device, dtype=param.data.dtype)
random_vector[name] = z
param.data = param.data + scaling_factor * z * self.args.zero_order_eps
return model, random_vector
def perturb_single_layer(self, model, layer_name, random_vector=None, scaling_factor=1):
if random_vector is None:
random_vector = {}
for name, param in self.named_parameters_to_optim:
cname = self.retrieve_c(name)
if cname == layer_name:
if name in random_vector:
z = random_vector[name]
else:
z = torch.normal(mean=0, std=1, size=param.data.size(), device=param.data.device, dtype=param.data.dtype)
random_vector[name] = z
param.data = param.data + scaling_factor * z * self.args.zero_order_eps
return model, random_vector
def initialize_c(self, model, inputs):
self.named_parameters_to_optim = []
for name, param in model.named_parameters():
if self.should_optim(name, param):
self.named_parameters_to_optim.append((name, param))
self.cs = {'embed': 0.0, 'lm_head': 0.0}
# OPT: embed_tokens; embed_positions
# RoBERTa: embeddings
self.num_params = copy.deepcopy(self.cs)
self.num_model_layers = model.config.num_hidden_layers
layer_name = "layers" if model.config.model_type == "opt" else "layer"
for i in range(self.num_model_layers):
self.cs[f'{layer_name}.{i}.'] = 0.0
self.num_params[f'{layer_name}.{i}.'] = 0
# ZO estimation of c's
if self.args.zo_variant != 'param_norm' and self.args.use_zo_grad_est:
for layer in self.cs.keys():
with torch.no_grad():
model, z = self.perturb_single_layer(model, layer_name=layer)
loss1 = self.zo_forward(model, inputs)
model, z = self.perturb_single_layer(model, layer_name=layer, random_vector=z, scaling_factor=-2)
loss2 = self.zo_forward(model, inputs)
projected_grad = (loss1 - loss2) / (2 * self.args.zero_order_eps)
self.cs[layer] = torch.abs(projected_grad)
model, z = self.perturb_single_layer(model, layer_name=layer, random_vector=z)
# no need to run backprop if we are using parameter norm variant, can just measure them
elif self.args.zo_variant == 'param_norm':
for name, param in self.named_parameters_to_optim:
print(name)
ckey = self.retrieve_c(name)
if ckey in self.cs:
self.cs[ckey] += torch.sum(param.data ** 2)
self.num_params[ckey] += param.data.numel()
# take sqrt to get norm
for ckey in self.cs:
self.cs[ckey] = torch.sqrt(self.cs[ckey])
if self.args.scale_norm_by_num_params:
self.cs[ckey] /= torch.sqrt(self.cs[ckey])
for ckey in self.cs:
if self.cs[ckey] != 0:
self.cs[ckey] = self.cs[ckey].detach().item()
# backpropagation estimation fo ZO c's
# this is mostly for debugging purposes to disentangle the variance from using ZO to estimate c
# from the effectiveness of the preconditioners
else:
model.eval()
inputs = self._prepare_inputs(inputs)
with self.compute_loss_context_manager():
loss = self.compute_loss(model, inputs)
if self.args.n_gpu > 1:
loss = loss.mean() # mean() to average on multi-gpu parallel training
loss.backward()
for name, param in self.named_parameters_to_optim:
if param.grad is None:
print(name)
else:
ckey = self.retrieve_c(name)
if ckey in self.cs:
self.cs[ckey] += torch.sum(param.grad ** 2)
self.num_params[ckey] += param.grad.numel()
# take sqrt to get norm
for ckey in self.cs:
self.cs[ckey] = torch.sqrt(self.cs[ckey])
if self.args.scale_norm_by_num_params:
self.cs[ckey] /= torch.sqrt(self.num_params[ckey])
for ckey in self.cs:
if self.cs[ckey] != 0:
self.cs[ckey] = self.cs[ckey].detach().item()
self.layer_names = list(self.cs.keys())
model.zero_grad()
def retrieve_c(self, param_name):
for c_name in self.cs.keys():
if c_name in param_name:
return c_name
return '' # these parameters are likely not being used in the forward pass
def get_num_samples(self):
if self.args.zero_order_sample_scheduler is None:
noise_sample_time = 1
elif self.args.zero_order_sample_scheduler == "linear":
noise_sample_time = max(1, int(self.state.global_step / self.args.max_steps * self.args.zero_order_sample))
elif self.args.zero_order_sample_scheduler == "constant":
noise_sample_time = int(self.args.zero_order_sample)
else:
raise NotImplementedError
# print("Sample %d zs" % (noise_sample_time))
return noise_sample_time
def train(self, model_path=None, dev_objective=None):
"""
Main training entry point.
The training logic is directly borrowed from transformers.Trainer (version 3.0.2).
Add early stopping.
"""
if self.args.from_linearhead and model_path is None:
super().train(model_path, dev_objective) # Train output layer using LinearHeadTrainer
self.best_dir = None
self.objective = -float("inf")
self.dev_objective = dev_objective if dev_objective is not None else default_dev_objective
# Data loading.
train_dataloader = self.get_train_dataloader()
num_update_steps_per_epoch = len(train_dataloader) // self.args.gradient_accumulation_steps
if num_update_steps_per_epoch == 0:
num_update_steps_per_epoch = 1
if self.args.max_steps > 0:
t_total = self.args.max_steps
num_train_epochs = self.args.max_steps // num_update_steps_per_epoch + int(
self.args.max_steps % num_update_steps_per_epoch > 0
)
else:
t_total = int(len(train_dataloader) // self.args.gradient_accumulation_steps * self.args.num_train_epochs)
num_train_epochs = self.args.num_train_epochs
self.create_optimizer_and_scheduler(num_training_steps=t_total)
optimizer = self.optimizer
scheduler = self.lr_scheduler
# Check if saved optimizer or scheduler states exist
if (
model_path is not None
and os.path.isfile(os.path.join(model_path, "optimizer.pt"))
and os.path.isfile(os.path.join(model_path, "scheduler.pt"))
):
# Load in optimizer and scheduler states
optimizer.load_state_dict(
torch.load(os.path.join(model_path, "optimizer.pt"), map_location=self.args.device)
)
scheduler.load_state_dict(torch.load(os.path.join(model_path, "scheduler.pt")))
model = self.model
if self.args.fp16 and _use_apex:
if not transformers.is_apex_available():
raise ImportError("Please install apex from https://www.github.com/nvidia/apex to use fp16 training.")
model, optimizer = amp.initialize(model, optimizer, opt_level=self.args.fp16_opt_level)
# Multi-gpu training (should be after apex fp16 initialization)
if self.args.n_gpu > 1:
model = torch.nn.DataParallel(model)
# Distributed training (should be after apex fp16 initialization)
if self.args.local_rank != -1:
model = torch.nn.parallel.DistributedDataParallel(
model,
device_ids=[self.args.local_rank],
output_device=self.args.local_rank,
find_unused_parameters=True,
)
# Train
if transformers.is_torch_tpu_available():
total_train_batch_size = self.args.train_batch_size * xm.xrt_world_size()
else:
total_train_batch_size = (
self.args.train_batch_size
* self.args.gradient_accumulation_steps
* (torch.distributed.get_world_size() if self.args.local_rank != -1 else 1)
)
logger.info("***** Running training *****")
logger.info(" Num examples = %d", self.num_examples(train_dataloader))
logger.info(" Num Epochs = %d", num_train_epochs)
logger.info(" Instantaneous batch size per device = %d", self.args.per_device_train_batch_size)
logger.info(" Total train batch size (w. parallel, distributed & accumulation) = %d", total_train_batch_size)
logger.info(" Gradient Accumulation steps = %d", self.args.gradient_accumulation_steps)
logger.info(" Total optimization steps = %d", t_total)
self.state = TrainerState()
self.state.global_step = 0
start_time = time.time()
self.state.zo_forward_step = 0
self.epoch = 0
epochs_trained = 0
steps_trained_in_current_epoch = 0
if self.args.gradient_checkpointing:
model.gradient_checkpointing_enable()
# Check if continuing training from a checkpoint
if model_path is not None:
# set global_step to global_step of last saved checkpoint from model path
try:
self.state.global_step = int(model_path.split("-")[-1].split("/")[0])
epochs_trained = self.state.global_step // (len(train_dataloader) // self.args.gradient_accumulation_steps)
steps_trained_in_current_epoch = self.state.global_step % (
len(train_dataloader) // self.args.gradient_accumulation_steps
)
logger.info(" Continuing training from checkpoint, will skip to saved global_step")
logger.info(" Continuing training from epoch %d", epochs_trained)
logger.info(" Continuing training from global step %d", self.state.global_step)
logger.info(" Will skip the first %d steps in the first epoch", steps_trained_in_current_epoch)
except ValueError:
self.state.global_step = 0
logger.info(" Starting fine-tuning.")
tr_loss = torch.tensor(0.0).to(self.args.device)
logging_loss_scalar = 0.0
model.zero_grad()
metrics = None
for epoch in range(epochs_trained, int(num_train_epochs)):
if isinstance(train_dataloader, DataLoader) and isinstance(train_dataloader.sampler, DistributedSampler):
train_dataloader.sampler.set_epoch(epoch)
if transformers.is_torch_tpu_available():
parallel_loader = pl.ParallelLoader(train_dataloader, [self.args.device]).per_device_loader(
self.args.device
)
epoch_iterator = tqdm(parallel_loader, desc="Iteration", disable=not self.is_local_process_zero())
else:
epoch_iterator = tqdm(train_dataloader, desc="Iteration", disable=True)
# Reset the past mems state at the beginning of each epoch if necessary.
if self.args.past_index >= 0:
self._past = None
for step, inputs in enumerate(epoch_iterator):
if self.args.sync_embedding_layers:
assert model.module.model_type == 'opt', 'did not implement embedding layer synchronization for non-OPT models'
model.module.model.decoder.embed_tokens.weight = model.module.lm_head.weight
# estimate c's (param or grad norm) on epoch 0
if epoch == 0 and step == 0 and self.args.zo_variant is not None:
self.initialize_c(model, inputs)
elif step == 0 and self.args.zo_variant is not None and self.args.recompute_norms:
self.initialize_c(model, inputs)
# Skip past any already trained steps if resuming training
if steps_trained_in_current_epoch > 0:
steps_trained_in_current_epoch -= 1
continue
if self.args.zero_order_optim:
# Get parameters that should be optimized (for layer-wise optimization and prefix-tuning)
self.named_parameters_to_optim = []
for name, param in model.named_parameters():
if self.should_optim(name, param):
self.named_parameters_to_optim.append((name, param))
if self.args.zo_by_layer:
assert not self.args.efficient_zero_order, 'did not implement preconditioned ZO for efficient ZO yet'
assert self.args.zero_order_use_trainer_optim, 'preconditioned ZO requires using the trainer optimizer'
num_zs = self.get_num_samples()
layers = [np.random.choice(self.layer_names)] if self.args.pc_rnd_layer else self.layer_names
# for each layer: perturb only that layer and store the gradient estimates in the grad buffer
for layer in self.layer_names:
for _ in range(num_zs):
c_i = self.cs[layer]
with torch.no_grad():
c_i = 1.0 if c_i == 0 else c_i # if the scaling is 0, just reset it to 1 so that there can eventually be some gradient to those layers
model, random_vector = self.perturb_single_layer(model, layer, scaling_factor=1.0/c_i)
loss1 = self.zo_forward(model, inputs)
model, random_vector = self.perturb_single_layer(model, layer, random_vector=random_vector, scaling_factor=-2.0/c_i)
loss2 = self.zo_forward(model, inputs)
model, random_vector = self.perturb_single_layer(model, layer, random_vector=random_vector, scaling_factor=1.0/c_i)
projected_grad = (loss1 - loss2) / (2 * self.args.zero_order_eps)
# scale grad according to number of zs sampled
if not self.args.scale_lr_with_samples:
projected_grad = projected_grad / float(num_zs)
for name, param in self.named_parameters_to_optim:
if self.retrieve_c(name) == layer:
z_tilde = random_vector[name] * c_i
if param.grad is None:
param.grad = projected_grad * z_tilde
else:
param.grad += projected_grad * z_tilde
# note that | E_z [ <z, grad of one layer > ] | is equal to norm of grad for that layer for gaussian z
# leverages this fact to update the grad norms
if self.args.zo_variant == 'grad_norm' and self.args.norm_running_update:
self.cs[layer] = torch.abs(projected_grad)
else:
# get number of zs to sample
num_zs = self.get_num_samples()
if num_zs > 1:
assert self.args.zero_order_use_trainer_optim, 'cannot sample multiple zs without storing intermediate gradient. use trainer.'
for _ in range(num_zs):
# prepare for sampling new zs
random_vector = None
if self.args.efficient_zero_order:
random_seed = np.random.randint(1000000000)
with torch.no_grad():
# first function evaluation
if self.args.efficient_zero_order:
model = self.efficient_perturb_parameters(model, random_seed)
elif self.args.zo_variant is not None:
model, random_vector = self.norm_perturb_parameters(model)
else:
model, random_vector = self.perturb_parameters(model)
loss1 = self.zo_forward(model, inputs)
# second function evaluation
if self.args.efficient_zero_order:
model = self.efficient_perturb_parameters(model, random_seed, scaling_factor=-2)
elif self.args.zo_variant is not None:
model, random_vector = self.norm_perturb_parameters(model, random_vector, scaling_factor=-2)
else:
model, random_vector = self.perturb_parameters(model, random_vector, scaling_factor=-2)
loss2 = self.zo_forward(model, inputs)
projected_grad = (loss1 - loss2) / (2 * self.args.zero_order_eps)
# scale grad according to accumulation
if self.args.gradient_accumulation_steps > 1:
assert self.args.zero_order_use_trainer_optim, 'grad accumulation not implemented for non-trainer ZO yet'
projected_grad = projected_grad / self.args.gradient_accumulation_steps
# scale grad according to number of zs sampled
if not self.args.scale_lr_with_samples:
projected_grad = projected_grad / float(num_zs)
# store gradient in parameter buffer if using trainer
# o/w, the loop will exit after one round and the update will be applied directly (see below)
if self.args.zero_order_use_trainer_optim:
if self.args.efficient_zero_order:
# print(random_seed)
torch.manual_seed(random_seed)
for name, param in self.named_parameters_to_optim:
# recover noise used in perturbations
if self.args.efficient_zero_order:
z = torch.normal(mean=0, std=1, size=param.data.size(), device=param.data.device, dtype=param.data.dtype)
else:
z = random_vector[name]
if self.args.zo_variant is not None and not self.args.change_grad_estimate:
cname = self.retrieve_c(name)
if cname in self.cs:
z = z * self.cs[cname]
if param.grad is None:
param.grad = projected_grad * z
else:
param.grad += projected_grad * z
# reset model back to its parameters at start of step
if self.args.efficient_zero_order:
model = self.efficient_perturb_parameters(model, random_seed)
elif self.args.zo_variant is not None:
model, random_vector = self.norm_perturb_parameters(model, random_vector)
else:
model, random_vector = self.perturb_parameters(model, random_vector)
# apply gradient updates
# if using trainer, follow trainer logic to clip grad and check if parameters should be updated
if self.args.zero_order_use_trainer_optim:
if (step + 1) % self.args.gradient_accumulation_steps == 0 or (
# last step in epoch but step is always smaller than gradient_accumulation_steps
len(epoch_iterator) <= self.args.gradient_accumulation_steps
and (step + 1) == len(epoch_iterator)
):
# Gradient norm clipping
if self.args.zero_order_clip_grad:
norm = torch.nn.utils.clip_grad_norm_(model.parameters(), self.args.max_grad_norm)
# Update the parameters and step scheduler
optimizer.step()
scheduler.step()
# logging
if (self.args.logging_steps > 0 and self.state.global_step % self.args.logging_steps == 0) or (
self.state.global_step == 1 and self.args.logging_first_step
):
logs = {}
logs["loss"] = loss1.item()
if not self.args.zero_order_clip_grad:
norm = 0.0
for _, p in model.named_parameters():
if p.grad is not None:
norm += torch.sum(p.grad ** 2)
norm = torch.sqrt(norm)
logs["grad_norm"] = norm.item()
logs["learning_rate"] = (
scheduler.get_last_lr()[0]
if version.parse(torch.__version__) >= version.parse("1.4")
else scheduler.get_lr()[0]
)
logs["num_zs"] = num_zs
logs["global_step"] = self.state.global_step
logs["zo_forward_step"] = self.state.zo_forward_step
logs["max_steps"] = self.args.max_steps
logs["max_zo_forward_steps"] = self.args.max_zo_forward_steps
logs["time"] = int(time.time() - start_time)
self.log(logs)
logger.info(str(logs))
model.zero_grad()
self.state.global_step += 1
self.epoch = epoch + (step + 1) / len(epoch_iterator)
# if not using the trainer, the updates are resampled and directly applied to the parameters
else:
# Efficient mode
# WARNING: no gradient accumulation when not storing the grad
assert self.args.gradient_accumulation_steps == 1, 'gradient accumulation is not supported for zero-order optimization'
assert self.args.zero_order_sample_scheduler is None
assert not self.args.zero_order_clip_grad, 'gradient clipping not implemented yet for non-trainer ZO'
if self.args.efficient_zero_order:
torch.manual_seed(random_seed)
for name, param in self.named_parameters_to_optim:
if self.args.efficient_zero_order:
z = torch.normal(mean=0, std=1, size=param.data.size(), device=param.data.device, dtype=param.data.dtype)
else:
z = random_vector[name]
param.data = param.data - self.args.learning_rate * (projected_grad * z + self.args.weight_decay * param.data)
if (self.args.logging_steps > 0 and self.state.global_step % self.args.logging_steps == 0) or (
self.state.global_step == 1 and self.args.logging_first_step
):
logs = {}
logs["loss"] = loss1.item()
logs["learning_rate"] = self.args.learning_rate
logs["global_step"] = self.state.global_step
logs["zo_forward_step"] = self.state.zo_forward_step
logs["max_steps"] = self.args.max_steps
logs["max_zo_forward_steps"] = self.args.max_zo_forward_steps
logs["time"] = int(time.time() - start_time)
self.log(logs)
logger.info(str(logs))
self.state.global_step += 1
self.epoch = epoch + (step + 1) / len(epoch_iterator)
# Debug information
# print("%.5f, %.5f" % (loss1.item(), loss2.item()))
# print("Loss: %.10f, projected_grad: %.5f" % (loss1, projected_grad))
# standard, non-ZO optimization
else:
tr_loss += self.training_step(model, inputs)
if (step + 1) % self.args.gradient_accumulation_steps == 0 or (
# last step in epoch but step is always smaller than gradient_accumulation_steps
len(epoch_iterator) <= self.args.gradient_accumulation_steps
and (step + 1) == len(epoch_iterator)
):
if self.args.fp16 and _use_native_amp:
self.scaler.unscale_(optimizer)
norm = torch.nn.utils.clip_grad_norm_(model.parameters(), self.args.max_grad_norm)
elif self.args.fp16:
norm = torch.nn.utils.clip_grad_norm_(amp.master_params(optimizer), self.args.max_grad_norm)
else:
norm = torch.nn.utils.clip_grad_norm_(model.parameters(), self.args.max_grad_norm)
if self.args.optimizer_variant == 'signgd':
for n,p in model.named_parameters():
if p.grad is not None:
p.grad = torch.sign(p.grad)
if transformers.is_torch_tpu_available():
xm.optimizer_step(optimizer)
elif self.args.fp16 and _use_native_amp:
self.scaler.step(optimizer)
self.scaler.update()
else:
optimizer.step()
scheduler.step()
model.zero_grad()
self.state.global_step += 1
self.epoch = epoch + (step + 1) / len(epoch_iterator)
if (self.args.logging_steps > 0 and self.state.global_step % self.args.logging_steps == 0) or (
self.state.global_step == 1 and self.args.logging_first_step
):
logs = {}
tr_loss_scalar = tr_loss.item()
logs["loss"] = (tr_loss_scalar - logging_loss_scalar) / self.args.logging_steps
logs["norm"] = norm.item()
# backward compatibility for pytorch schedulers
logs["learning_rate"] = (
scheduler.get_last_lr()[0]
if version.parse(torch.__version__) >= version.parse("1.4")
else scheduler.get_lr()[0]
)
logging_loss_scalar = tr_loss_scalar
self.log(logs)
logger.info(str(logs))
if self.args.max_steps > 0 and self.state.global_step > self.args.max_steps or (self.args.max_zo_forward_steps > 0 and self.state.zo_forward_step > self.args.max_zo_forward_steps):
epoch_iterator.close()
break
if self.args.evaluate_during_training and self.state.global_step % self.args.eval_steps == 0:
output = self.evaluate()
metrics = output.metrics
objective = self.dev_objective(metrics)
if objective > self.objective:
logger.info("Best dev result: {}".format(objective))
self.objective = objective
# self.save_model(self.args.output_dir)
# Now we save this to (CPU) memory instead of disk <-- much faster
self.best_model_ckpt = {k: v.detach().cpu() for k, v in model.state_dict().items()}
if self.args.max_steps > 0 and self.state.global_step > self.args.max_steps or (self.args.max_zo_forward_steps > 0 and self.state.zo_forward_step > self.args.max_zo_forward_steps):
# train_iterator.close()
break
if self.args.tpu_metrics_debug or self.args.debug:
# tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.)
xm.master_print(met.metrics_report())
if self.args.past_index and hasattr(self, "_past"):
# Clean the state at the end of training
delattr(self, "_past")
logger.info("\n\nTraining completed. Do not forget to share your model on huggingface.co/models =)\n\n")
return TrainOutput(self.state.global_step, tr_loss / self.state.global_step, metrics), self.objective
"""
Difference compared to original implementation: return output instead of output.metrics (so there is also the logits)
"""
def evaluate(self, eval_dataset: Optional[Dataset] = None) -> Dict[str, float]:
"""
Run evaluation and returns metrics.
The calling script will be responsible for providing a method to compute metrics, as they are
task-dependent (pass it to the init :obj:`compute_metrics` argument).
You can also subclass and override this method to inject custom behavior.
Args:
eval_dataset (:obj:`Dataset`, `optional`):
Pass a dataset if you wish to override :obj:`self.eval_dataset`. If it is an :obj:`datasets.Dataset`,
columns not accepted by the ``model.forward()`` method are automatically removed. It must implement
the :obj:`__len__` method.
Returns:
A dictionary containing the evaluation loss and the potential metrics computed from the predictions.
"""
if eval_dataset is not None and not isinstance(eval_dataset, collections.abc.Sized):
raise ValueError("eval_dataset must implement __len__")
eval_dataloader = self.get_eval_dataloader(eval_dataset)
output = self.prediction_loop(eval_dataloader, description="Evaluation")
self.log(output.metrics)
logger.info(output.metrics)
if self.args.tpu_metrics_debug or self.args.debug:
# tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.)
xm.master_print(met.metrics_report())
return output
@@ -0,0 +1,259 @@
import argparse
import json
import numpy as np
import torch
from torch import device
import itertools
from transformers.optimization import get_scheduler
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--condition", type=str, help="A dictionary contains conditions that the experiment results need to fulfill (e.g., tag, task_name, few_shot_type)")
parser.add_argument("--args_to_care", default=None, type=str, help="A list of args to care about. If provided, outputs which configs were not tested in your grid search")
# These options should be kept as their default values
parser.add_argument("--log", type=str, default="log", help="Log path.")
parser.add_argument("--key", type=str, default='', help="Validation metric name")
parser.add_argument("--test_key", type=str, default="", help="Test metric name")
parser.add_argument("--test_key2", type=str, default="", help="Second test metric name")
args = parser.parse_args()
condition = eval(args.condition)
if args.args_to_care is not None:
args_to_care = eval(args.args_to_care)
if len(args.key) == 0:
if condition['task_name'] == 'cola':
args.key = 'cola_dev_eval_mcc'
args.test_key = 'cola_test_eval_mcc'
elif condition['task_name'] == 'mrpc/acc':
args.key = 'mrpc_dev_eval_acc'
args.test_key = 'mrpc_test_eval_acc'
args.test_key2 = 'mrpc_test_eval_f1'
condition['task_name'] = 'mrpc'
elif condition['task_name'] == 'mrpc/f1':
args.key = 'mrpc_dev_eval_f1'
args.test_key2 = 'mrpc_test_eval_acc'
args.test_key = 'mrpc_test_eval_f1'
condition['task_name'] = 'mrpc'
elif condition['task_name'] == 'qqp/acc':
args.key = 'qqp_dev_eval_acc'
args.test_key = 'qqp_test_eval_acc'
args.test_key2 = 'qqp_test_eval_f1'
condition['task_name'] = 'qqp'
elif condition['task_name'] == 'qqp/f1':
args.key = 'qqp_dev_eval_f1'
args.test_key2 = 'qqp_test_eval_acc'
args.test_key = 'qqp_test_eval_f1'
condition['task_name'] = 'qqp'
elif condition['task_name'] == 'sts-b/pearson':
args.key = 'sts-b_dev_eval_pearson'
args.test_key = 'sts-b_test_eval_pearson'
args.test_key2 = 'sts-b_test_eval_spearmanr'
condition['task_name'] = 'sts-b'
elif condition['task_name'] == 'sts-b/spearmanr':
args.key = 'sts-b_dev_eval_spearmanr'
args.test_key2 = 'sts-b_test_eval_pearson'
args.test_key = 'sts-b_test_eval_spearmanr'
condition['task_name'] = 'sts-b'
elif condition['task_name'] == 'qnli':
args.key = 'qnli_dev_eval_acc'
args.test_key = 'qnli_test_eval_acc'
elif condition['task_name'] == 'sst-2':
args.key = 'sst-2_dev_eval_acc'
args.test_key = 'sst-2_test_eval_acc'
elif condition['task_name'] == 'snli':
args.key = 'snli_dev_eval_acc'
args.test_key = 'snli_test_eval_acc'
elif condition['task_name'] == 'mnli':
args.key = 'mnli_dev_eval_mnli/acc'
args.test_key = 'mnli_test_eval_mnli/acc'
elif condition['task_name'] == 'mnli-mm':
condition['task_name'] = 'mnli'
args.key = 'mnli_dev_eval_mnli/acc'
args.test_key = 'mnli-mm_test_eval_mnli-mm/acc'
elif condition['task_name'] == 'rte':
args.key = 'rte_dev_eval_acc'
args.test_key = 'rte_test_eval_acc'
elif condition['task_name'] == 'ag_news':
args.key = 'ag_news_dev_eval_acc'
args.test_key = 'ag_news_test_eval_acc'
elif condition['task_name'] == 'yahoo_answers':
args.key = 'yahoo_answers_dev_eval_acc'
args.test_key = 'yahoo_answers_test_eval_acc'
elif condition['task_name'] == 'yelp_review_full':
args.key = 'yelp_review_full_dev_eval_acc'
args.test_key = 'yelp_review_full_test_eval_acc'
elif condition['task_name'] == 'mr':
args.key = 'mr_dev_eval_acc'
args.test_key = 'mr_test_eval_acc'
elif condition['task_name'] == 'sst-5':
args.key = 'sst-5_dev_eval_acc'
args.test_key = 'sst-5_test_eval_acc'
elif condition['task_name'] == 'subj':
args.key = 'subj_dev_eval_acc'
args.test_key = 'subj_test_eval_acc'
elif condition['task_name'] == 'trec':
args.key = 'trec_dev_eval_acc'
args.test_key = 'trec_test_eval_acc'
elif condition['task_name'] == 'cr':
args.key = 'cr_dev_eval_acc'
args.test_key = 'cr_test_eval_acc'
elif condition['task_name'] == 'mpqa':
args.key = 'mpqa_dev_eval_acc'
args.test_key = 'mpqa_test_eval_acc'
else:
raise NotImplementedError
with open(args.log) as f:
result_list = []
for line in f:
line = line.replace("<", "\"")
line = line.replace(">", "\"")
line = line.replace(" inf,", "float('inf'),")
line = line.replace(" nan,", "float('nan'),")
result_list.append(eval(line))
seed_result = {}
for item in result_list:
ok = True
for cond in condition:
if isinstance(condition[cond], list):
if cond not in item or (item[cond] not in condition[cond]):
ok = False
break
else:
if cond not in item or (item[cond] != condition[cond]):
ok = False
break
if ok and args.test_key in item and args.key in item:
seed = item['data_dir'].split('-')[-1] + '-' + str(item['seed'])
if seed not in seed_result:
seed_result[seed] = [item]
else:
seed_result[seed].append(item)
all_seed_result = seed_result
all_tags = sorted(set(x['tag'] for x in sum(all_seed_result.values(), [])))
all_k = sorted(set(x['num_k'] for x in sum(all_seed_result.values(), [])))
for tag in all_tags:
for k in all_k:
print("Tag: {}, K: {}".format(tag, k))
seed_result_with_duplicates = {
s: list(x for x in v if x['tag'] == tag and x['num_k'] == k)
for s, v in all_seed_result.items()
}
seed_result = {
s: list({x['output_dir']: x for x in v}.values())
for s, v in seed_result_with_duplicates.items()
}
seed_best = {
k: max(sorted(v, key=lambda x: x['output_dir']), key=lambda x: x[args.key])
for k, v in seed_result.items() if v
}
### check if all possible configs were run or not
if args.args_to_care is not None:
unique_arg_values = {}
for _arg in args_to_care:
unique_arg_values[_arg] = []
# collect all desired configs and all that were run
arg_configs = {} # all configs that were run
for seed in seed_result.keys():
seed_configs = []
for config in seed_result[seed]:
if config['tag'] == tag and config['num_k'] == k:
_config = []
for _arg in args_to_care:
_value = config[_arg]
if _value not in unique_arg_values[_arg]:
unique_arg_values[_arg].append(_value)
_config.append(_value)
seed_configs.append(tuple(_config))
arg_configs[seed] = seed_configs
# compare to all possible configs
missing_configs = {'seeds': []}
for arg in args_to_care:
missing_configs[f'{arg}s'] = []
num_missing = 0
for seed in seed_result.keys():
all_possible_configs = itertools.product(*list(unique_arg_values.values()))
print(f'Missing configs for seed {seed}')
for config in all_possible_configs:
if config not in arg_configs[seed]:
missing_configs['seeds'].append(seed.split('-')[-1])
print(f'\t', end='')
for _arg, _val in zip(args_to_care, config):
print(f'{_arg}: {_val}', end=' ')
missing_configs[f'{_arg}s'].append(str(_val))
print()
num_missing += 1
print(f'Rerun {num_missing} configs')
for key, missed in missing_configs.items():
missed_str = ' '.join(missed)
print(f'{key}=({missed_str})')
final_result_dev = np.zeros((len(seed_best)))
final_result_test = np.zeros((len(seed_best)))
final_result_test2 = np.zeros((len(seed_best)))
final_result_loss = np.zeros((len(seed_best)))
num_results = np.zeros((len(seed_best)))
for i, seed in enumerate(seed_best):
# for res in seed_result[seed]:
# print(res)
final_result_dev[i] = seed_best[seed][args.key]
final_result_test[i] = seed_best[seed][args.test_key]
test_loss_key = args.test_key.split("_eval")[0] + "_eval_loss"
dev_loss_key = test_loss_key.replace("test", "dev")
final_result_loss[i] = seed_best[seed][test_loss_key]
num_results[i] = len(seed_result[seed])
if len(args.test_key2) > 0:
final_result_test2[i] = seed_best[seed][args.test_key2]
print("%s: best dev (%.5f, loss=%.4f) test (%.5f, loss=%.4f) %s | total trials: %d (ignored %d)" % (
seed,
seed_best[seed][args.key],
seed_best[seed][dev_loss_key],
seed_best[seed][args.test_key],
seed_best[seed][test_loss_key],
"test2 (%.5f)" % (seed_best[seed][args.test_key2]) if len(args.test_key2) > 0 else "",
len(seed_result[seed]),
len(seed_result_with_duplicates[seed]) - len(seed_result[seed])
))
s = ''
if args.args_to_care is None:
hp_to_care_about = [
'per_device_train_batch_size',
'gradient_accumulation_steps',
'learning_rate',
'zero_order_eps',
'zero_order_sample',
'zero_order_sample_scheduler',
'scale_lr_with_samples',
'lr_scheduler_type',
'weight_decay',
]
else:
hp_to_care_about = args_to_care
for k in hp_to_care_about:
s += '| {}: {} '.format(k, seed_best[seed].get(k, ""))
print(' ' + s)
s = "mean +- std: "
if len(final_result_test) > 0:
s += "%.1f (%.1f) (#seeds %s) (#runs %s) (median %.1f)" % (final_result_test.mean() * 100, final_result_test.std() * 100, len(final_result_test), num_results.sum(), np.median(final_result_test) * 100,)
if len(args.test_key2) > 0:
s += " | second metric: %.1f (%.1f) (median %.1f)" % (final_result_test2.mean() * 100, final_result_test2.std() * 100, np.median(final_result_test2) * 100)
s += " | loss: %.4f (%.4f)" % (final_result_loss.mean(), final_result_loss.std())
print(s)
print("")
if __name__ == '__main__':
main()
@@ -0,0 +1,192 @@
"""This script samples K examples randomly without replacement from the original data."""
import argparse
import os
import numpy as np
import pandas as pd
from pandas import DataFrame
def get_label(task, line):
if task in ["MNLI", "MRPC", "QNLI", "QQP", "RTE", "SNLI", "SST-2", "STS-B", "WNLI", "CoLA"]:
# GLUE style
line = line.strip().split('\t')
if task == 'CoLA':
return line[1]
elif task == 'MNLI':
return line[-1]
elif task == 'MRPC':
return line[0]
elif task == 'QNLI':
return line[-1]
elif task == 'QQP':
return line[-1]
elif task == 'RTE':
return line[-1]
elif task == 'SNLI':
return line[-1]
elif task == 'SST-2':
return line[-1]
elif task == 'STS-B':
return 0 if float(line[-1]) < 2.5 else 1
elif task == 'WNLI':
return line[-1]
else:
raise NotImplementedError
else:
return line[0]
def load_datasets(data_dir, tasks):
datasets = {}
for task in tasks:
if task in ["MNLI", "MRPC", "QNLI", "QQP", "RTE", "SNLI", "SST-2", "STS-B", "WNLI", "CoLA"]:
# GLUE style (tsv)
dataset = {}
dirname = os.path.join(data_dir, task)
if task == "MNLI":
splits = ["train", "dev_matched", "dev_mismatched"]
else:
splits = ["train", "dev"]
for split in splits:
filename = os.path.join(dirname, f"{split}.tsv")
with open(filename, "r") as f:
lines = f.readlines()
dataset[split] = lines
datasets[task] = dataset
else:
# Other datasets (csv)
dataset = {}
dirname = os.path.join(data_dir, task)
splits = ["train", "test"]
for split in splits:
filename = os.path.join(dirname, f"{split}.csv")
dataset[split] = pd.read_csv(filename, header=None)
datasets[task] = dataset
return datasets
def split_header(task, lines):
"""
Returns if the task file has a header or not. Only for GLUE tasks.
"""
if task in ["CoLA"]:
return [], lines
elif task in ["MNLI", "MRPC", "QNLI", "QQP", "RTE", "SNLI", "SST-2", "STS-B", "WNLI"]:
return lines[0:1], lines[1:]
else:
raise ValueError("Unknown GLUE task.")
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--k", type=int, default=16,
help="Training examples for each class.")
parser.add_argument("--task", type=str, nargs="+",
default=['SST-2', 'sst-5', 'mr', 'cr', 'mpqa', 'subj', 'trec', 'CoLA', 'MRPC', 'QQP', 'STS-B', 'MNLI', 'SNLI', 'QNLI', 'RTE'],
help="Task names")
parser.add_argument("--seed", type=int, nargs="+",
default=[100, 13, 21, 42, 87],
help="Random seeds")
parser.add_argument("--data_dir", type=str, default="data/original", help="Path to original data")
parser.add_argument("--output_dir", type=str, default="data", help="Output path")
parser.add_argument("--mode", type=str, default='k-shot', choices=['k-shot', 'k-shot-10x', 'k-shot-1k-test'], help="k-shot or k-shot-10x (10x dev set)")
args = parser.parse_args()
args.output_dir = os.path.join(args.output_dir, args.mode)
k = args.k
print("K =", k)
datasets = load_datasets(args.data_dir, args.task)
for seed in args.seed:
print("Seed = %d" % (seed))
for task, dataset in datasets.items():
# Set random seed
np.random.seed(seed)
# Shuffle the training set
print("| Task = %s" % (task))
if task in ["MNLI", "MRPC", "QNLI", "QQP", "RTE", "SNLI", "SST-2", "STS-B", "WNLI", "CoLA"]:
# GLUE style
train_header, train_lines = split_header(task, dataset["train"])
np.random.shuffle(train_lines)
else:
# Other datasets
train_lines = dataset['train'].values.tolist()
np.random.shuffle(train_lines)
# Set up dir
task_dir = os.path.join(args.output_dir, task)
setting_dir = os.path.join(task_dir, f"{k}-{seed}")
os.makedirs(setting_dir, exist_ok=True)
# Write test splits
if task in ["MNLI", "MRPC", "QNLI", "QQP", "RTE", "SNLI", "SST-2", "STS-B", "WNLI", "CoLA"]:
# GLUE style
# Use the original development set as the test set (the original test sets are not publicly available)
for split, lines in dataset.items():
if split.startswith("train"):
continue
split = split.replace('dev', 'test')
test_header, test_lines = split_header(task, lines)
if '1k-test' in args.mode and len(test_lines) > 1000:
np.random.seed(42)
np.random.shuffle(test_lines)
test_lines = test_lines[:1000]
with open(os.path.join(setting_dir, f"{split}.tsv"), "w") as f:
for line in test_header:
f.write(line)
for line in test_lines:
f.write(line)
else:
# Other datasets
# Use the original test sets
test_dataset = dataset['test']
if '1k-test' in args.mode and len(test_dataset.index) > 1000:
test_dataset = test_dataset.sample(n=1000, random_state=42)
test_dataset.to_csv(os.path.join(setting_dir, 'test.csv'), header=False, index=False)
# Get label list for balanced sampling
label_list = {}
for line in train_lines:
label = get_label(task, line)
if label not in label_list:
label_list[label] = [line]
else:
label_list[label].append(line)
if task in ["MNLI", "MRPC", "QNLI", "QQP", "RTE", "SNLI", "SST-2", "STS-B", "WNLI", "CoLA"]:
with open(os.path.join(setting_dir, "train.tsv"), "w") as f:
for line in train_header:
f.write(line)
for label in label_list:
for line in label_list[label][:k]:
f.write(line)
name = "dev.tsv"
if task == 'MNLI':
name = "dev_matched.tsv"
with open(os.path.join(setting_dir, name), "w") as f:
for line in train_header:
f.write(line)
for label in label_list:
dev_rate = 11 if '10x' in args.mode else 2
for line in label_list[label][k:k*dev_rate]:
f.write(line)
else:
new_train = []
for label in label_list:
for line in label_list[label][:k]:
new_train.append(line)
new_train = DataFrame(new_train)
new_train.to_csv(os.path.join(setting_dir, 'train.csv'), header=False, index=False)
new_dev = []
for label in label_list:
dev_rate = 11 if '10x' in args.mode else 2
for line in label_list[label][k:k*dev_rate]:
new_dev.append(line)
new_dev = DataFrame(new_dev)
new_dev.to_csv(os.path.join(setting_dir, 'dev.csv'), header=False, index=False)
if __name__ == "__main__":
main()
+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-mezo-experiment"
version = "0.1.0"
requires-python = ">=3.11,<3.12"
dependencies = ["torch==2.13.0", "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"]
[dependency-groups]
native = ["transformers==4.28.1", "datasets==2.14.7", "pyarrow==17.0.0", "accelerate==0.20.3", "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"}]]
+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='mezo')
+1711
View File
File diff suppressed because it is too large. Load diff