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

+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)