Stage Harbor release files 88501-89000
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/codeparrot/scripts/human_eval.py +228 -0
- tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/codeparrot/scripts/initialize_model.py +27 -0
- tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/codeparrot/scripts/minhash_deduplication.py +268 -0
- tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/codeparrot/scripts/preprocessing.py +215 -0
- tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/codeparrot/scripts/pretokenizing.py +49 -0
- tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/codeparrot/scripts/tests/__init__.py +0 -0
- tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/codeparrot/scripts/tests/test_deduplicate.py +29 -0
- tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/codeparrot/scripts/validation_loss.py +99 -0
- tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/decision_transformer/requirements.txt +240 -0
- tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/decision_transformer/run_decision_transformer.py +173 -0
- tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/deebert/README.md +54 -0
- tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/deebert/entropy_eval.sh +33 -0
- tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/deebert/eval_deebert.sh +30 -0
- tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/deebert/requirements.txt +1 -0
- tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/deebert/run_glue_deebert.py +735 -0
- tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/deebert/src/__init__.py +0 -0
- tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/deebert/src/modeling_highway_bert.py +397 -0
- tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/deebert/src/modeling_highway_roberta.py +154 -0
- tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/deebert/test_glue_deebert.py +104 -0
- tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/deebert/train_deebert.sh +38 -0
- tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/distillation/README.md +193 -0
- tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/distillation/distiller.py +601 -0
- tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/distillation/grouped_batch_sampler.py +108 -0
- tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/distillation/lm_seqs_dataset.py +167 -0
- tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/distillation/requirements.txt +7 -0
- tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/distillation/run_squad_w_distillation.py +877 -0
- tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/distillation/scripts/binarized_data.py +97 -0
- tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/distillation/scripts/extract.py +106 -0
- tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/distillation/scripts/extract_distilbert.py +96 -0
- tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/distillation/scripts/token_counts.py +57 -0
- tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/distillation/train.py +325 -0
- tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/distillation/training_configs/distilbert-base-cased.json +15 -0
- tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/distillation/training_configs/distilbert-base-multilingual-cased.json +15 -0
- tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/distillation/training_configs/distilbert-base-uncased.json +15 -0
- tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/distillation/training_configs/distilgpt2.json +9 -0
- tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/distillation/training_configs/distilroberta-base.json +14 -0
- tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/distillation/utils.py +134 -0
- tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/fsner/README.md +88 -0
- tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/fsner/pyproject.toml +7 -0
- tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/fsner/requirements.txt +1 -0
- tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/fsner/setup.py +27 -0
- tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/fsner/src/fsner/__init__.py +5 -0
- tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/fsner/src/fsner/model.py +80 -0
- tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/fsner/src/fsner/tokenizer_utils.py +102 -0
- tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/information-gain-filtration/README.md +100 -0
- tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/information-gain-filtration/igf/__init__.py +0 -0
- tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/information-gain-filtration/igf/igf.py +416 -0
- tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/information-gain-filtration/requirements.txt +6 -0
- tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/information-gain-filtration/result_igf.png +3 -0
- tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/information-gain-filtration/run_clm_igf.py +450 -0
tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/codeparrot/scripts/human_eval.py
ADDED
|
@@ -0,0 +1,228 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import multiprocessing
|
| 3 |
+
import os
|
| 4 |
+
import re
|
| 5 |
+
from collections import defaultdict
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
from accelerate import Accelerator
|
| 9 |
+
from accelerate.utils import set_seed
|
| 10 |
+
from arguments import HumanEvalArguments
|
| 11 |
+
from datasets import load_dataset, load_metric
|
| 12 |
+
from torch.utils.data import IterableDataset
|
| 13 |
+
from torch.utils.data.dataloader import DataLoader
|
| 14 |
+
from tqdm import tqdm
|
| 15 |
+
|
| 16 |
+
import transformers
|
| 17 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, HfArgumentParser, StoppingCriteria, StoppingCriteriaList
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
EOF_STRINGS = ["\nclass", "\ndef", "\n#", "\n@", "\nprint", "\nif"]
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class TokenizedDataset(IterableDataset):
|
| 24 |
+
"""Tokenize and preprocess the dataset
|
| 25 |
+
Multiple copies of the same prompt are sent sequentially.
|
| 26 |
+
See compute_code for more details.
|
| 27 |
+
"""
|
| 28 |
+
|
| 29 |
+
def __init__(self, tokenizer, dataset, n_tasks=None, n_copies=1):
|
| 30 |
+
self.tokenizer = tokenizer
|
| 31 |
+
self.dataset = dataset
|
| 32 |
+
self.n_tasks = len(dataset) if n_tasks is None else n_tasks
|
| 33 |
+
self.n_copies = n_copies
|
| 34 |
+
|
| 35 |
+
def __iter__(self):
|
| 36 |
+
prompts = []
|
| 37 |
+
for task in range(self.n_tasks):
|
| 38 |
+
# without strip, the model generate commented codes ...
|
| 39 |
+
prompts.append(self.tokenizer.eos_token + self.dataset[task]["prompt"].strip())
|
| 40 |
+
outputs = self.tokenizer(prompts, padding=True, return_tensors="pt")
|
| 41 |
+
for task in range(self.n_tasks):
|
| 42 |
+
for _ in range(self.n_copies):
|
| 43 |
+
yield {
|
| 44 |
+
"ids": outputs.input_ids[task],
|
| 45 |
+
"task_id": task,
|
| 46 |
+
"input_len": outputs.attention_mask[task].sum(),
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
class EndOfFunctionCriteria(StoppingCriteria):
|
| 51 |
+
"""Custom `StoppingCriteria` which checks if all generated functions in the batch are completed."""
|
| 52 |
+
|
| 53 |
+
def __init__(self, start_length, eof_strings, tokenizer):
|
| 54 |
+
self.start_length = start_length
|
| 55 |
+
self.eof_strings = eof_strings
|
| 56 |
+
self.tokenizer = tokenizer
|
| 57 |
+
|
| 58 |
+
def __call__(self, input_ids, scores, **kwargs):
|
| 59 |
+
"""Returns true if all generated sequences contain any of the end-of-function strings."""
|
| 60 |
+
decoded_generations = self.tokenizer.batch_decode(input_ids[:, self.start_length :])
|
| 61 |
+
done = []
|
| 62 |
+
for decoded_generation in decoded_generations:
|
| 63 |
+
done.append(any(stop_string in decoded_generation for stop_string in self.eof_strings))
|
| 64 |
+
return all(done)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def remove_last_block(string):
|
| 68 |
+
"""Remove the last block of the code containing EOF_STRINGS"""
|
| 69 |
+
string_list = re.split("(%s)" % "|".join(EOF_STRINGS), string)
|
| 70 |
+
# last string should be ""
|
| 71 |
+
return "".join(string_list[:-2])
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def complete_code(accelerator, model, tokenizer, dataloader, n_tasks, batch_size=20, **gen_kwargs):
|
| 75 |
+
"""Generate multiple codes for each task in the dataset. This function leverage accelerator to distribute
|
| 76 |
+
the processing to multiple GPUs.
|
| 77 |
+
dataloader, a wrapper around a TokenizeDataset objectm is supposed to send all the prompts from
|
| 78 |
+
the evalution dataset to the modelm as the following:
|
| 79 |
+
[p_0_0, p_0_1, ..., p_0_nc-1, p_1_0, ..., p_nt-1_nc-1]
|
| 80 |
+
where nc is the number of copies of the prompt, and nt is the number of tasks.
|
| 81 |
+
nc is such that num_sample = nc * batch_size
|
| 82 |
+
|
| 83 |
+
Parameters
|
| 84 |
+
----------
|
| 85 |
+
accelerator: Accelerator
|
| 86 |
+
|
| 87 |
+
model: transformers.PreTrainedModel
|
| 88 |
+
Code generation model. AutoTokenizer.from_pretrained(model_ckpt), ex model_ckpt = "lvwerra/codeparrot"
|
| 89 |
+
|
| 90 |
+
tokenizer: transformers.AutoTokenizer
|
| 91 |
+
The tokenizer used to train model
|
| 92 |
+
|
| 93 |
+
dataloader: DataLoader
|
| 94 |
+
The dataloader is a wrapper around a TokenizeDataset object. It is designed to be used with multiple GPUs.
|
| 95 |
+
|
| 96 |
+
n_tasks: int
|
| 97 |
+
The number of tasks in the dataset. It is used to determine the length of the output.
|
| 98 |
+
Should be aligned with the number of tasks in the TokenizeDataset.
|
| 99 |
+
|
| 100 |
+
batch_size: int
|
| 101 |
+
num_return_sequences per copy of the prompt such that num_sample = batch_size * n_copies
|
| 102 |
+
|
| 103 |
+
gen_kwargs: dict
|
| 104 |
+
Keyword arguments for the generation function of the model.
|
| 105 |
+
|
| 106 |
+
Returns
|
| 107 |
+
-------
|
| 108 |
+
code_gens: list of list of str, of length n_tasks
|
| 109 |
+
List of generated codes for each task.
|
| 110 |
+
Each element is a list of generated codes for each task, with length num_samples
|
| 111 |
+
"""
|
| 112 |
+
gen_token_dict = defaultdict(list) # dict of list of generated tokens
|
| 113 |
+
for step, batch in tqdm(enumerate(dataloader)):
|
| 114 |
+
with torch.no_grad():
|
| 115 |
+
gen_kwargs["stopping_criteria"][0].start_length = batch["ids"].shape[-1]
|
| 116 |
+
generated_tokens = accelerator.unwrap_model(model).generate(
|
| 117 |
+
input_ids=batch["ids"][:, : batch["input_len"]], num_return_sequences=batch_size, **gen_kwargs
|
| 118 |
+
)
|
| 119 |
+
# each task is generated batch_size times
|
| 120 |
+
generated_tasks = batch["task_id"].repeat(batch_size)
|
| 121 |
+
generated_tokens = accelerator.pad_across_processes(
|
| 122 |
+
generated_tokens, dim=1, pad_index=tokenizer.pad_token_id
|
| 123 |
+
)
|
| 124 |
+
|
| 125 |
+
generated_tokens, generated_tasks = accelerator.gather((generated_tokens, generated_tasks))
|
| 126 |
+
generated_tokens = generated_tokens.cpu().numpy()
|
| 127 |
+
generated_tasks = generated_tasks.cpu().numpy()
|
| 128 |
+
|
| 129 |
+
for task, generated_tokens in zip(generated_tasks, generated_tokens):
|
| 130 |
+
gen_token_dict[task].append(generated_tokens)
|
| 131 |
+
|
| 132 |
+
code_gens = [[] for _ in range(n_tasks)]
|
| 133 |
+
for task, generated_tokens in gen_token_dict.items():
|
| 134 |
+
for s in generated_tokens:
|
| 135 |
+
gen_code = tokenizer.decode(s, skip_special_tokens=True, clean_up_tokenization_spaces=True)
|
| 136 |
+
code_gens[task].append(remove_last_block(gen_code))
|
| 137 |
+
return code_gens
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def main():
|
| 141 |
+
# Setup configuration
|
| 142 |
+
parser = HfArgumentParser(HumanEvalArguments)
|
| 143 |
+
args = parser.parse_args()
|
| 144 |
+
|
| 145 |
+
transformers.logging.set_verbosity_error()
|
| 146 |
+
# enables code execution in code_eval metric
|
| 147 |
+
os.environ["HF_ALLOW_CODE_EVAL"] = args.HF_ALLOW_CODE_EVAL
|
| 148 |
+
# make sure tokenizer plays nice with multiprocessing
|
| 149 |
+
os.environ["TOKENIZERS_PARALLELISM"] = "false"
|
| 150 |
+
|
| 151 |
+
if args.num_workers is None:
|
| 152 |
+
args.num_workers = multiprocessing.cpu_count()
|
| 153 |
+
|
| 154 |
+
# Use dataset load to feed to accelerate
|
| 155 |
+
accelerator = Accelerator()
|
| 156 |
+
set_seed(args.seed, device_specific=True)
|
| 157 |
+
|
| 158 |
+
# Load model and tokenizer
|
| 159 |
+
tokenizer = AutoTokenizer.from_pretrained(args.model_ckpt)
|
| 160 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 161 |
+
model = AutoModelForCausalLM.from_pretrained(args.model_ckpt)
|
| 162 |
+
|
| 163 |
+
# Generation settings
|
| 164 |
+
gen_kwargs = {
|
| 165 |
+
"do_sample": args.do_sample,
|
| 166 |
+
"temperature": args.temperature,
|
| 167 |
+
"max_new_tokens": args.max_new_tokens,
|
| 168 |
+
"top_p": args.top_p,
|
| 169 |
+
"top_k": args.top_k,
|
| 170 |
+
"stopping_criteria": StoppingCriteriaList([EndOfFunctionCriteria(0, EOF_STRINGS, tokenizer)]),
|
| 171 |
+
}
|
| 172 |
+
|
| 173 |
+
# Load evaluation dataset and metric
|
| 174 |
+
human_eval = load_dataset("openai_humaneval")
|
| 175 |
+
code_eval_metric = load_metric("code_eval")
|
| 176 |
+
|
| 177 |
+
n_tasks = args.num_tasks if args.num_tasks is not None else len(human_eval["test"])
|
| 178 |
+
n_copies = args.n_samples // args.batch_size
|
| 179 |
+
|
| 180 |
+
human_eval_tokenized = TokenizedDataset(tokenizer, human_eval["test"], n_copies=n_copies, n_tasks=n_tasks)
|
| 181 |
+
# do not confuse args.batch_size, which is actually the num_return_sequences
|
| 182 |
+
human_eval_loader = DataLoader(human_eval_tokenized, batch_size=1)
|
| 183 |
+
|
| 184 |
+
# Run a quick test to see if code evaluation is enabled
|
| 185 |
+
try:
|
| 186 |
+
_ = code_eval_metric.compute(references=[""], predictions=[[""]])
|
| 187 |
+
except ValueError as exception:
|
| 188 |
+
print(
|
| 189 |
+
'Code evaluation not enabled. Read the warning below carefully and then use `--HF_ALLOW_CODE_EVAL="1"`'
|
| 190 |
+
" flag to enable code evaluation."
|
| 191 |
+
)
|
| 192 |
+
raise exception
|
| 193 |
+
|
| 194 |
+
model, human_eval_loader = accelerator.prepare(model, human_eval_loader)
|
| 195 |
+
|
| 196 |
+
generations = complete_code(
|
| 197 |
+
accelerator,
|
| 198 |
+
model,
|
| 199 |
+
tokenizer,
|
| 200 |
+
human_eval_loader,
|
| 201 |
+
n_tasks=n_tasks,
|
| 202 |
+
batch_size=args.batch_size,
|
| 203 |
+
**gen_kwargs,
|
| 204 |
+
)
|
| 205 |
+
|
| 206 |
+
if accelerator.is_main_process:
|
| 207 |
+
references = []
|
| 208 |
+
|
| 209 |
+
for task in tqdm(range(n_tasks)):
|
| 210 |
+
test_func = human_eval["test"][task]["test"]
|
| 211 |
+
entry_point = f"check({human_eval['test'][task]['entry_point']})"
|
| 212 |
+
references.append("\n" + test_func + "\n" + entry_point)
|
| 213 |
+
|
| 214 |
+
# Evaluate completions with "code_eval" metric
|
| 215 |
+
pass_at_k, _ = code_eval_metric.compute(
|
| 216 |
+
references=references, predictions=generations, num_workers=args.num_workers
|
| 217 |
+
)
|
| 218 |
+
print(f"Results: {pass_at_k}")
|
| 219 |
+
|
| 220 |
+
# Save results to json file
|
| 221 |
+
with open(args.output_file, "w") as fp:
|
| 222 |
+
json.dump(pass_at_k, fp)
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
# For some reason the folliwng seems to be necessary sometimes for code_eval to work nice with multiprocessing
|
| 226 |
+
# https://stackoverflow.com/questions/60804599/python-multiprocessing-keeps-spawning-the-whole-script
|
| 227 |
+
if __name__ == "__main__":
|
| 228 |
+
main()
|
tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/codeparrot/scripts/initialize_model.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from arguments import InitializationArguments
|
| 2 |
+
|
| 3 |
+
from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer, HfArgumentParser
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
# Configuration
|
| 7 |
+
parser = HfArgumentParser(InitializationArguments)
|
| 8 |
+
args = parser.parse_args()
|
| 9 |
+
|
| 10 |
+
# Load codeparrot tokenizer trained for Python code tokenization
|
| 11 |
+
tokenizer = AutoTokenizer.from_pretrained(args.tokenizer_name)
|
| 12 |
+
|
| 13 |
+
# Config: "scale_attn_by_layer_idx" and "reorder_and_upcast_attn" are Mistral stability tweaks
|
| 14 |
+
config_kwargs = {
|
| 15 |
+
"vocab_size": len(tokenizer),
|
| 16 |
+
"scale_attn_by_inverse_layer_idx": True,
|
| 17 |
+
"reorder_and_upcast_attn": True,
|
| 18 |
+
}
|
| 19 |
+
|
| 20 |
+
# Load model config (GPT-2 large in this case)
|
| 21 |
+
config = AutoConfig.from_pretrained(args.config_name, **config_kwargs)
|
| 22 |
+
|
| 23 |
+
# Initialize new model with config
|
| 24 |
+
model = AutoModelForCausalLM.from_config(config)
|
| 25 |
+
|
| 26 |
+
# Save model to the hub
|
| 27 |
+
model.save_pretrained(args.model_name, push_to_hub=args.push_to_hub)
|
tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/codeparrot/scripts/minhash_deduplication.py
ADDED
|
@@ -0,0 +1,268 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import multiprocessing as mp
|
| 3 |
+
import re
|
| 4 |
+
from collections import defaultdict
|
| 5 |
+
from functools import partial
|
| 6 |
+
from typing import Dict, List, Optional, Set, Tuple, Type
|
| 7 |
+
|
| 8 |
+
from datasets import Dataset
|
| 9 |
+
from datasketch import MinHash, MinHashLSH
|
| 10 |
+
from dpu_utils.utils.iterators import ThreadedIterator
|
| 11 |
+
from tqdm import tqdm
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
NON_ALPHA = re.compile("[^A-Za-z_0-9]")
|
| 15 |
+
# parameters used in DuplicationIndex
|
| 16 |
+
MIN_NUM_TOKENS = 10
|
| 17 |
+
NUM_PERM = 256
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def get_min_hash(tokens: List[str]) -> Optional[MinHash]:
|
| 21 |
+
"""Compute the MinHash of a code snippet."""
|
| 22 |
+
if len(tokens) < MIN_NUM_TOKENS:
|
| 23 |
+
return None
|
| 24 |
+
min_hash = MinHash(num_perm=NUM_PERM)
|
| 25 |
+
for token in set(tokens):
|
| 26 |
+
min_hash.update(token.encode())
|
| 27 |
+
return min_hash
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def get_tokens(code: str) -> Set[str]:
|
| 31 |
+
"""Tokenize a code snippet."""
|
| 32 |
+
return {t for t in NON_ALPHA.split(code) if len(t.strip()) > 0}
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class DuplicationIndex:
|
| 36 |
+
def __init__(
|
| 37 |
+
self,
|
| 38 |
+
*,
|
| 39 |
+
duplication_jaccard_threshold: float = 0.85,
|
| 40 |
+
):
|
| 41 |
+
self._duplication_jaccard_threshold = duplication_jaccard_threshold
|
| 42 |
+
self._num_perm = NUM_PERM
|
| 43 |
+
self._index = MinHashLSH(threshold=self._duplication_jaccard_threshold, num_perm=self._num_perm)
|
| 44 |
+
|
| 45 |
+
self._duplicate_clusters = defaultdict(set)
|
| 46 |
+
|
| 47 |
+
def add(self, code_key: Tuple, min_hash: MinHash) -> None:
|
| 48 |
+
"""Add a key to _index (MinHashLSH)
|
| 49 |
+
the min_hash is used to query closest matches based on the jaccard_threshold.
|
| 50 |
+
The new key is either added to a existing cluster of one close match,
|
| 51 |
+
or a new cluster is created. The clusters created in this way, depend on the order of add.
|
| 52 |
+
|
| 53 |
+
Args:
|
| 54 |
+
code_key (Tuple of (index, repo_name, path)):
|
| 55 |
+
Theoritically any hasbale key. Here we use a tuple to retrieve the information later.
|
| 56 |
+
min_hash: MinHash of the code_key.
|
| 57 |
+
"""
|
| 58 |
+
close_duplicates = self._index.query(min_hash)
|
| 59 |
+
if code_key in self._index.keys:
|
| 60 |
+
print(f"Duplicate key {code_key}")
|
| 61 |
+
return
|
| 62 |
+
|
| 63 |
+
self._index.insert(code_key, min_hash)
|
| 64 |
+
if len(close_duplicates) > 0:
|
| 65 |
+
for base_duplicate in close_duplicates:
|
| 66 |
+
if base_duplicate in self._duplicate_clusters:
|
| 67 |
+
self._duplicate_clusters[base_duplicate].add(code_key)
|
| 68 |
+
break
|
| 69 |
+
else:
|
| 70 |
+
self._duplicate_clusters[close_duplicates[0]].add(code_key)
|
| 71 |
+
|
| 72 |
+
def get_duplicate_clusters(self) -> List[List[Dict]]:
|
| 73 |
+
"""Export the duplicate clusters.
|
| 74 |
+
For each cluster, the first element is the base element of the cluster.
|
| 75 |
+
The base element has an estimation jaccard similarity higher than the threshold with all the other elements.
|
| 76 |
+
|
| 77 |
+
Returns:
|
| 78 |
+
duplicate_clusters (List[List[Dict]]):
|
| 79 |
+
List of duplicate clusters.
|
| 80 |
+
"""
|
| 81 |
+
duplicate_clusters = []
|
| 82 |
+
for base, duplicates in self._duplicate_clusters.items():
|
| 83 |
+
cluster = [base] + list(duplicates)
|
| 84 |
+
# reformat the cluster to be a list of dict
|
| 85 |
+
cluster = [{"base_index": el[0], "repo_name": el[1], "path": el[2]} for el in cluster]
|
| 86 |
+
duplicate_clusters.append(cluster)
|
| 87 |
+
return duplicate_clusters
|
| 88 |
+
|
| 89 |
+
def save(self, filepath) -> None:
|
| 90 |
+
duplicate_clusters = self.get_duplicate_clusters()
|
| 91 |
+
with open(filepath, "w") as f:
|
| 92 |
+
json.dump(duplicate_clusters, f)
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def _compute_min_hash(element):
|
| 96 |
+
index, data = element
|
| 97 |
+
min_hash = get_min_hash([t for t in NON_ALPHA.split(data["content"]) if len(t.strip()) > 0])
|
| 98 |
+
if min_hash is not None:
|
| 99 |
+
return (index, data["repo_name"], data["path"]), min_hash
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def minhash_iter(dataset_iterator: Type[Dataset]):
|
| 103 |
+
with mp.Pool() as pool:
|
| 104 |
+
for data in pool.imap_unordered(
|
| 105 |
+
_compute_min_hash,
|
| 106 |
+
ThreadedIterator(dataset_iterator, max_queue_size=10000),
|
| 107 |
+
chunksize=100,
|
| 108 |
+
):
|
| 109 |
+
if data is not None:
|
| 110 |
+
yield data
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def make_duplicate_clusters(dataset_iterator: Type[Dataset], jaccard_threshold: float):
|
| 114 |
+
"""Find duplicate clusters in the dataset in two steps:
|
| 115 |
+
1. Compute MinHash for each code snippet. MinHash is a tool for fast jaccard similarity estimation.
|
| 116 |
+
This step is computed using an asynchronous multiprocessing pool, minhash_iter
|
| 117 |
+
2. Find duplicate clusters. The computed MinHash is added sequentially to the DuplicationIndex.
|
| 118 |
+
This step cannot be parallelized. So using asynchronous thread in the previous step helps to speed up the process.
|
| 119 |
+
"""
|
| 120 |
+
di = DuplicationIndex(duplication_jaccard_threshold=jaccard_threshold)
|
| 121 |
+
|
| 122 |
+
for filename, min_hash in tqdm(ThreadedIterator(minhash_iter(enumerate(dataset_iterator)), max_queue_size=100)):
|
| 123 |
+
di.add(filename, min_hash)
|
| 124 |
+
|
| 125 |
+
# Returns a List[Cluster] where Cluster is List[str] with the filenames.
|
| 126 |
+
return di.get_duplicate_clusters()
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def jaccard_similarity(code1: str, code2: str) -> float:
|
| 130 |
+
"""Compute the Jaccard similarity of two code snippets."""
|
| 131 |
+
tokens1 = get_tokens(code1)
|
| 132 |
+
tokens2 = get_tokens(code2)
|
| 133 |
+
return len(tokens1 & tokens2) / len(tokens1 | tokens2)
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
_shared_dataset = None
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def _find_cluster_extremes_shared(cluster, jaccard_threshold):
|
| 140 |
+
"""Find a reduced cluster such that each code in the origin cluster is similar to at least one code in the reduced cluster.
|
| 141 |
+
Two codes are similar if their Jaccard similarity is above the threshold.
|
| 142 |
+
|
| 143 |
+
Args:
|
| 144 |
+
cluster (List[dict]):
|
| 145 |
+
cluster is a list of dict, each dict contains the following keys:
|
| 146 |
+
- base_index
|
| 147 |
+
- repo_name
|
| 148 |
+
- path
|
| 149 |
+
This is a typical output of DuplicationIndex.get_duplicate_clusters()
|
| 150 |
+
jaccard_threshold (float):
|
| 151 |
+
threshold for Jaccard similarity.
|
| 152 |
+
Two codes are similar if their Jaccard similarity is above the threshold.
|
| 153 |
+
|
| 154 |
+
Returns:
|
| 155 |
+
extremes (List[dict]):
|
| 156 |
+
A reduced representation of the cluster. The field copies is added to each dict.
|
| 157 |
+
The copies field indicates the number of similar codes in the cluster for a extreme.
|
| 158 |
+
"""
|
| 159 |
+
extremes = []
|
| 160 |
+
for element1 in cluster:
|
| 161 |
+
code1 = _shared_dataset[element1["base_index"]]["content"]
|
| 162 |
+
for element2 in extremes:
|
| 163 |
+
code2 = _shared_dataset[element2["base_index"]]["content"]
|
| 164 |
+
if jaccard_similarity(code1, code2) >= jaccard_threshold:
|
| 165 |
+
element2["copies"] += 1
|
| 166 |
+
break
|
| 167 |
+
else:
|
| 168 |
+
element1["copies"] = 1
|
| 169 |
+
extremes.append(element1)
|
| 170 |
+
return extremes
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def find_extremes(cluster_list, dataset, jaccard_threshold):
|
| 174 |
+
"""Call the _find_cluster_extremes_shared function in a parallel fashion.
|
| 175 |
+
|
| 176 |
+
Args:
|
| 177 |
+
cluster_list (List[List[Dict]]):
|
| 178 |
+
each cluster is a list of dicts with the key base_index,
|
| 179 |
+
referring to the index of the base code in the dataset.
|
| 180 |
+
dataset (Type[Dataset]):
|
| 181 |
+
dataset is used to access the content of the code snippets,
|
| 182 |
+
using the base_index from the cluster_list.
|
| 183 |
+
dataset is shared between all the processes using a glabal variable (any other way to share the dataset?),
|
| 184 |
+
otherwise the multi processing is not speeded up.
|
| 185 |
+
jaccard_threshold (float):
|
| 186 |
+
the threshold for the jaccard similarity. The default value is 0.85
|
| 187 |
+
|
| 188 |
+
Returns:
|
| 189 |
+
extremes_list (List[Dict]):
|
| 190 |
+
Each cluster is reduced to extremes.
|
| 191 |
+
See _find_cluster_extremes_shared for the definition of extremes.
|
| 192 |
+
"""
|
| 193 |
+
global _shared_dataset
|
| 194 |
+
_shared_dataset = dataset
|
| 195 |
+
extremes_list = []
|
| 196 |
+
f = partial(_find_cluster_extremes_shared, jaccard_threshold=jaccard_threshold)
|
| 197 |
+
with mp.Pool() as pool:
|
| 198 |
+
for extremes in tqdm(
|
| 199 |
+
pool.imap_unordered(
|
| 200 |
+
f,
|
| 201 |
+
cluster_list,
|
| 202 |
+
),
|
| 203 |
+
total=len(cluster_list),
|
| 204 |
+
):
|
| 205 |
+
extremes_list.append(extremes)
|
| 206 |
+
return extremes_list
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
def deduplicate_dataset(
|
| 210 |
+
dataset: Type[Dataset], jaccard_threshold: float = 0.85
|
| 211 |
+
) -> Tuple[Type[Dataset], List[List[Dict]]]:
|
| 212 |
+
"""Deduplicate the dataset using minhash and jaccard similarity.
|
| 213 |
+
This function first generate duplicate clusters, then each cluster
|
| 214 |
+
is reduced to the extremes that are similar to the other elements in the cluster.
|
| 215 |
+
Codes are called similar if their Jaccard similarity is greater than jaccard_threshold (0.85 default).
|
| 216 |
+
|
| 217 |
+
Args:
|
| 218 |
+
dataset (Type[Dataset]):
|
| 219 |
+
The dataset to deduplicate.
|
| 220 |
+
jaccard_threshold (float, default=0.85):
|
| 221 |
+
jaccard threshold to determine if two codes are similar
|
| 222 |
+
|
| 223 |
+
Returns:
|
| 224 |
+
ds_dedup (Type[Dataset]):
|
| 225 |
+
The deduplicated dataset.
|
| 226 |
+
duplicate_clusters (List[List[Dict]]):
|
| 227 |
+
The list of duplicate clusters.
|
| 228 |
+
Each cluster is a list of dicts with the following keys:
|
| 229 |
+
- base_index : int
|
| 230 |
+
The index of the code in the original dataset.
|
| 231 |
+
- repo_name : str
|
| 232 |
+
- path : str
|
| 233 |
+
- copies : int
|
| 234 |
+
The number of copies of the code in the cluster. (find_cluster_extremes)
|
| 235 |
+
- is_extreme : bool
|
| 236 |
+
Whether the code is an extreme in the cluster.
|
| 237 |
+
All the codes in the cluster are removed from the dataset except the extremes.
|
| 238 |
+
|
| 239 |
+
Example:
|
| 240 |
+
>>> from datasets import load_dataset
|
| 241 |
+
>>> from minhash_deduplication import deduplicate_dataset
|
| 242 |
+
>>> ds = load_dataset("lvwerra/codeparrot-clean", split="train")
|
| 243 |
+
>>> ds_dedup, duplicate_clusters = deduplicate_dataset(ds, jaccard_threshold=0.85)
|
| 244 |
+
"""
|
| 245 |
+
duplicate_clusters = make_duplicate_clusters(dataset, jaccard_threshold)
|
| 246 |
+
duplicate_indices = {x["base_index"] for cluster in duplicate_clusters for x in cluster}
|
| 247 |
+
extreme_dict = {}
|
| 248 |
+
extremes_clusters = find_extremes(duplicate_clusters, dataset, jaccard_threshold)
|
| 249 |
+
for extremes in extremes_clusters:
|
| 250 |
+
for element in extremes:
|
| 251 |
+
extreme_dict[element["base_index"]] = element
|
| 252 |
+
remove_indices = duplicate_indices - set(extreme_dict.keys())
|
| 253 |
+
ds_filter = dataset.filter(lambda x, idx: idx not in remove_indices, with_indices=True)
|
| 254 |
+
|
| 255 |
+
# update duplicate_clusters
|
| 256 |
+
for cluster in duplicate_clusters:
|
| 257 |
+
for element in cluster:
|
| 258 |
+
element["is_extreme"] = element["base_index"] in extreme_dict
|
| 259 |
+
if element["is_extreme"]:
|
| 260 |
+
element["copies"] = extreme_dict[element["base_index"]]["copies"]
|
| 261 |
+
|
| 262 |
+
print(f"Original dataset size: {len(dataset)}")
|
| 263 |
+
print(f"Number of duplicate clusters: {len(duplicate_clusters)}")
|
| 264 |
+
print(f"Files in duplicate cluster: {len(duplicate_indices)}")
|
| 265 |
+
print(f"Unique files in duplicate cluster: {len(extreme_dict)}")
|
| 266 |
+
print(f"Filtered dataset size: {len(ds_filter)}")
|
| 267 |
+
|
| 268 |
+
return ds_filter, duplicate_clusters
|
tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/codeparrot/scripts/preprocessing.py
ADDED
|
@@ -0,0 +1,215 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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11 |
+
from arguments import PreprocessingArguments
|
| 12 |
+
from datasets import load_dataset
|
| 13 |
+
from huggingface_hub.utils import insecure_hashlib
|
| 14 |
+
from minhash_deduplication import deduplicate_dataset
|
| 15 |
+
|
| 16 |
+
from transformers import AutoTokenizer, HfArgumentParser
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
PATTERN = re.compile(r"\s+")
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def get_hash(example):
|
| 23 |
+
"""Get hash of content field."""
|
| 24 |
+
return {"hash": insecure_hashlib.md5(re.sub(PATTERN, "", example["content"]).encode("utf-8")).hexdigest()}
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def line_stats(example):
|
| 28 |
+
"""Calculates mean and max line length of file."""
|
| 29 |
+
line_lengths = [len(line) for line in example["content"].splitlines()]
|
| 30 |
+
return {"line_mean": np.mean(line_lengths), "line_max": max(line_lengths)}
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def alpha_stats(example):
|
| 34 |
+
"""Calculates mean and max line length of file."""
|
| 35 |
+
alpha_frac = np.mean([c.isalnum() for c in example["content"]])
|
| 36 |
+
return {"alpha_frac": alpha_frac}
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def check_uniques(example, uniques):
|
| 40 |
+
"""Check if current hash is still in set of unique hashes and remove if true."""
|
| 41 |
+
if example["hash"] in uniques:
|
| 42 |
+
uniques.remove(example["hash"])
|
| 43 |
+
return True
|
| 44 |
+
else:
|
| 45 |
+
return False
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def is_autogenerated(example, scan_width=5):
|
| 49 |
+
"""Check if file is autogenerated by looking for keywords in the first few lines of the file."""
|
| 50 |
+
keywords = ["auto-generated", "autogenerated", "automatically generated"]
|
| 51 |
+
lines = example["content"].splitlines()
|
| 52 |
+
for _, line in zip(range(scan_width), lines):
|
| 53 |
+
for keyword in keywords:
|
| 54 |
+
if keyword in line.lower():
|
| 55 |
+
return {"autogenerated": True}
|
| 56 |
+
else:
|
| 57 |
+
return {"autogenerated": False}
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def is_config_or_test(example, scan_width=5, coeff=0.05):
|
| 61 |
+
"""Check if file is a configuration file or a unit test by :
|
| 62 |
+
1- looking for keywords in the first few lines of the file.
|
| 63 |
+
2- counting number of occurrence of the words 'config' and 'test' with respect to number of lines.
|
| 64 |
+
"""
|
| 65 |
+
|
| 66 |
+
keywords = ["unit tests", "test file", "configuration file"]
|
| 67 |
+
lines = example["content"].splitlines()
|
| 68 |
+
count_config = 0
|
| 69 |
+
count_test = 0
|
| 70 |
+
# first test
|
| 71 |
+
for _, line in zip(range(scan_width), lines):
|
| 72 |
+
for keyword in keywords:
|
| 73 |
+
if keyword in line.lower():
|
| 74 |
+
return {"config_or_test": True}
|
| 75 |
+
# second test
|
| 76 |
+
nlines = example["content"].count("\n")
|
| 77 |
+
threshold = int(coeff * nlines)
|
| 78 |
+
for line in lines:
|
| 79 |
+
count_config += line.lower().count("config")
|
| 80 |
+
count_test += line.lower().count("test")
|
| 81 |
+
if count_config > threshold or count_test > threshold:
|
| 82 |
+
return {"config_or_test": True}
|
| 83 |
+
return {"config_or_test": False}
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def has_no_keywords(example):
|
| 87 |
+
"""Check if a python file has none of the keywords for: funcion, class, for loop, while loop."""
|
| 88 |
+
keywords = ["def ", "class ", "for ", "while "]
|
| 89 |
+
lines = example["content"].splitlines()
|
| 90 |
+
for line in lines:
|
| 91 |
+
for keyword in keywords:
|
| 92 |
+
if keyword in line.lower():
|
| 93 |
+
return {"has_no_keywords": False}
|
| 94 |
+
return {"has_no_keywords": True}
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def has_few_assignments(example, minimum=4):
|
| 98 |
+
"""Check if file uses symbol '=' less than `minimum` times."""
|
| 99 |
+
lines = example["content"].splitlines()
|
| 100 |
+
counter = 0
|
| 101 |
+
for line in lines:
|
| 102 |
+
counter += line.lower().count("=")
|
| 103 |
+
if counter > minimum:
|
| 104 |
+
return {"has_few_assignments": False}
|
| 105 |
+
return {"has_few_assignments": True}
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def char_token_ratio(example):
|
| 109 |
+
"""Compute character/token ratio of the file with tokenizer."""
|
| 110 |
+
input_ids = tokenizer(example["content"], truncation=False)["input_ids"]
|
| 111 |
+
ratio = len(example["content"]) / len(input_ids)
|
| 112 |
+
return {"ratio": ratio}
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def preprocess(example):
|
| 116 |
+
"""Chain all preprocessing steps into one function to not fill cache."""
|
| 117 |
+
results = {}
|
| 118 |
+
results.update(get_hash(example))
|
| 119 |
+
results.update(line_stats(example))
|
| 120 |
+
results.update(alpha_stats(example))
|
| 121 |
+
results.update(char_token_ratio(example))
|
| 122 |
+
results.update(is_autogenerated(example))
|
| 123 |
+
results.update(is_config_or_test(example))
|
| 124 |
+
results.update(has_no_keywords(example))
|
| 125 |
+
results.update(has_few_assignments(example))
|
| 126 |
+
return results
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def filter(example, uniques, args):
|
| 130 |
+
"""Filter dataset with heuristics. Config, test and has_no_keywords files are removed with a given probability."""
|
| 131 |
+
if not check_uniques(example, uniques):
|
| 132 |
+
return False
|
| 133 |
+
elif example["autogenerated"]:
|
| 134 |
+
return False
|
| 135 |
+
elif example["line_max"] > args.line_max:
|
| 136 |
+
return False
|
| 137 |
+
elif example["line_mean"] > args.line_mean:
|
| 138 |
+
return False
|
| 139 |
+
elif example["alpha_frac"] < args.alpha_frac:
|
| 140 |
+
return False
|
| 141 |
+
elif example["ratio"] < args.min_token_ratio:
|
| 142 |
+
return False
|
| 143 |
+
elif example["config_or_test"] and np.random.rand() <= args.filter_proba:
|
| 144 |
+
return False
|
| 145 |
+
elif example["has_no_keywords"] and np.random.rand() <= args.filter_proba:
|
| 146 |
+
return False
|
| 147 |
+
elif example["has_few_assignments"]:
|
| 148 |
+
return False
|
| 149 |
+
else:
|
| 150 |
+
return True
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def compress_file(file_path):
|
| 154 |
+
"""Compress a file with g-zip."""
|
| 155 |
+
with open(file_path, "rb") as f_in:
|
| 156 |
+
with gzip.open(str(file_path) + ".gz", "wb", compresslevel=6) as f_out:
|
| 157 |
+
shutil.copyfileobj(f_in, f_out)
|
| 158 |
+
os.unlink(file_path)
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
# Settings
|
| 162 |
+
parser = HfArgumentParser(PreprocessingArguments)
|
| 163 |
+
args = parser.parse_args()
|
| 164 |
+
if args.num_workers is None:
|
| 165 |
+
args.num_workers = multiprocessing.cpu_count()
|
| 166 |
+
tokenizer = AutoTokenizer.from_pretrained(args.tokenizer_dir)
|
| 167 |
+
|
| 168 |
+
# Load dataset
|
| 169 |
+
t_start = time.time()
|
| 170 |
+
ds = load_dataset(args.dataset_name, split="train")
|
| 171 |
+
print(f"Time to load dataset: {time.time()-t_start:.2f}")
|
| 172 |
+
|
| 173 |
+
# Run preprocessing
|
| 174 |
+
t_start = time.time()
|
| 175 |
+
ds = ds.map(preprocess, num_proc=args.num_workers)
|
| 176 |
+
print(f"Time to preprocess dataset: {time.time()-t_start:.2f}")
|
| 177 |
+
|
| 178 |
+
# Deduplicate hashes
|
| 179 |
+
uniques = set(ds.unique("hash"))
|
| 180 |
+
frac = len(uniques) / len(ds)
|
| 181 |
+
print(f"Fraction of duplicates: {1-frac:.2%}")
|
| 182 |
+
|
| 183 |
+
# Deduplicate data and apply heuristics
|
| 184 |
+
t_start = time.time()
|
| 185 |
+
ds_filter = ds.filter(filter, fn_kwargs={"uniques": uniques, "args": args})
|
| 186 |
+
print(f"Time to filter dataset: {time.time()-t_start:.2f}")
|
| 187 |
+
print(f"Size of filtered dataset: {len(ds_filter)}")
|
| 188 |
+
|
| 189 |
+
# Deduplicate with minhash and jaccard similarity
|
| 190 |
+
if args.near_deduplication:
|
| 191 |
+
t_start = time.time()
|
| 192 |
+
ds_filter, duplicate_clusters = deduplicate_dataset(ds_filter, args.jaccard_threshold)
|
| 193 |
+
print(f"Time to deduplicate dataset: {time.time()-t_start:.2f}")
|
| 194 |
+
print(f"Size of deduplicate dataset: {len(ds_filter)}")
|
| 195 |
+
|
| 196 |
+
# Save data in batches of samples_per_file
|
| 197 |
+
output_dir = Path(args.output_dir)
|
| 198 |
+
output_dir.mkdir(exist_ok=True)
|
| 199 |
+
|
| 200 |
+
# save duplicate_clusters in the output_dir as artifacts
|
| 201 |
+
# not sure it is the right place the save it
|
| 202 |
+
if args.near_deduplication:
|
| 203 |
+
with open(output_dir / "duplicate_clusters.json", "w") as f:
|
| 204 |
+
json.dump(duplicate_clusters, f)
|
| 205 |
+
|
| 206 |
+
data_dir = output_dir / "data"
|
| 207 |
+
data_dir.mkdir(exist_ok=True)
|
| 208 |
+
|
| 209 |
+
t_start = time.time()
|
| 210 |
+
for file_number, index in enumerate(range(0, len(ds_filter), args.samples_per_file)):
|
| 211 |
+
file_path = str(data_dir / f"file-{file_number+1:012}.json")
|
| 212 |
+
end_index = min(len(ds_filter), index + args.samples_per_file)
|
| 213 |
+
ds_filter.select(list(range(index, end_index))).to_json(file_path)
|
| 214 |
+
compress_file(file_path)
|
| 215 |
+
print(f"Time to save dataset: {time.time()-t_start:.2f}")
|
tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/codeparrot/scripts/pretokenizing.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import multiprocessing
|
| 2 |
+
import time
|
| 3 |
+
|
| 4 |
+
from arguments import PretokenizationArguments
|
| 5 |
+
from datasets import load_dataset
|
| 6 |
+
|
| 7 |
+
from transformers import AutoTokenizer, HfArgumentParser
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def tokenize(example):
|
| 11 |
+
output = {}
|
| 12 |
+
output["input_ids"] = tokenizer(example["content"], truncation=False)["input_ids"]
|
| 13 |
+
output["ratio_char_token"] = len(example["content"]) / len(output["input_ids"])
|
| 14 |
+
return output
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
parser = HfArgumentParser(PretokenizationArguments)
|
| 18 |
+
args = parser.parse_args()
|
| 19 |
+
if args.num_workers is None:
|
| 20 |
+
args.num_workers = multiprocessing.cpu_count()
|
| 21 |
+
tokenizer = AutoTokenizer.from_pretrained(args.tokenizer_dir)
|
| 22 |
+
|
| 23 |
+
t_start = time.time()
|
| 24 |
+
ds = load_dataset(args.dataset_name, split="train")
|
| 25 |
+
print(f"Dataset loaded in {time.time()-t_start:.2f}s")
|
| 26 |
+
|
| 27 |
+
t_start = time.time()
|
| 28 |
+
ds = ds.map(
|
| 29 |
+
tokenize,
|
| 30 |
+
num_proc=args.num_workers,
|
| 31 |
+
remove_columns=[
|
| 32 |
+
"repo_name",
|
| 33 |
+
"path",
|
| 34 |
+
"copies",
|
| 35 |
+
"size",
|
| 36 |
+
"content",
|
| 37 |
+
"license",
|
| 38 |
+
"hash",
|
| 39 |
+
"line_mean",
|
| 40 |
+
"line_max",
|
| 41 |
+
"alpha_frac",
|
| 42 |
+
"autogenerated",
|
| 43 |
+
],
|
| 44 |
+
)
|
| 45 |
+
print(f"Dataset tokenized in {time.time()-t_start:.2f}s")
|
| 46 |
+
|
| 47 |
+
t_start = time.time()
|
| 48 |
+
ds.push_to_hub(args.tokenized_data_repo)
|
| 49 |
+
print(f"Data pushed to the hub in {time.time()-t_start:.2f}s")
|
tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/codeparrot/scripts/tests/__init__.py
ADDED
|
File without changes
|
tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/codeparrot/scripts/tests/test_deduplicate.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from unittest import TestCase
|
| 2 |
+
|
| 3 |
+
from datasets import Dataset
|
| 4 |
+
from minhash_deduplication import deduplicate_dataset, make_duplicate_clusters
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def get_dataset():
|
| 8 |
+
data_dict = {
|
| 9 |
+
"repo_name": ["test_repo1", "test_repo2", "test_repo3"],
|
| 10 |
+
"path": ["test_1.py", "test_2.py", "unit_test.py"],
|
| 11 |
+
"content": ["a " * 20, "a " * 30, "b " * 7],
|
| 12 |
+
}
|
| 13 |
+
dataset = Dataset.from_dict(data_dict)
|
| 14 |
+
return dataset
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class MakeDuplicateClustersTest(TestCase):
|
| 18 |
+
def test_make_duplicate_clusters(self):
|
| 19 |
+
ds = get_dataset()
|
| 20 |
+
duplicate_clusters = make_duplicate_clusters(ds, 0.85)
|
| 21 |
+
self.assertEqual(len(duplicate_clusters[0]), 2)
|
| 22 |
+
|
| 23 |
+
def test_deduplicate_dataset(self):
|
| 24 |
+
ds = get_dataset()
|
| 25 |
+
ds_filter, duplicate_clusters = deduplicate_dataset(ds)
|
| 26 |
+
self.assertEqual(len(ds_filter), 2)
|
| 27 |
+
print(duplicate_clusters)
|
| 28 |
+
self.assertEqual(duplicate_clusters[0][0]["copies"], 2)
|
| 29 |
+
self.assertEqual(duplicate_clusters[0][0]["is_extreme"], True)
|
tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/codeparrot/scripts/validation_loss.py
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
from accelerate import Accelerator
|
| 5 |
+
from arguments import EvaluationArguments
|
| 6 |
+
from datasets import load_dataset
|
| 7 |
+
from torch.utils.data import IterableDataset
|
| 8 |
+
from torch.utils.data.dataloader import DataLoader
|
| 9 |
+
|
| 10 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, HfArgumentParser, set_seed
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class ConstantLengthDataset(IterableDataset):
|
| 14 |
+
def __init__(self, tokenizer, dataset, seq_length=1024, num_of_sequences=1024, chars_per_token=3.6):
|
| 15 |
+
self.tokenizer = tokenizer
|
| 16 |
+
self.concat_token_id = tokenizer.bos_token_id
|
| 17 |
+
self.dataset = dataset
|
| 18 |
+
self.seq_length = seq_length
|
| 19 |
+
self.input_characters = seq_length * chars_per_token * num_of_sequences
|
| 20 |
+
|
| 21 |
+
def __iter__(self):
|
| 22 |
+
iterator = iter(self.dataset)
|
| 23 |
+
more_examples = True
|
| 24 |
+
while more_examples:
|
| 25 |
+
buffer, buffer_len = [], 0
|
| 26 |
+
while True:
|
| 27 |
+
if buffer_len >= self.input_characters:
|
| 28 |
+
break
|
| 29 |
+
try:
|
| 30 |
+
buffer.append(next(iterator)["content"])
|
| 31 |
+
buffer_len += len(buffer[-1])
|
| 32 |
+
except StopIteration:
|
| 33 |
+
more_examples = False
|
| 34 |
+
break
|
| 35 |
+
tokenized_inputs = tokenizer(buffer, truncation=False)["input_ids"]
|
| 36 |
+
all_token_ids = []
|
| 37 |
+
for tokenized_input in tokenized_inputs:
|
| 38 |
+
all_token_ids.extend(tokenized_input + [self.concat_token_id])
|
| 39 |
+
for i in range(0, len(all_token_ids), self.seq_length):
|
| 40 |
+
input_ids = all_token_ids[i : i + self.seq_length]
|
| 41 |
+
if len(input_ids) == self.seq_length:
|
| 42 |
+
yield torch.tensor(input_ids)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def create_dataloader(args):
|
| 46 |
+
ds_kwargs = {"streaming": True}
|
| 47 |
+
valid_data = load_dataset(args.dataset_name, split="train", **ds_kwargs)
|
| 48 |
+
valid_dataset = ConstantLengthDataset(tokenizer, valid_data, seq_length=args.seq_length)
|
| 49 |
+
eval_dataloader = DataLoader(valid_dataset, batch_size=args.batch_size)
|
| 50 |
+
return eval_dataloader
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def evaluate(args):
|
| 54 |
+
model.eval()
|
| 55 |
+
losses = []
|
| 56 |
+
for step, batch in enumerate(eval_dataloader):
|
| 57 |
+
with torch.no_grad():
|
| 58 |
+
outputs = model(batch, labels=batch)
|
| 59 |
+
loss = outputs.loss.repeat(args.batch_size)
|
| 60 |
+
losses.append(accelerator.gather(loss))
|
| 61 |
+
|
| 62 |
+
if args.max_eval_steps > 0 and step >= args.max_eval_steps:
|
| 63 |
+
break
|
| 64 |
+
loss = torch.mean(torch.cat(losses))
|
| 65 |
+
try:
|
| 66 |
+
perplexity = torch.exp(loss)
|
| 67 |
+
except OverflowError:
|
| 68 |
+
perplexity = float("inf")
|
| 69 |
+
return loss.item(), perplexity.item()
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
# Setup Accelerator
|
| 73 |
+
accelerator = Accelerator()
|
| 74 |
+
|
| 75 |
+
# Parse configuration
|
| 76 |
+
parser = HfArgumentParser(EvaluationArguments)
|
| 77 |
+
args = parser.parse_args()
|
| 78 |
+
set_seed(args.seed)
|
| 79 |
+
|
| 80 |
+
# Logging
|
| 81 |
+
logger = logging.getLogger(__name__)
|
| 82 |
+
logging.basicConfig(
|
| 83 |
+
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", level=logging.INFO
|
| 84 |
+
)
|
| 85 |
+
|
| 86 |
+
# Load model and tokenizer
|
| 87 |
+
model = AutoModelForCausalLM.from_pretrained(args.model_ckpt)
|
| 88 |
+
tokenizer = AutoTokenizer.from_pretrained(args.model_ckpt)
|
| 89 |
+
|
| 90 |
+
# Load dataset and dataloader
|
| 91 |
+
eval_dataloader = create_dataloader(args)
|
| 92 |
+
|
| 93 |
+
# Prepare everything with our `accelerator`.
|
| 94 |
+
model, eval_dataloader = accelerator.prepare(model, eval_dataloader)
|
| 95 |
+
|
| 96 |
+
# Evaluate and save the last checkpoint
|
| 97 |
+
logger.info("Evaluating and saving model after training")
|
| 98 |
+
eval_loss, perplexity = evaluate(args)
|
| 99 |
+
logger.info(f"loss/eval: {eval_loss}, perplexity: {perplexity}")
|
tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/decision_transformer/requirements.txt
ADDED
|
@@ -0,0 +1,240 @@
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
absl-py==1.0.0
|
| 2 |
+
aiohttp==3.10.11
|
| 3 |
+
aiosignal==1.2.0
|
| 4 |
+
alembic==1.7.7
|
| 5 |
+
appdirs==1.4.4
|
| 6 |
+
APScheduler==3.9.1
|
| 7 |
+
arrow==1.2.2
|
| 8 |
+
asttokens==2.0.5
|
| 9 |
+
astunparse==1.6.3
|
| 10 |
+
async-timeout==4.0.2
|
| 11 |
+
attrs==21.4.0
|
| 12 |
+
audioread==2.1.9
|
| 13 |
+
autopage==0.5.0
|
| 14 |
+
backcall==0.2.0
|
| 15 |
+
backoff==1.11.1
|
| 16 |
+
backports.zoneinfo==0.2.1
|
| 17 |
+
binaryornot==0.4.4
|
| 18 |
+
black==24.3.0
|
| 19 |
+
boto3==1.16.34
|
| 20 |
+
botocore==1.19.63
|
| 21 |
+
Brotli==1.0.9
|
| 22 |
+
cachetools==5.0.0
|
| 23 |
+
certifi==2024.7.4
|
| 24 |
+
cffi==1.15.0
|
| 25 |
+
chardet==4.0.0
|
| 26 |
+
charset-normalizer==2.0.12
|
| 27 |
+
chex==0.1.1
|
| 28 |
+
click==8.0.4
|
| 29 |
+
cliff==3.10.1
|
| 30 |
+
clldutils==3.11.1
|
| 31 |
+
cloudpickle==2.0.0
|
| 32 |
+
cmaes==0.8.2
|
| 33 |
+
cmd2==2.4.0
|
| 34 |
+
codecarbon==1.2.0
|
| 35 |
+
colorlog==6.6.0
|
| 36 |
+
cookiecutter==2.1.1
|
| 37 |
+
cryptography==44.0.1
|
| 38 |
+
csvw==2.0.0
|
| 39 |
+
cycler==0.11.0
|
| 40 |
+
Cython==0.29.28
|
| 41 |
+
dash==2.15.0
|
| 42 |
+
dash-bootstrap-components==1.0.3
|
| 43 |
+
dash-core-components==2.0.0
|
| 44 |
+
dash-html-components==2.0.0
|
| 45 |
+
dash-table==5.0.0
|
| 46 |
+
datasets==2.0.0
|
| 47 |
+
decorator==5.1.1
|
| 48 |
+
Deprecated==1.2.13
|
| 49 |
+
dill==0.3.4
|
| 50 |
+
dlinfo==1.2.1
|
| 51 |
+
dm-tree==0.1.6
|
| 52 |
+
docker==4.4.4
|
| 53 |
+
execnet==1.9.0
|
| 54 |
+
executing==0.8.3
|
| 55 |
+
faiss-cpu==1.7.2
|
| 56 |
+
fasteners==0.17.3
|
| 57 |
+
filelock==3.6.0
|
| 58 |
+
fire==0.4.0
|
| 59 |
+
flake8==4.0.1
|
| 60 |
+
Flask==2.3.2
|
| 61 |
+
Flask-Compress==1.11
|
| 62 |
+
flatbuffers==2.0
|
| 63 |
+
flax==0.4.0
|
| 64 |
+
fonttools==4.43.0
|
| 65 |
+
frozenlist==1.3.0
|
| 66 |
+
fsspec==2022.2.0
|
| 67 |
+
fugashi==1.1.2
|
| 68 |
+
gast==0.5.3
|
| 69 |
+
gitdb==4.0.9
|
| 70 |
+
GitPython==3.1.41
|
| 71 |
+
glfw==2.5.1
|
| 72 |
+
google-auth==2.6.2
|
| 73 |
+
google-auth-oauthlib==0.4.6
|
| 74 |
+
google-pasta==0.2.0
|
| 75 |
+
greenlet==1.1.2
|
| 76 |
+
grpcio==1.53.2
|
| 77 |
+
gym==0.23.1
|
| 78 |
+
gym-notices==0.0.6
|
| 79 |
+
h5py==3.6.0
|
| 80 |
+
huggingface-hub==0.4.0
|
| 81 |
+
hypothesis==6.39.4
|
| 82 |
+
idna==3.7
|
| 83 |
+
imageio==2.16.1
|
| 84 |
+
importlib-metadata==4.11.3
|
| 85 |
+
importlib-resources==5.4.0
|
| 86 |
+
iniconfig==1.1.1
|
| 87 |
+
ipadic==1.0.0
|
| 88 |
+
ipython==8.10.0
|
| 89 |
+
isodate==0.6.1
|
| 90 |
+
isort==5.10.1
|
| 91 |
+
itsdangerous==2.1.1
|
| 92 |
+
jax==0.3.4
|
| 93 |
+
jaxlib==0.3.2
|
| 94 |
+
jedi==0.18.1
|
| 95 |
+
Jinja2==3.1.5
|
| 96 |
+
jinja2-time==0.2.0
|
| 97 |
+
jmespath==0.10.0
|
| 98 |
+
joblib==1.2.0
|
| 99 |
+
jsonschema==4.4.0
|
| 100 |
+
keras==2.13.1
|
| 101 |
+
Keras-Preprocessing==1.1.2
|
| 102 |
+
kiwisolver==1.4.0
|
| 103 |
+
kubernetes==12.0.1
|
| 104 |
+
libclang==13.0.0
|
| 105 |
+
librosa==0.9.1
|
| 106 |
+
llvmlite==0.38.0
|
| 107 |
+
Mako==1.2.2
|
| 108 |
+
Markdown==3.3.6
|
| 109 |
+
MarkupSafe==1.1.1
|
| 110 |
+
matplotlib==3.5.1
|
| 111 |
+
matplotlib-inline==0.1.3
|
| 112 |
+
mccabe==0.6.1
|
| 113 |
+
msgpack==1.0.3
|
| 114 |
+
mujoco-py==2.1.2.14
|
| 115 |
+
multidict==6.0.2
|
| 116 |
+
multiprocess==0.70.12.2
|
| 117 |
+
mypy-extensions==0.4.3
|
| 118 |
+
nltk==3.9
|
| 119 |
+
numba==0.55.1
|
| 120 |
+
numpy==1.22.3
|
| 121 |
+
oauthlib==3.2.2
|
| 122 |
+
onnx>=1.15.0
|
| 123 |
+
onnxconverter-common==1.9.0
|
| 124 |
+
opt-einsum==3.3.0
|
| 125 |
+
optax==0.1.1
|
| 126 |
+
optuna==2.10.0
|
| 127 |
+
packaging==21.3
|
| 128 |
+
pandas==1.4.1
|
| 129 |
+
parameterized==0.8.1
|
| 130 |
+
parso==0.8.3
|
| 131 |
+
pathspec==0.9.0
|
| 132 |
+
pbr==5.8.1
|
| 133 |
+
pexpect==4.8.0
|
| 134 |
+
phonemizer==3.0.1
|
| 135 |
+
pickleshare==0.7.5
|
| 136 |
+
Pillow==10.3.0
|
| 137 |
+
Pint==0.16.1
|
| 138 |
+
plac==1.3.4
|
| 139 |
+
platformdirs==2.5.1
|
| 140 |
+
plotly==5.6.0
|
| 141 |
+
pluggy==1.0.0
|
| 142 |
+
pooch==1.6.0
|
| 143 |
+
portalocker==2.0.0
|
| 144 |
+
poyo==0.5.0
|
| 145 |
+
prettytable==3.2.0
|
| 146 |
+
prompt-toolkit==3.0.28
|
| 147 |
+
protobuf==3.19.5
|
| 148 |
+
psutil==5.9.0
|
| 149 |
+
ptyprocess==0.7.0
|
| 150 |
+
pure-eval==0.2.2
|
| 151 |
+
py==1.11.0
|
| 152 |
+
py-cpuinfo==8.0.0
|
| 153 |
+
pyarrow==15.0.0
|
| 154 |
+
pyasn1==0.4.8
|
| 155 |
+
pyasn1-modules==0.2.8
|
| 156 |
+
pycodestyle==2.8.0
|
| 157 |
+
pycparser==2.21
|
| 158 |
+
pyctcdecode==0.3.0
|
| 159 |
+
pyflakes==2.4.0
|
| 160 |
+
Pygments==2.15.0
|
| 161 |
+
pygtrie==2.4.2
|
| 162 |
+
pynvml==11.4.1
|
| 163 |
+
pyOpenSSL==22.0.0
|
| 164 |
+
pyparsing==3.0.7
|
| 165 |
+
pyperclip==1.8.2
|
| 166 |
+
pypng==0.0.21
|
| 167 |
+
pyrsistent==0.18.1
|
| 168 |
+
pytest==7.1.1
|
| 169 |
+
pytest-forked==1.4.0
|
| 170 |
+
pytest-timeout==2.1.0
|
| 171 |
+
pytest-xdist==2.5.0
|
| 172 |
+
python-dateutil==2.8.2
|
| 173 |
+
python-slugify==6.1.1
|
| 174 |
+
pytz==2022.1
|
| 175 |
+
pytz-deprecation-shim==0.1.0.post0
|
| 176 |
+
PyYAML==6.0
|
| 177 |
+
ray>2.6.3
|
| 178 |
+
redis==4.5.4
|
| 179 |
+
regex==2022.3.15
|
| 180 |
+
requests==2.32.0
|
| 181 |
+
requests-oauthlib==1.3.1
|
| 182 |
+
resampy==0.2.2
|
| 183 |
+
responses==0.18.0
|
| 184 |
+
rfc3986==1.5.0
|
| 185 |
+
rouge-score==0.0.4
|
| 186 |
+
rsa==4.8
|
| 187 |
+
s3transfer==0.3.7
|
| 188 |
+
sacrebleu==1.5.1
|
| 189 |
+
sacremoses==0.0.49
|
| 190 |
+
scikit-learn==1.5.0
|
| 191 |
+
scipy==1.8.0
|
| 192 |
+
segments==2.2.0
|
| 193 |
+
sentencepiece==0.1.96
|
| 194 |
+
sigopt==8.2.0
|
| 195 |
+
six==1.16.0
|
| 196 |
+
smmap==5.0.0
|
| 197 |
+
sortedcontainers==2.4.0
|
| 198 |
+
SoundFile==0.10.3.post1
|
| 199 |
+
SQLAlchemy==1.4.32
|
| 200 |
+
stack-data==0.2.0
|
| 201 |
+
stevedore==3.5.0
|
| 202 |
+
tabulate==0.8.9
|
| 203 |
+
tenacity==8.0.1
|
| 204 |
+
tensorboard==2.8.0
|
| 205 |
+
tensorboard-data-server==0.6.1
|
| 206 |
+
tensorboard-plugin-wit==1.8.1
|
| 207 |
+
tensorboardX==2.5
|
| 208 |
+
tensorflow==2.12.1
|
| 209 |
+
tensorflow-io-gcs-filesystem==0.24.0
|
| 210 |
+
termcolor==1.1.0
|
| 211 |
+
text-unidecode==1.3
|
| 212 |
+
tf-estimator-nightly==2.8.0.dev2021122109
|
| 213 |
+
tf2onnx==1.9.3
|
| 214 |
+
threadpoolctl==3.1.0
|
| 215 |
+
timeout-decorator==0.5.0
|
| 216 |
+
timm==0.5.4
|
| 217 |
+
tokenizers==0.11.6
|
| 218 |
+
tomli==2.0.1
|
| 219 |
+
toolz==0.11.2
|
| 220 |
+
torch==2.2.0
|
| 221 |
+
torchaudio==0.11.0
|
| 222 |
+
torchvision==0.12.0
|
| 223 |
+
tqdm==4.66.3
|
| 224 |
+
traitlets==5.1.1
|
| 225 |
+
-e git+git@github.com:edbeeching/transformers.git@77b90113ca0a0e4058b046796c874bdc98f1da61#egg=transformers
|
| 226 |
+
typing-extensions==4.1.1
|
| 227 |
+
tzdata==2022.1
|
| 228 |
+
tzlocal==4.1
|
| 229 |
+
unidic==1.1.0
|
| 230 |
+
unidic-lite==1.0.8
|
| 231 |
+
uritemplate==4.1.1
|
| 232 |
+
urllib3==1.26.19
|
| 233 |
+
wasabi==0.9.0
|
| 234 |
+
wcwidth==0.2.5
|
| 235 |
+
websocket-client==1.3.1
|
| 236 |
+
Werkzeug==3.0.6
|
| 237 |
+
wrapt==1.14.0
|
| 238 |
+
xxhash==3.0.0
|
| 239 |
+
yarl==1.7.2
|
| 240 |
+
zipp==3.19.1
|
tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/decision_transformer/run_decision_transformer.py
ADDED
|
@@ -0,0 +1,173 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gym
|
| 2 |
+
import numpy as np
|
| 3 |
+
import torch
|
| 4 |
+
from mujoco_py import GlfwContext
|
| 5 |
+
|
| 6 |
+
from transformers import DecisionTransformerModel
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
GlfwContext(offscreen=True) # Create a window to init GLFW.
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def get_action(model, states, actions, rewards, returns_to_go, timesteps):
|
| 13 |
+
# we don't care about the past rewards in this model
|
| 14 |
+
|
| 15 |
+
states = states.reshape(1, -1, model.config.state_dim)
|
| 16 |
+
actions = actions.reshape(1, -1, model.config.act_dim)
|
| 17 |
+
returns_to_go = returns_to_go.reshape(1, -1, 1)
|
| 18 |
+
timesteps = timesteps.reshape(1, -1)
|
| 19 |
+
|
| 20 |
+
if model.config.max_length is not None:
|
| 21 |
+
states = states[:, -model.config.max_length :]
|
| 22 |
+
actions = actions[:, -model.config.max_length :]
|
| 23 |
+
returns_to_go = returns_to_go[:, -model.config.max_length :]
|
| 24 |
+
timesteps = timesteps[:, -model.config.max_length :]
|
| 25 |
+
|
| 26 |
+
# pad all tokens to sequence length
|
| 27 |
+
attention_mask = torch.cat(
|
| 28 |
+
[torch.zeros(model.config.max_length - states.shape[1]), torch.ones(states.shape[1])]
|
| 29 |
+
)
|
| 30 |
+
attention_mask = attention_mask.to(dtype=torch.long, device=states.device).reshape(1, -1)
|
| 31 |
+
states = torch.cat(
|
| 32 |
+
[
|
| 33 |
+
torch.zeros(
|
| 34 |
+
(states.shape[0], model.config.max_length - states.shape[1], model.config.state_dim),
|
| 35 |
+
device=states.device,
|
| 36 |
+
),
|
| 37 |
+
states,
|
| 38 |
+
],
|
| 39 |
+
dim=1,
|
| 40 |
+
).to(dtype=torch.float32)
|
| 41 |
+
actions = torch.cat(
|
| 42 |
+
[
|
| 43 |
+
torch.zeros(
|
| 44 |
+
(actions.shape[0], model.config.max_length - actions.shape[1], model.config.act_dim),
|
| 45 |
+
device=actions.device,
|
| 46 |
+
),
|
| 47 |
+
actions,
|
| 48 |
+
],
|
| 49 |
+
dim=1,
|
| 50 |
+
).to(dtype=torch.float32)
|
| 51 |
+
returns_to_go = torch.cat(
|
| 52 |
+
[
|
| 53 |
+
torch.zeros(
|
| 54 |
+
(returns_to_go.shape[0], model.config.max_length - returns_to_go.shape[1], 1),
|
| 55 |
+
device=returns_to_go.device,
|
| 56 |
+
),
|
| 57 |
+
returns_to_go,
|
| 58 |
+
],
|
| 59 |
+
dim=1,
|
| 60 |
+
).to(dtype=torch.float32)
|
| 61 |
+
timesteps = torch.cat(
|
| 62 |
+
[
|
| 63 |
+
torch.zeros(
|
| 64 |
+
(timesteps.shape[0], model.config.max_length - timesteps.shape[1]), device=timesteps.device
|
| 65 |
+
),
|
| 66 |
+
timesteps,
|
| 67 |
+
],
|
| 68 |
+
dim=1,
|
| 69 |
+
).to(dtype=torch.long)
|
| 70 |
+
else:
|
| 71 |
+
attention_mask = None
|
| 72 |
+
|
| 73 |
+
_, action_preds, _ = model(
|
| 74 |
+
states=states,
|
| 75 |
+
actions=actions,
|
| 76 |
+
rewards=rewards,
|
| 77 |
+
returns_to_go=returns_to_go,
|
| 78 |
+
timesteps=timesteps,
|
| 79 |
+
attention_mask=attention_mask,
|
| 80 |
+
return_dict=False,
|
| 81 |
+
)
|
| 82 |
+
|
| 83 |
+
return action_preds[0, -1]
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
# build the environment
|
| 87 |
+
|
| 88 |
+
env = gym.make("Hopper-v3")
|
| 89 |
+
state_dim = env.observation_space.shape[0]
|
| 90 |
+
act_dim = env.action_space.shape[0]
|
| 91 |
+
max_ep_len = 1000
|
| 92 |
+
device = "cuda"
|
| 93 |
+
scale = 1000.0 # normalization for rewards/returns
|
| 94 |
+
TARGET_RETURN = 3600 / scale # evaluation conditioning targets, 3600 is reasonable from the paper LINK
|
| 95 |
+
state_mean = np.array(
|
| 96 |
+
[
|
| 97 |
+
1.311279,
|
| 98 |
+
-0.08469521,
|
| 99 |
+
-0.5382719,
|
| 100 |
+
-0.07201576,
|
| 101 |
+
0.04932366,
|
| 102 |
+
2.1066856,
|
| 103 |
+
-0.15017354,
|
| 104 |
+
0.00878345,
|
| 105 |
+
-0.2848186,
|
| 106 |
+
-0.18540096,
|
| 107 |
+
-0.28461286,
|
| 108 |
+
]
|
| 109 |
+
)
|
| 110 |
+
state_std = np.array(
|
| 111 |
+
[
|
| 112 |
+
0.17790751,
|
| 113 |
+
0.05444621,
|
| 114 |
+
0.21297139,
|
| 115 |
+
0.14530419,
|
| 116 |
+
0.6124444,
|
| 117 |
+
0.85174465,
|
| 118 |
+
1.4515252,
|
| 119 |
+
0.6751696,
|
| 120 |
+
1.536239,
|
| 121 |
+
1.6160746,
|
| 122 |
+
5.6072536,
|
| 123 |
+
]
|
| 124 |
+
)
|
| 125 |
+
state_mean = torch.from_numpy(state_mean).to(device=device)
|
| 126 |
+
state_std = torch.from_numpy(state_std).to(device=device)
|
| 127 |
+
|
| 128 |
+
# Create the decision transformer model
|
| 129 |
+
model = DecisionTransformerModel.from_pretrained("edbeeching/decision-transformer-gym-hopper-medium")
|
| 130 |
+
model = model.to(device)
|
| 131 |
+
model.eval()
|
| 132 |
+
|
| 133 |
+
for ep in range(10):
|
| 134 |
+
episode_return, episode_length = 0, 0
|
| 135 |
+
state = env.reset()
|
| 136 |
+
target_return = torch.tensor(TARGET_RETURN, device=device, dtype=torch.float32).reshape(1, 1)
|
| 137 |
+
states = torch.from_numpy(state).reshape(1, state_dim).to(device=device, dtype=torch.float32)
|
| 138 |
+
actions = torch.zeros((0, act_dim), device=device, dtype=torch.float32)
|
| 139 |
+
rewards = torch.zeros(0, device=device, dtype=torch.float32)
|
| 140 |
+
|
| 141 |
+
timesteps = torch.tensor(0, device=device, dtype=torch.long).reshape(1, 1)
|
| 142 |
+
for t in range(max_ep_len):
|
| 143 |
+
env.render()
|
| 144 |
+
# add padding
|
| 145 |
+
actions = torch.cat([actions, torch.zeros((1, act_dim), device=device)], dim=0)
|
| 146 |
+
rewards = torch.cat([rewards, torch.zeros(1, device=device)])
|
| 147 |
+
|
| 148 |
+
action = get_action(
|
| 149 |
+
model,
|
| 150 |
+
(states.to(dtype=torch.float32) - state_mean) / state_std,
|
| 151 |
+
actions.to(dtype=torch.float32),
|
| 152 |
+
rewards.to(dtype=torch.float32),
|
| 153 |
+
target_return.to(dtype=torch.float32),
|
| 154 |
+
timesteps.to(dtype=torch.long),
|
| 155 |
+
)
|
| 156 |
+
actions[-1] = action
|
| 157 |
+
action = action.detach().cpu().numpy()
|
| 158 |
+
|
| 159 |
+
state, reward, done, _ = env.step(action)
|
| 160 |
+
|
| 161 |
+
cur_state = torch.from_numpy(state).to(device=device).reshape(1, state_dim)
|
| 162 |
+
states = torch.cat([states, cur_state], dim=0)
|
| 163 |
+
rewards[-1] = reward
|
| 164 |
+
|
| 165 |
+
pred_return = target_return[0, -1] - (reward / scale)
|
| 166 |
+
target_return = torch.cat([target_return, pred_return.reshape(1, 1)], dim=1)
|
| 167 |
+
timesteps = torch.cat([timesteps, torch.ones((1, 1), device=device, dtype=torch.long) * (t + 1)], dim=1)
|
| 168 |
+
|
| 169 |
+
episode_return += reward
|
| 170 |
+
episode_length += 1
|
| 171 |
+
|
| 172 |
+
if done:
|
| 173 |
+
break
|
tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/deebert/README.md
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# DeeBERT: Early Exiting for *BERT
|
| 2 |
+
|
| 3 |
+
This is the code base for the paper [DeeBERT: Dynamic Early Exiting for Accelerating BERT Inference](https://www.aclweb.org/anthology/2020.acl-main.204/), modified from its [original code base](https://github.com/castorini/deebert).
|
| 4 |
+
|
| 5 |
+
The original code base also has information for downloading sample models that we have trained in advance.
|
| 6 |
+
|
| 7 |
+
## Usage
|
| 8 |
+
|
| 9 |
+
There are three scripts in the folder which can be run directly.
|
| 10 |
+
|
| 11 |
+
In each script, there are several things to modify before running:
|
| 12 |
+
|
| 13 |
+
* `PATH_TO_DATA`: path to the GLUE dataset.
|
| 14 |
+
* `--output_dir`: path for saving fine-tuned models. Default: `./saved_models`.
|
| 15 |
+
* `--plot_data_dir`: path for saving evaluation results. Default: `./results`. Results are printed to stdout and also saved to `npy` files in this directory to facilitate plotting figures and further analyses.
|
| 16 |
+
* `MODEL_TYPE`: bert or roberta
|
| 17 |
+
* `MODEL_SIZE`: base or large
|
| 18 |
+
* `DATASET`: SST-2, MRPC, RTE, QNLI, QQP, or MNLI
|
| 19 |
+
|
| 20 |
+
#### train_deebert.sh
|
| 21 |
+
|
| 22 |
+
This is for fine-tuning DeeBERT models.
|
| 23 |
+
|
| 24 |
+
#### eval_deebert.sh
|
| 25 |
+
|
| 26 |
+
This is for evaluating each exit layer for fine-tuned DeeBERT models.
|
| 27 |
+
|
| 28 |
+
#### entropy_eval.sh
|
| 29 |
+
|
| 30 |
+
This is for evaluating fine-tuned DeeBERT models, given a number of different early exit entropy thresholds.
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
## Citation
|
| 35 |
+
|
| 36 |
+
Please cite our paper if you find the resource useful:
|
| 37 |
+
```bibtex
|
| 38 |
+
@inproceedings{xin-etal-2020-deebert,
|
| 39 |
+
title = "{D}ee{BERT}: Dynamic Early Exiting for Accelerating {BERT} Inference",
|
| 40 |
+
author = "Xin, Ji and
|
| 41 |
+
Tang, Raphael and
|
| 42 |
+
Lee, Jaejun and
|
| 43 |
+
Yu, Yaoliang and
|
| 44 |
+
Lin, Jimmy",
|
| 45 |
+
booktitle = "Proceedings of the 58th Annual Meeting of the Association for Computational Linguistics",
|
| 46 |
+
month = jul,
|
| 47 |
+
year = "2020",
|
| 48 |
+
address = "Online",
|
| 49 |
+
publisher = "Association for Computational Linguistics",
|
| 50 |
+
url = "https://www.aclweb.org/anthology/2020.acl-main.204",
|
| 51 |
+
pages = "2246--2251",
|
| 52 |
+
}
|
| 53 |
+
```
|
| 54 |
+
|
tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/deebert/entropy_eval.sh
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
export CUDA_VISIBLE_DEVICES=0
|
| 3 |
+
|
| 4 |
+
PATH_TO_DATA=/h/xinji/projects/GLUE
|
| 5 |
+
|
| 6 |
+
MODEL_TYPE=bert # bert or roberta
|
| 7 |
+
MODEL_SIZE=base # base or large
|
| 8 |
+
DATASET=MRPC # SST-2, MRPC, RTE, QNLI, QQP, or MNLI
|
| 9 |
+
|
| 10 |
+
MODEL_NAME=${MODEL_TYPE}-${MODEL_SIZE}
|
| 11 |
+
if [ $MODEL_TYPE = 'bert' ]
|
| 12 |
+
then
|
| 13 |
+
MODEL_NAME=${MODEL_NAME}-uncased
|
| 14 |
+
fi
|
| 15 |
+
|
| 16 |
+
ENTROPIES="0 0.1 0.2 0.3 0.4 0.5 0.6 0.7"
|
| 17 |
+
|
| 18 |
+
for ENTROPY in $ENTROPIES; do
|
| 19 |
+
python -u run_glue_deebert.py \
|
| 20 |
+
--model_type $MODEL_TYPE \
|
| 21 |
+
--model_name_or_path ./saved_models/${MODEL_TYPE}-${MODEL_SIZE}/$DATASET/two_stage \
|
| 22 |
+
--task_name $DATASET \
|
| 23 |
+
--do_eval \
|
| 24 |
+
--do_lower_case \
|
| 25 |
+
--data_dir $PATH_TO_DATA/$DATASET \
|
| 26 |
+
--output_dir ./saved_models/${MODEL_TYPE}-${MODEL_SIZE}/$DATASET/two_stage \
|
| 27 |
+
--plot_data_dir ./results/ \
|
| 28 |
+
--max_seq_length 128 \
|
| 29 |
+
--early_exit_entropy $ENTROPY \
|
| 30 |
+
--eval_highway \
|
| 31 |
+
--overwrite_cache \
|
| 32 |
+
--per_gpu_eval_batch_size=1
|
| 33 |
+
done
|
tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/deebert/eval_deebert.sh
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
export CUDA_VISIBLE_DEVICES=0
|
| 3 |
+
|
| 4 |
+
PATH_TO_DATA=/h/xinji/projects/GLUE
|
| 5 |
+
|
| 6 |
+
MODEL_TYPE=bert # bert or roberta
|
| 7 |
+
MODEL_SIZE=base # base or large
|
| 8 |
+
DATASET=MRPC # SST-2, MRPC, RTE, QNLI, QQP, or MNLI
|
| 9 |
+
|
| 10 |
+
MODEL_NAME=${MODEL_TYPE}-${MODEL_SIZE}
|
| 11 |
+
if [ $MODEL_TYPE = 'bert' ]
|
| 12 |
+
then
|
| 13 |
+
MODEL_NAME=${MODEL_NAME}-uncased
|
| 14 |
+
fi
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
python -u run_glue_deebert.py \
|
| 18 |
+
--model_type $MODEL_TYPE \
|
| 19 |
+
--model_name_or_path ./saved_models/${MODEL_TYPE}-${MODEL_SIZE}/$DATASET/two_stage \
|
| 20 |
+
--task_name $DATASET \
|
| 21 |
+
--do_eval \
|
| 22 |
+
--do_lower_case \
|
| 23 |
+
--data_dir $PATH_TO_DATA/$DATASET \
|
| 24 |
+
--output_dir ./saved_models/${MODEL_TYPE}-${MODEL_SIZE}/$DATASET/two_stage \
|
| 25 |
+
--plot_data_dir ./results/ \
|
| 26 |
+
--max_seq_length 128 \
|
| 27 |
+
--eval_each_highway \
|
| 28 |
+
--eval_highway \
|
| 29 |
+
--overwrite_cache \
|
| 30 |
+
--per_gpu_eval_batch_size=1
|
tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/deebert/requirements.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
transformers == 4.38.0
|
tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/deebert/run_glue_deebert.py
ADDED
|
@@ -0,0 +1,735 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import absolute_import, division, print_function
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import glob
|
| 5 |
+
import logging
|
| 6 |
+
import os
|
| 7 |
+
import random
|
| 8 |
+
import time
|
| 9 |
+
|
| 10 |
+
import numpy as np
|
| 11 |
+
import torch
|
| 12 |
+
from torch import nn
|
| 13 |
+
from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset
|
| 14 |
+
from torch.utils.data.distributed import DistributedSampler
|
| 15 |
+
from tqdm import tqdm, trange
|
| 16 |
+
|
| 17 |
+
import transformers
|
| 18 |
+
from src.modeling_highway_bert import DeeBertForSequenceClassification
|
| 19 |
+
from src.modeling_highway_roberta import DeeRobertaForSequenceClassification
|
| 20 |
+
from transformers import (
|
| 21 |
+
WEIGHTS_NAME,
|
| 22 |
+
AdamW,
|
| 23 |
+
BertConfig,
|
| 24 |
+
BertTokenizer,
|
| 25 |
+
RobertaConfig,
|
| 26 |
+
RobertaTokenizer,
|
| 27 |
+
get_linear_schedule_with_warmup,
|
| 28 |
+
)
|
| 29 |
+
from transformers import glue_compute_metrics as compute_metrics
|
| 30 |
+
from transformers import glue_convert_examples_to_features as convert_examples_to_features
|
| 31 |
+
from transformers import glue_output_modes as output_modes
|
| 32 |
+
from transformers import glue_processors as processors
|
| 33 |
+
from transformers.trainer_utils import is_main_process
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
try:
|
| 37 |
+
from torch.utils.tensorboard import SummaryWriter
|
| 38 |
+
except ImportError:
|
| 39 |
+
from tensorboardX import SummaryWriter
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
logger = logging.getLogger(__name__)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
MODEL_CLASSES = {
|
| 46 |
+
"bert": (BertConfig, DeeBertForSequenceClassification, BertTokenizer),
|
| 47 |
+
"roberta": (RobertaConfig, DeeRobertaForSequenceClassification, RobertaTokenizer),
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def set_seed(args):
|
| 52 |
+
random.seed(args.seed)
|
| 53 |
+
np.random.seed(args.seed)
|
| 54 |
+
torch.manual_seed(args.seed)
|
| 55 |
+
if args.n_gpu > 0:
|
| 56 |
+
torch.cuda.manual_seed_all(args.seed)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def get_wanted_result(result):
|
| 60 |
+
if "spearmanr" in result:
|
| 61 |
+
print_result = result["spearmanr"]
|
| 62 |
+
elif "f1" in result:
|
| 63 |
+
print_result = result["f1"]
|
| 64 |
+
elif "mcc" in result:
|
| 65 |
+
print_result = result["mcc"]
|
| 66 |
+
elif "acc" in result:
|
| 67 |
+
print_result = result["acc"]
|
| 68 |
+
else:
|
| 69 |
+
raise ValueError("Primary metric unclear in the results")
|
| 70 |
+
return print_result
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def train(args, train_dataset, model, tokenizer, train_highway=False):
|
| 74 |
+
"""Train the model"""
|
| 75 |
+
if args.local_rank in [-1, 0]:
|
| 76 |
+
tb_writer = SummaryWriter()
|
| 77 |
+
|
| 78 |
+
args.train_batch_size = args.per_gpu_train_batch_size * max(1, args.n_gpu)
|
| 79 |
+
train_sampler = RandomSampler(train_dataset) if args.local_rank == -1 else DistributedSampler(train_dataset)
|
| 80 |
+
train_dataloader = DataLoader(train_dataset, sampler=train_sampler, batch_size=args.train_batch_size)
|
| 81 |
+
|
| 82 |
+
if args.max_steps > 0:
|
| 83 |
+
t_total = args.max_steps
|
| 84 |
+
args.num_train_epochs = args.max_steps // (len(train_dataloader) // args.gradient_accumulation_steps) + 1
|
| 85 |
+
else:
|
| 86 |
+
t_total = len(train_dataloader) // args.gradient_accumulation_steps * args.num_train_epochs
|
| 87 |
+
|
| 88 |
+
# Prepare optimizer and schedule (linear warmup and decay)
|
| 89 |
+
no_decay = ["bias", "LayerNorm.weight"]
|
| 90 |
+
if train_highway:
|
| 91 |
+
optimizer_grouped_parameters = [
|
| 92 |
+
{
|
| 93 |
+
"params": [
|
| 94 |
+
p
|
| 95 |
+
for n, p in model.named_parameters()
|
| 96 |
+
if ("highway" in n) and (not any(nd in n for nd in no_decay))
|
| 97 |
+
],
|
| 98 |
+
"weight_decay": args.weight_decay,
|
| 99 |
+
},
|
| 100 |
+
{
|
| 101 |
+
"params": [
|
| 102 |
+
p for n, p in model.named_parameters() if ("highway" in n) and (any(nd in n for nd in no_decay))
|
| 103 |
+
],
|
| 104 |
+
"weight_decay": 0.0,
|
| 105 |
+
},
|
| 106 |
+
]
|
| 107 |
+
else:
|
| 108 |
+
optimizer_grouped_parameters = [
|
| 109 |
+
{
|
| 110 |
+
"params": [
|
| 111 |
+
p
|
| 112 |
+
for n, p in model.named_parameters()
|
| 113 |
+
if ("highway" not in n) and (not any(nd in n for nd in no_decay))
|
| 114 |
+
],
|
| 115 |
+
"weight_decay": args.weight_decay,
|
| 116 |
+
},
|
| 117 |
+
{
|
| 118 |
+
"params": [
|
| 119 |
+
p
|
| 120 |
+
for n, p in model.named_parameters()
|
| 121 |
+
if ("highway" not in n) and (any(nd in n for nd in no_decay))
|
| 122 |
+
],
|
| 123 |
+
"weight_decay": 0.0,
|
| 124 |
+
},
|
| 125 |
+
]
|
| 126 |
+
optimizer = AdamW(optimizer_grouped_parameters, lr=args.learning_rate, eps=args.adam_epsilon)
|
| 127 |
+
scheduler = get_linear_schedule_with_warmup(
|
| 128 |
+
optimizer, num_warmup_steps=args.warmup_steps, num_training_steps=t_total
|
| 129 |
+
)
|
| 130 |
+
if args.fp16:
|
| 131 |
+
try:
|
| 132 |
+
from apex import amp
|
| 133 |
+
except ImportError:
|
| 134 |
+
raise ImportError("Please install apex from https://www.github.com/nvidia/apex to use fp16 training.")
|
| 135 |
+
model, optimizer = amp.initialize(model, optimizer, opt_level=args.fp16_opt_level)
|
| 136 |
+
|
| 137 |
+
# multi-gpu training (should be after apex fp16 initialization)
|
| 138 |
+
if args.n_gpu > 1:
|
| 139 |
+
model = nn.DataParallel(model)
|
| 140 |
+
|
| 141 |
+
# Distributed training (should be after apex fp16 initialization)
|
| 142 |
+
if args.local_rank != -1:
|
| 143 |
+
model = nn.parallel.DistributedDataParallel(
|
| 144 |
+
model, device_ids=[args.local_rank], output_device=args.local_rank, find_unused_parameters=True
|
| 145 |
+
)
|
| 146 |
+
|
| 147 |
+
# Train!
|
| 148 |
+
logger.info("***** Running training *****")
|
| 149 |
+
logger.info(" Num examples = %d", len(train_dataset))
|
| 150 |
+
logger.info(" Num Epochs = %d", args.num_train_epochs)
|
| 151 |
+
logger.info(" Instantaneous batch size per GPU = %d", args.per_gpu_train_batch_size)
|
| 152 |
+
logger.info(
|
| 153 |
+
" Total train batch size (w. parallel, distributed & accumulation) = %d",
|
| 154 |
+
args.train_batch_size
|
| 155 |
+
* args.gradient_accumulation_steps
|
| 156 |
+
* (torch.distributed.get_world_size() if args.local_rank != -1 else 1),
|
| 157 |
+
)
|
| 158 |
+
logger.info(" Gradient Accumulation steps = %d", args.gradient_accumulation_steps)
|
| 159 |
+
logger.info(" Total optimization steps = %d", t_total)
|
| 160 |
+
|
| 161 |
+
global_step = 0
|
| 162 |
+
tr_loss, logging_loss = 0.0, 0.0
|
| 163 |
+
model.zero_grad()
|
| 164 |
+
train_iterator = trange(int(args.num_train_epochs), desc="Epoch", disable=args.local_rank not in [-1, 0])
|
| 165 |
+
set_seed(args) # Added here for reproducibility (even between python 2 and 3)
|
| 166 |
+
for _ in train_iterator:
|
| 167 |
+
epoch_iterator = tqdm(train_dataloader, desc="Iteration", disable=args.local_rank not in [-1, 0])
|
| 168 |
+
for step, batch in enumerate(epoch_iterator):
|
| 169 |
+
model.train()
|
| 170 |
+
batch = tuple(t.to(args.device) for t in batch)
|
| 171 |
+
inputs = {"input_ids": batch[0], "attention_mask": batch[1], "labels": batch[3]}
|
| 172 |
+
if args.model_type != "distilbert":
|
| 173 |
+
inputs["token_type_ids"] = (
|
| 174 |
+
batch[2] if args.model_type in ["bert", "xlnet"] else None
|
| 175 |
+
) # XLM, DistilBERT and RoBERTa don't use segment_ids
|
| 176 |
+
inputs["train_highway"] = train_highway
|
| 177 |
+
outputs = model(**inputs)
|
| 178 |
+
loss = outputs[0] # model outputs are always tuple in transformers (see doc)
|
| 179 |
+
|
| 180 |
+
if args.n_gpu > 1:
|
| 181 |
+
loss = loss.mean() # mean() to average on multi-gpu parallel training
|
| 182 |
+
if args.gradient_accumulation_steps > 1:
|
| 183 |
+
loss = loss / args.gradient_accumulation_steps
|
| 184 |
+
|
| 185 |
+
if args.fp16:
|
| 186 |
+
with amp.scale_loss(loss, optimizer) as scaled_loss:
|
| 187 |
+
scaled_loss.backward()
|
| 188 |
+
else:
|
| 189 |
+
loss.backward()
|
| 190 |
+
|
| 191 |
+
tr_loss += loss.item()
|
| 192 |
+
if (step + 1) % args.gradient_accumulation_steps == 0:
|
| 193 |
+
if args.fp16:
|
| 194 |
+
nn.utils.clip_grad_norm_(amp.master_params(optimizer), args.max_grad_norm)
|
| 195 |
+
else:
|
| 196 |
+
nn.utils.clip_grad_norm_(model.parameters(), args.max_grad_norm)
|
| 197 |
+
|
| 198 |
+
optimizer.step()
|
| 199 |
+
scheduler.step() # Update learning rate schedule
|
| 200 |
+
model.zero_grad()
|
| 201 |
+
global_step += 1
|
| 202 |
+
|
| 203 |
+
if args.local_rank in [-1, 0] and args.logging_steps > 0 and global_step % args.logging_steps == 0:
|
| 204 |
+
# Log metrics
|
| 205 |
+
if (
|
| 206 |
+
args.local_rank == -1 and args.evaluate_during_training
|
| 207 |
+
): # Only evaluate when single GPU otherwise metrics may not average well
|
| 208 |
+
results = evaluate(args, model, tokenizer)
|
| 209 |
+
for key, value in results.items():
|
| 210 |
+
tb_writer.add_scalar("eval_{}".format(key), value, global_step)
|
| 211 |
+
tb_writer.add_scalar("lr", scheduler.get_lr()[0], global_step)
|
| 212 |
+
tb_writer.add_scalar("loss", (tr_loss - logging_loss) / args.logging_steps, global_step)
|
| 213 |
+
logging_loss = tr_loss
|
| 214 |
+
|
| 215 |
+
if args.local_rank in [-1, 0] and args.save_steps > 0 and global_step % args.save_steps == 0:
|
| 216 |
+
# Save model checkpoint
|
| 217 |
+
output_dir = os.path.join(args.output_dir, "checkpoint-{}".format(global_step))
|
| 218 |
+
if not os.path.exists(output_dir):
|
| 219 |
+
os.makedirs(output_dir)
|
| 220 |
+
model_to_save = (
|
| 221 |
+
model.module if hasattr(model, "module") else model
|
| 222 |
+
) # Take care of distributed/parallel training
|
| 223 |
+
model_to_save.save_pretrained(output_dir)
|
| 224 |
+
torch.save(args, os.path.join(output_dir, "training_args.bin"))
|
| 225 |
+
logger.info("Saving model checkpoint to %s", output_dir)
|
| 226 |
+
|
| 227 |
+
if args.max_steps > 0 and global_step > args.max_steps:
|
| 228 |
+
epoch_iterator.close()
|
| 229 |
+
break
|
| 230 |
+
if args.max_steps > 0 and global_step > args.max_steps:
|
| 231 |
+
train_iterator.close()
|
| 232 |
+
break
|
| 233 |
+
|
| 234 |
+
if args.local_rank in [-1, 0]:
|
| 235 |
+
tb_writer.close()
|
| 236 |
+
|
| 237 |
+
return global_step, tr_loss / global_step
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
def evaluate(args, model, tokenizer, prefix="", output_layer=-1, eval_highway=False):
|
| 241 |
+
# Loop to handle MNLI double evaluation (matched, mis-matched)
|
| 242 |
+
eval_task_names = ("mnli", "mnli-mm") if args.task_name == "mnli" else (args.task_name,)
|
| 243 |
+
eval_outputs_dirs = (args.output_dir, args.output_dir + "-MM") if args.task_name == "mnli" else (args.output_dir,)
|
| 244 |
+
|
| 245 |
+
results = {}
|
| 246 |
+
for eval_task, eval_output_dir in zip(eval_task_names, eval_outputs_dirs):
|
| 247 |
+
eval_dataset = load_and_cache_examples(args, eval_task, tokenizer, evaluate=True)
|
| 248 |
+
|
| 249 |
+
if not os.path.exists(eval_output_dir) and args.local_rank in [-1, 0]:
|
| 250 |
+
os.makedirs(eval_output_dir)
|
| 251 |
+
|
| 252 |
+
args.eval_batch_size = args.per_gpu_eval_batch_size * max(1, args.n_gpu)
|
| 253 |
+
# Note that DistributedSampler samples randomly
|
| 254 |
+
eval_sampler = SequentialSampler(eval_dataset) if args.local_rank == -1 else DistributedSampler(eval_dataset)
|
| 255 |
+
eval_dataloader = DataLoader(eval_dataset, sampler=eval_sampler, batch_size=args.eval_batch_size)
|
| 256 |
+
|
| 257 |
+
# multi-gpu eval
|
| 258 |
+
if args.n_gpu > 1:
|
| 259 |
+
model = nn.DataParallel(model)
|
| 260 |
+
|
| 261 |
+
# Eval!
|
| 262 |
+
logger.info("***** Running evaluation {} *****".format(prefix))
|
| 263 |
+
logger.info(" Num examples = %d", len(eval_dataset))
|
| 264 |
+
logger.info(" Batch size = %d", args.eval_batch_size)
|
| 265 |
+
eval_loss = 0.0
|
| 266 |
+
nb_eval_steps = 0
|
| 267 |
+
preds = None
|
| 268 |
+
out_label_ids = None
|
| 269 |
+
exit_layer_counter = {(i + 1): 0 for i in range(model.num_layers)}
|
| 270 |
+
st = time.time()
|
| 271 |
+
for batch in tqdm(eval_dataloader, desc="Evaluating"):
|
| 272 |
+
model.eval()
|
| 273 |
+
batch = tuple(t.to(args.device) for t in batch)
|
| 274 |
+
|
| 275 |
+
with torch.no_grad():
|
| 276 |
+
inputs = {"input_ids": batch[0], "attention_mask": batch[1], "labels": batch[3]}
|
| 277 |
+
if args.model_type != "distilbert":
|
| 278 |
+
inputs["token_type_ids"] = (
|
| 279 |
+
batch[2] if args.model_type in ["bert", "xlnet"] else None
|
| 280 |
+
) # XLM, DistilBERT and RoBERTa don't use segment_ids
|
| 281 |
+
if output_layer >= 0:
|
| 282 |
+
inputs["output_layer"] = output_layer
|
| 283 |
+
outputs = model(**inputs)
|
| 284 |
+
if eval_highway:
|
| 285 |
+
exit_layer_counter[outputs[-1]] += 1
|
| 286 |
+
tmp_eval_loss, logits = outputs[:2]
|
| 287 |
+
|
| 288 |
+
eval_loss += tmp_eval_loss.mean().item()
|
| 289 |
+
nb_eval_steps += 1
|
| 290 |
+
if preds is None:
|
| 291 |
+
preds = logits.detach().cpu().numpy()
|
| 292 |
+
out_label_ids = inputs["labels"].detach().cpu().numpy()
|
| 293 |
+
else:
|
| 294 |
+
preds = np.append(preds, logits.detach().cpu().numpy(), axis=0)
|
| 295 |
+
out_label_ids = np.append(out_label_ids, inputs["labels"].detach().cpu().numpy(), axis=0)
|
| 296 |
+
eval_time = time.time() - st
|
| 297 |
+
logger.info("Eval time: {}".format(eval_time))
|
| 298 |
+
|
| 299 |
+
eval_loss = eval_loss / nb_eval_steps
|
| 300 |
+
if args.output_mode == "classification":
|
| 301 |
+
preds = np.argmax(preds, axis=1)
|
| 302 |
+
elif args.output_mode == "regression":
|
| 303 |
+
preds = np.squeeze(preds)
|
| 304 |
+
result = compute_metrics(eval_task, preds, out_label_ids)
|
| 305 |
+
results.update(result)
|
| 306 |
+
|
| 307 |
+
if eval_highway:
|
| 308 |
+
logger.info("Exit layer counter: {}".format(exit_layer_counter))
|
| 309 |
+
actual_cost = sum([l * c for l, c in exit_layer_counter.items()])
|
| 310 |
+
full_cost = len(eval_dataloader) * model.num_layers
|
| 311 |
+
logger.info("Expected saving: {}".format(actual_cost / full_cost))
|
| 312 |
+
if args.early_exit_entropy >= 0:
|
| 313 |
+
save_fname = (
|
| 314 |
+
args.plot_data_dir
|
| 315 |
+
+ "/"
|
| 316 |
+
+ args.model_name_or_path[2:]
|
| 317 |
+
+ "/entropy_{}.npy".format(args.early_exit_entropy)
|
| 318 |
+
)
|
| 319 |
+
if not os.path.exists(os.path.dirname(save_fname)):
|
| 320 |
+
os.makedirs(os.path.dirname(save_fname))
|
| 321 |
+
print_result = get_wanted_result(result)
|
| 322 |
+
np.save(save_fname, np.array([exit_layer_counter, eval_time, actual_cost / full_cost, print_result]))
|
| 323 |
+
logger.info("Entropy={}\tResult={:.2f}".format(args.early_exit_entropy, 100 * print_result))
|
| 324 |
+
|
| 325 |
+
output_eval_file = os.path.join(eval_output_dir, prefix, "eval_results.txt")
|
| 326 |
+
with open(output_eval_file, "w") as writer:
|
| 327 |
+
logger.info("***** Eval results {} *****".format(prefix))
|
| 328 |
+
for key in sorted(result.keys()):
|
| 329 |
+
logger.info(" %s = %s", key, str(result[key]))
|
| 330 |
+
writer.write("%s = %s\n" % (key, str(result[key])))
|
| 331 |
+
|
| 332 |
+
return results
|
| 333 |
+
|
| 334 |
+
|
| 335 |
+
def load_and_cache_examples(args, task, tokenizer, evaluate=False):
|
| 336 |
+
if args.local_rank not in [-1, 0] and not evaluate:
|
| 337 |
+
torch.distributed.barrier() # Make sure only the first process in distributed training process the dataset, and the others will use the cache
|
| 338 |
+
|
| 339 |
+
processor = processors[task]()
|
| 340 |
+
output_mode = output_modes[task]
|
| 341 |
+
# Load data features from cache or dataset file
|
| 342 |
+
cached_features_file = os.path.join(
|
| 343 |
+
args.data_dir,
|
| 344 |
+
"cached_{}_{}_{}_{}".format(
|
| 345 |
+
"dev" if evaluate else "train",
|
| 346 |
+
list(filter(None, args.model_name_or_path.split("/"))).pop(),
|
| 347 |
+
str(args.max_seq_length),
|
| 348 |
+
str(task),
|
| 349 |
+
),
|
| 350 |
+
)
|
| 351 |
+
if os.path.exists(cached_features_file) and not args.overwrite_cache:
|
| 352 |
+
logger.info("Loading features from cached file %s", cached_features_file)
|
| 353 |
+
features = torch.load(cached_features_file)
|
| 354 |
+
else:
|
| 355 |
+
logger.info("Creating features from dataset file at %s", args.data_dir)
|
| 356 |
+
label_list = processor.get_labels()
|
| 357 |
+
if task in ["mnli", "mnli-mm"] and args.model_type in ["roberta"]:
|
| 358 |
+
# HACK(label indices are swapped in RoBERTa pretrained model)
|
| 359 |
+
label_list[1], label_list[2] = label_list[2], label_list[1]
|
| 360 |
+
examples = (
|
| 361 |
+
processor.get_dev_examples(args.data_dir) if evaluate else processor.get_train_examples(args.data_dir)
|
| 362 |
+
)
|
| 363 |
+
features = convert_examples_to_features(
|
| 364 |
+
examples,
|
| 365 |
+
tokenizer,
|
| 366 |
+
label_list=label_list,
|
| 367 |
+
max_length=args.max_seq_length,
|
| 368 |
+
output_mode=output_mode,
|
| 369 |
+
)
|
| 370 |
+
if args.local_rank in [-1, 0]:
|
| 371 |
+
logger.info("Saving features into cached file %s", cached_features_file)
|
| 372 |
+
torch.save(features, cached_features_file)
|
| 373 |
+
|
| 374 |
+
if args.local_rank == 0 and not evaluate:
|
| 375 |
+
torch.distributed.barrier() # Make sure only the first process in distributed training process the dataset, and the others will use the cache
|
| 376 |
+
|
| 377 |
+
# Convert to Tensors and build dataset
|
| 378 |
+
all_input_ids = torch.tensor([f.input_ids for f in features], dtype=torch.long)
|
| 379 |
+
all_attention_mask = torch.tensor([f.attention_mask for f in features], dtype=torch.long)
|
| 380 |
+
|
| 381 |
+
if features[0].token_type_ids is None:
|
| 382 |
+
# For RoBERTa (a potential bug!)
|
| 383 |
+
all_token_type_ids = torch.tensor([[0] * args.max_seq_length for f in features], dtype=torch.long)
|
| 384 |
+
else:
|
| 385 |
+
all_token_type_ids = torch.tensor([f.token_type_ids for f in features], dtype=torch.long)
|
| 386 |
+
if output_mode == "classification":
|
| 387 |
+
all_labels = torch.tensor([f.label for f in features], dtype=torch.long)
|
| 388 |
+
elif output_mode == "regression":
|
| 389 |
+
all_labels = torch.tensor([f.label for f in features], dtype=torch.float)
|
| 390 |
+
|
| 391 |
+
dataset = TensorDataset(all_input_ids, all_attention_mask, all_token_type_ids, all_labels)
|
| 392 |
+
return dataset
|
| 393 |
+
|
| 394 |
+
|
| 395 |
+
def main():
|
| 396 |
+
parser = argparse.ArgumentParser()
|
| 397 |
+
|
| 398 |
+
# Required parameters
|
| 399 |
+
parser.add_argument(
|
| 400 |
+
"--data_dir",
|
| 401 |
+
default=None,
|
| 402 |
+
type=str,
|
| 403 |
+
required=True,
|
| 404 |
+
help="The input data dir. Should contain the .tsv files (or other data files) for the task.",
|
| 405 |
+
)
|
| 406 |
+
parser.add_argument(
|
| 407 |
+
"--model_type",
|
| 408 |
+
default=None,
|
| 409 |
+
type=str,
|
| 410 |
+
required=True,
|
| 411 |
+
help="Model type selected in the list: " + ", ".join(MODEL_CLASSES.keys()),
|
| 412 |
+
)
|
| 413 |
+
parser.add_argument(
|
| 414 |
+
"--model_name_or_path",
|
| 415 |
+
default=None,
|
| 416 |
+
type=str,
|
| 417 |
+
required=True,
|
| 418 |
+
help="Path to pre-trained model or shortcut name.",
|
| 419 |
+
)
|
| 420 |
+
parser.add_argument(
|
| 421 |
+
"--task_name",
|
| 422 |
+
default=None,
|
| 423 |
+
type=str,
|
| 424 |
+
required=True,
|
| 425 |
+
help="The name of the task to train selected in the list: " + ", ".join(processors.keys()),
|
| 426 |
+
)
|
| 427 |
+
parser.add_argument(
|
| 428 |
+
"--output_dir",
|
| 429 |
+
default=None,
|
| 430 |
+
type=str,
|
| 431 |
+
required=True,
|
| 432 |
+
help="The output directory where the model predictions and checkpoints will be written.",
|
| 433 |
+
)
|
| 434 |
+
parser.add_argument(
|
| 435 |
+
"--plot_data_dir",
|
| 436 |
+
default="./plotting/",
|
| 437 |
+
type=str,
|
| 438 |
+
required=False,
|
| 439 |
+
help="The directory to store data for plotting figures.",
|
| 440 |
+
)
|
| 441 |
+
|
| 442 |
+
# Other parameters
|
| 443 |
+
parser.add_argument(
|
| 444 |
+
"--config_name", default="", type=str, help="Pretrained config name or path if not the same as model_name"
|
| 445 |
+
)
|
| 446 |
+
parser.add_argument(
|
| 447 |
+
"--tokenizer_name",
|
| 448 |
+
default="",
|
| 449 |
+
type=str,
|
| 450 |
+
help="Pretrained tokenizer name or path if not the same as model_name",
|
| 451 |
+
)
|
| 452 |
+
parser.add_argument(
|
| 453 |
+
"--cache_dir",
|
| 454 |
+
default="",
|
| 455 |
+
type=str,
|
| 456 |
+
help="Where do you want to store the pre-trained models downloaded from huggingface.co",
|
| 457 |
+
)
|
| 458 |
+
parser.add_argument(
|
| 459 |
+
"--max_seq_length",
|
| 460 |
+
default=128,
|
| 461 |
+
type=int,
|
| 462 |
+
help=(
|
| 463 |
+
"The maximum total input sequence length after tokenization. Sequences longer "
|
| 464 |
+
"than this will be truncated, sequences shorter will be padded."
|
| 465 |
+
),
|
| 466 |
+
)
|
| 467 |
+
parser.add_argument("--do_train", action="store_true", help="Whether to run training.")
|
| 468 |
+
parser.add_argument("--do_eval", action="store_true", help="Whether to run eval on the dev set.")
|
| 469 |
+
parser.add_argument(
|
| 470 |
+
"--evaluate_during_training", action="store_true", help="Rul evaluation during training at each logging step."
|
| 471 |
+
)
|
| 472 |
+
parser.add_argument(
|
| 473 |
+
"--do_lower_case", action="store_true", help="Set this flag if you are using an uncased model."
|
| 474 |
+
)
|
| 475 |
+
parser.add_argument("--eval_each_highway", action="store_true", help="Set this flag to evaluate each highway.")
|
| 476 |
+
parser.add_argument(
|
| 477 |
+
"--eval_after_first_stage",
|
| 478 |
+
action="store_true",
|
| 479 |
+
help="Set this flag to evaluate after training only bert (not highway).",
|
| 480 |
+
)
|
| 481 |
+
parser.add_argument("--eval_highway", action="store_true", help="Set this flag if it's evaluating highway models")
|
| 482 |
+
|
| 483 |
+
parser.add_argument("--per_gpu_train_batch_size", default=8, type=int, help="Batch size per GPU/CPU for training.")
|
| 484 |
+
parser.add_argument(
|
| 485 |
+
"--per_gpu_eval_batch_size", default=8, type=int, help="Batch size per GPU/CPU for evaluation."
|
| 486 |
+
)
|
| 487 |
+
parser.add_argument(
|
| 488 |
+
"--gradient_accumulation_steps",
|
| 489 |
+
type=int,
|
| 490 |
+
default=1,
|
| 491 |
+
help="Number of updates steps to accumulate before performing a backward/update pass.",
|
| 492 |
+
)
|
| 493 |
+
parser.add_argument("--learning_rate", default=5e-5, type=float, help="The initial learning rate for Adam.")
|
| 494 |
+
parser.add_argument("--weight_decay", default=0.0, type=float, help="Weight decay if we apply some.")
|
| 495 |
+
parser.add_argument("--adam_epsilon", default=1e-8, type=float, help="Epsilon for Adam optimizer.")
|
| 496 |
+
parser.add_argument("--max_grad_norm", default=1.0, type=float, help="Max gradient norm.")
|
| 497 |
+
parser.add_argument(
|
| 498 |
+
"--num_train_epochs", default=3.0, type=float, help="Total number of training epochs to perform."
|
| 499 |
+
)
|
| 500 |
+
parser.add_argument(
|
| 501 |
+
"--max_steps",
|
| 502 |
+
default=-1,
|
| 503 |
+
type=int,
|
| 504 |
+
help="If > 0: set total number of training steps to perform. Override num_train_epochs.",
|
| 505 |
+
)
|
| 506 |
+
parser.add_argument("--warmup_steps", default=0, type=int, help="Linear warmup over warmup_steps.")
|
| 507 |
+
parser.add_argument("--early_exit_entropy", default=-1, type=float, help="Entropy threshold for early exit.")
|
| 508 |
+
|
| 509 |
+
parser.add_argument("--logging_steps", type=int, default=50, help="Log every X updates steps.")
|
| 510 |
+
parser.add_argument("--save_steps", type=int, default=50, help="Save checkpoint every X updates steps.")
|
| 511 |
+
parser.add_argument(
|
| 512 |
+
"--eval_all_checkpoints",
|
| 513 |
+
action="store_true",
|
| 514 |
+
help="Evaluate all checkpoints starting with the same prefix as model_name ending and ending with step number",
|
| 515 |
+
)
|
| 516 |
+
parser.add_argument("--no_cuda", action="store_true", help="Avoid using CUDA when available")
|
| 517 |
+
parser.add_argument(
|
| 518 |
+
"--overwrite_output_dir", action="store_true", help="Overwrite the content of the output directory"
|
| 519 |
+
)
|
| 520 |
+
parser.add_argument(
|
| 521 |
+
"--overwrite_cache", action="store_true", help="Overwrite the cached training and evaluation sets"
|
| 522 |
+
)
|
| 523 |
+
parser.add_argument("--seed", type=int, default=42, help="random seed for initialization")
|
| 524 |
+
|
| 525 |
+
parser.add_argument(
|
| 526 |
+
"--fp16",
|
| 527 |
+
action="store_true",
|
| 528 |
+
help="Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit",
|
| 529 |
+
)
|
| 530 |
+
parser.add_argument(
|
| 531 |
+
"--fp16_opt_level",
|
| 532 |
+
type=str,
|
| 533 |
+
default="O1",
|
| 534 |
+
help=(
|
| 535 |
+
"For fp16: Apex AMP optimization level selected in ['O0', 'O1', 'O2', and 'O3']. "
|
| 536 |
+
"See details at https://nvidia.github.io/apex/amp.html"
|
| 537 |
+
),
|
| 538 |
+
)
|
| 539 |
+
parser.add_argument("--local_rank", type=int, default=-1, help="For distributed training: local_rank")
|
| 540 |
+
parser.add_argument("--server_ip", type=str, default="", help="For distant debugging.")
|
| 541 |
+
parser.add_argument("--server_port", type=str, default="", help="For distant debugging.")
|
| 542 |
+
args = parser.parse_args()
|
| 543 |
+
|
| 544 |
+
if (
|
| 545 |
+
os.path.exists(args.output_dir)
|
| 546 |
+
and os.listdir(args.output_dir)
|
| 547 |
+
and args.do_train
|
| 548 |
+
and not args.overwrite_output_dir
|
| 549 |
+
):
|
| 550 |
+
raise ValueError(
|
| 551 |
+
"Output directory ({}) already exists and is not empty. Use --overwrite_output_dir to overcome.".format(
|
| 552 |
+
args.output_dir
|
| 553 |
+
)
|
| 554 |
+
)
|
| 555 |
+
|
| 556 |
+
# Setup distant debugging if needed
|
| 557 |
+
if args.server_ip and args.server_port:
|
| 558 |
+
# Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script
|
| 559 |
+
import ptvsd
|
| 560 |
+
|
| 561 |
+
print("Waiting for debugger attach")
|
| 562 |
+
ptvsd.enable_attach(address=(args.server_ip, args.server_port), redirect_output=True)
|
| 563 |
+
ptvsd.wait_for_attach()
|
| 564 |
+
|
| 565 |
+
# Setup CUDA, GPU & distributed training
|
| 566 |
+
if args.local_rank == -1 or args.no_cuda:
|
| 567 |
+
device = torch.device("cuda" if torch.cuda.is_available() and not args.no_cuda else "cpu")
|
| 568 |
+
args.n_gpu = torch.cuda.device_count()
|
| 569 |
+
else: # Initializes the distributed backend which will take care of synchronizing nodes/GPUs
|
| 570 |
+
torch.cuda.set_device(args.local_rank)
|
| 571 |
+
device = torch.device("cuda", args.local_rank)
|
| 572 |
+
torch.distributed.init_process_group(backend="nccl")
|
| 573 |
+
args.n_gpu = 1
|
| 574 |
+
args.device = device
|
| 575 |
+
|
| 576 |
+
# Setup logging
|
| 577 |
+
logging.basicConfig(
|
| 578 |
+
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
|
| 579 |
+
datefmt="%m/%d/%Y %H:%M:%S",
|
| 580 |
+
level=logging.INFO if args.local_rank in [-1, 0] else logging.WARN,
|
| 581 |
+
)
|
| 582 |
+
logger.warning(
|
| 583 |
+
"Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s",
|
| 584 |
+
args.local_rank,
|
| 585 |
+
device,
|
| 586 |
+
args.n_gpu,
|
| 587 |
+
bool(args.local_rank != -1),
|
| 588 |
+
args.fp16,
|
| 589 |
+
)
|
| 590 |
+
# Set the verbosity to info of the Transformers logger (on main process only):
|
| 591 |
+
if is_main_process(args.local_rank):
|
| 592 |
+
transformers.utils.logging.set_verbosity_info()
|
| 593 |
+
transformers.utils.logging.enable_default_handler()
|
| 594 |
+
transformers.utils.logging.enable_explicit_format()
|
| 595 |
+
# Set seed
|
| 596 |
+
set_seed(args)
|
| 597 |
+
|
| 598 |
+
# Prepare GLUE task
|
| 599 |
+
args.task_name = args.task_name.lower()
|
| 600 |
+
if args.task_name not in processors:
|
| 601 |
+
raise ValueError("Task not found: %s" % (args.task_name))
|
| 602 |
+
processor = processors[args.task_name]()
|
| 603 |
+
args.output_mode = output_modes[args.task_name]
|
| 604 |
+
label_list = processor.get_labels()
|
| 605 |
+
num_labels = len(label_list)
|
| 606 |
+
|
| 607 |
+
# Load pretrained model and tokenizer
|
| 608 |
+
if args.local_rank not in [-1, 0]:
|
| 609 |
+
torch.distributed.barrier() # Make sure only the first process in distributed training will download model & vocab
|
| 610 |
+
|
| 611 |
+
args.model_type = args.model_type.lower()
|
| 612 |
+
config_class, model_class, tokenizer_class = MODEL_CLASSES[args.model_type]
|
| 613 |
+
config = config_class.from_pretrained(
|
| 614 |
+
args.config_name if args.config_name else args.model_name_or_path,
|
| 615 |
+
num_labels=num_labels,
|
| 616 |
+
finetuning_task=args.task_name,
|
| 617 |
+
cache_dir=args.cache_dir if args.cache_dir else None,
|
| 618 |
+
)
|
| 619 |
+
tokenizer = tokenizer_class.from_pretrained(
|
| 620 |
+
args.tokenizer_name if args.tokenizer_name else args.model_name_or_path,
|
| 621 |
+
do_lower_case=args.do_lower_case,
|
| 622 |
+
cache_dir=args.cache_dir if args.cache_dir else None,
|
| 623 |
+
)
|
| 624 |
+
model = model_class.from_pretrained(
|
| 625 |
+
args.model_name_or_path,
|
| 626 |
+
from_tf=bool(".ckpt" in args.model_name_or_path),
|
| 627 |
+
config=config,
|
| 628 |
+
cache_dir=args.cache_dir if args.cache_dir else None,
|
| 629 |
+
)
|
| 630 |
+
|
| 631 |
+
if args.model_type == "bert":
|
| 632 |
+
model.bert.encoder.set_early_exit_entropy(args.early_exit_entropy)
|
| 633 |
+
model.bert.init_highway_pooler()
|
| 634 |
+
elif args.model_type == "roberta":
|
| 635 |
+
model.roberta.encoder.set_early_exit_entropy(args.early_exit_entropy)
|
| 636 |
+
model.roberta.init_highway_pooler()
|
| 637 |
+
else:
|
| 638 |
+
raise NotImplementedError()
|
| 639 |
+
|
| 640 |
+
if args.local_rank == 0:
|
| 641 |
+
torch.distributed.barrier() # Make sure only the first process in distributed training will download model & vocab
|
| 642 |
+
|
| 643 |
+
model.to(args.device)
|
| 644 |
+
|
| 645 |
+
logger.info("Training/evaluation parameters %s", args)
|
| 646 |
+
|
| 647 |
+
# Training
|
| 648 |
+
if args.do_train:
|
| 649 |
+
train_dataset = load_and_cache_examples(args, args.task_name, tokenizer, evaluate=False)
|
| 650 |
+
global_step, tr_loss = train(args, train_dataset, model, tokenizer)
|
| 651 |
+
logger.info(" global_step = %s, average loss = %s", global_step, tr_loss)
|
| 652 |
+
|
| 653 |
+
if args.eval_after_first_stage:
|
| 654 |
+
result = evaluate(args, model, tokenizer, prefix="")
|
| 655 |
+
print_result = get_wanted_result(result)
|
| 656 |
+
|
| 657 |
+
train(args, train_dataset, model, tokenizer, train_highway=True)
|
| 658 |
+
|
| 659 |
+
# Saving best-practices: if you use defaults names for the model, you can reload it using from_pretrained()
|
| 660 |
+
if args.do_train and (args.local_rank == -1 or torch.distributed.get_rank() == 0):
|
| 661 |
+
# Create output directory if needed
|
| 662 |
+
if not os.path.exists(args.output_dir) and args.local_rank in [-1, 0]:
|
| 663 |
+
os.makedirs(args.output_dir)
|
| 664 |
+
|
| 665 |
+
logger.info("Saving model checkpoint to %s", args.output_dir)
|
| 666 |
+
# Save a trained model, configuration and tokenizer using `save_pretrained()`.
|
| 667 |
+
# They can then be reloaded using `from_pretrained()`
|
| 668 |
+
model_to_save = (
|
| 669 |
+
model.module if hasattr(model, "module") else model
|
| 670 |
+
) # Take care of distributed/parallel training
|
| 671 |
+
model_to_save.save_pretrained(args.output_dir)
|
| 672 |
+
tokenizer.save_pretrained(args.output_dir)
|
| 673 |
+
|
| 674 |
+
# Good practice: save your training arguments together with the trained model
|
| 675 |
+
torch.save(args, os.path.join(args.output_dir, "training_args.bin"))
|
| 676 |
+
|
| 677 |
+
# Load a trained model and vocabulary that you have fine-tuned
|
| 678 |
+
model = model_class.from_pretrained(args.output_dir)
|
| 679 |
+
tokenizer = tokenizer_class.from_pretrained(args.output_dir)
|
| 680 |
+
model.to(args.device)
|
| 681 |
+
|
| 682 |
+
# Evaluation
|
| 683 |
+
results = {}
|
| 684 |
+
if args.do_eval and args.local_rank in [-1, 0]:
|
| 685 |
+
tokenizer = tokenizer_class.from_pretrained(args.output_dir, do_lower_case=args.do_lower_case)
|
| 686 |
+
checkpoints = [args.output_dir]
|
| 687 |
+
if args.eval_all_checkpoints:
|
| 688 |
+
checkpoints = [
|
| 689 |
+
os.path.dirname(c) for c in sorted(glob.glob(args.output_dir + "/**/" + WEIGHTS_NAME, recursive=True))
|
| 690 |
+
]
|
| 691 |
+
|
| 692 |
+
logger.info("Evaluate the following checkpoints: %s", checkpoints)
|
| 693 |
+
for checkpoint in checkpoints:
|
| 694 |
+
global_step = checkpoint.split("-")[-1] if len(checkpoints) > 1 else ""
|
| 695 |
+
prefix = checkpoint.split("/")[-1] if checkpoint.find("checkpoint") != -1 else ""
|
| 696 |
+
|
| 697 |
+
model = model_class.from_pretrained(checkpoint)
|
| 698 |
+
if args.model_type == "bert":
|
| 699 |
+
model.bert.encoder.set_early_exit_entropy(args.early_exit_entropy)
|
| 700 |
+
elif args.model_type == "roberta":
|
| 701 |
+
model.roberta.encoder.set_early_exit_entropy(args.early_exit_entropy)
|
| 702 |
+
else:
|
| 703 |
+
raise NotImplementedError()
|
| 704 |
+
|
| 705 |
+
model.to(args.device)
|
| 706 |
+
result = evaluate(args, model, tokenizer, prefix=prefix, eval_highway=args.eval_highway)
|
| 707 |
+
print_result = get_wanted_result(result)
|
| 708 |
+
logger.info("Result: {}".format(print_result))
|
| 709 |
+
if args.eval_each_highway:
|
| 710 |
+
last_layer_results = print_result
|
| 711 |
+
each_layer_results = []
|
| 712 |
+
for i in range(model.num_layers):
|
| 713 |
+
logger.info("\n")
|
| 714 |
+
_result = evaluate(
|
| 715 |
+
args, model, tokenizer, prefix=prefix, output_layer=i, eval_highway=args.eval_highway
|
| 716 |
+
)
|
| 717 |
+
if i + 1 < model.num_layers:
|
| 718 |
+
each_layer_results.append(get_wanted_result(_result))
|
| 719 |
+
each_layer_results.append(last_layer_results)
|
| 720 |
+
save_fname = args.plot_data_dir + "/" + args.model_name_or_path[2:] + "/each_layer.npy"
|
| 721 |
+
if not os.path.exists(os.path.dirname(save_fname)):
|
| 722 |
+
os.makedirs(os.path.dirname(save_fname))
|
| 723 |
+
np.save(save_fname, np.array(each_layer_results))
|
| 724 |
+
info_str = "Score of each layer:"
|
| 725 |
+
for i in range(model.num_layers):
|
| 726 |
+
info_str += " {:.2f}".format(100 * each_layer_results[i])
|
| 727 |
+
logger.info(info_str)
|
| 728 |
+
result = {k + "_{}".format(global_step): v for k, v in result.items()}
|
| 729 |
+
results.update(result)
|
| 730 |
+
|
| 731 |
+
return results
|
| 732 |
+
|
| 733 |
+
|
| 734 |
+
if __name__ == "__main__":
|
| 735 |
+
main()
|
tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/deebert/src/__init__.py
ADDED
|
File without changes
|
tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/deebert/src/modeling_highway_bert.py
ADDED
|
@@ -0,0 +1,397 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from torch import nn
|
| 3 |
+
from torch.nn import CrossEntropyLoss, MSELoss
|
| 4 |
+
|
| 5 |
+
from transformers.file_utils import add_start_docstrings, add_start_docstrings_to_model_forward
|
| 6 |
+
from transformers.models.bert.modeling_bert import (
|
| 7 |
+
BERT_INPUTS_DOCSTRING,
|
| 8 |
+
BERT_START_DOCSTRING,
|
| 9 |
+
BertEmbeddings,
|
| 10 |
+
BertLayer,
|
| 11 |
+
BertPooler,
|
| 12 |
+
BertPreTrainedModel,
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def entropy(x):
|
| 17 |
+
"""Calculate entropy of a pre-softmax logit Tensor"""
|
| 18 |
+
exp_x = torch.exp(x)
|
| 19 |
+
A = torch.sum(exp_x, dim=1) # sum of exp(x_i)
|
| 20 |
+
B = torch.sum(x * exp_x, dim=1) # sum of x_i * exp(x_i)
|
| 21 |
+
return torch.log(A) - B / A
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class DeeBertEncoder(nn.Module):
|
| 25 |
+
def __init__(self, config):
|
| 26 |
+
super().__init__()
|
| 27 |
+
self.output_attentions = config.output_attentions
|
| 28 |
+
self.output_hidden_states = config.output_hidden_states
|
| 29 |
+
self.layer = nn.ModuleList([BertLayer(config) for _ in range(config.num_hidden_layers)])
|
| 30 |
+
self.highway = nn.ModuleList([BertHighway(config) for _ in range(config.num_hidden_layers)])
|
| 31 |
+
|
| 32 |
+
self.early_exit_entropy = [-1 for _ in range(config.num_hidden_layers)]
|
| 33 |
+
|
| 34 |
+
def set_early_exit_entropy(self, x):
|
| 35 |
+
if isinstance(x, (float, int)):
|
| 36 |
+
for i in range(len(self.early_exit_entropy)):
|
| 37 |
+
self.early_exit_entropy[i] = x
|
| 38 |
+
else:
|
| 39 |
+
self.early_exit_entropy = x
|
| 40 |
+
|
| 41 |
+
def init_highway_pooler(self, pooler):
|
| 42 |
+
loaded_model = pooler.state_dict()
|
| 43 |
+
for highway in self.highway:
|
| 44 |
+
for name, param in highway.pooler.state_dict().items():
|
| 45 |
+
param.copy_(loaded_model[name])
|
| 46 |
+
|
| 47 |
+
def forward(
|
| 48 |
+
self,
|
| 49 |
+
hidden_states,
|
| 50 |
+
attention_mask=None,
|
| 51 |
+
head_mask=None,
|
| 52 |
+
encoder_hidden_states=None,
|
| 53 |
+
encoder_attention_mask=None,
|
| 54 |
+
):
|
| 55 |
+
all_hidden_states = ()
|
| 56 |
+
all_attentions = ()
|
| 57 |
+
all_highway_exits = ()
|
| 58 |
+
for i, layer_module in enumerate(self.layer):
|
| 59 |
+
if self.output_hidden_states:
|
| 60 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 61 |
+
|
| 62 |
+
layer_outputs = layer_module(
|
| 63 |
+
hidden_states, attention_mask, head_mask[i], encoder_hidden_states, encoder_attention_mask
|
| 64 |
+
)
|
| 65 |
+
hidden_states = layer_outputs[0]
|
| 66 |
+
|
| 67 |
+
if self.output_attentions:
|
| 68 |
+
all_attentions = all_attentions + (layer_outputs[1],)
|
| 69 |
+
|
| 70 |
+
current_outputs = (hidden_states,)
|
| 71 |
+
if self.output_hidden_states:
|
| 72 |
+
current_outputs = current_outputs + (all_hidden_states,)
|
| 73 |
+
if self.output_attentions:
|
| 74 |
+
current_outputs = current_outputs + (all_attentions,)
|
| 75 |
+
|
| 76 |
+
highway_exit = self.highway[i](current_outputs)
|
| 77 |
+
# logits, pooled_output
|
| 78 |
+
|
| 79 |
+
if not self.training:
|
| 80 |
+
highway_logits = highway_exit[0]
|
| 81 |
+
highway_entropy = entropy(highway_logits)
|
| 82 |
+
highway_exit = highway_exit + (highway_entropy,) # logits, hidden_states(?), entropy
|
| 83 |
+
all_highway_exits = all_highway_exits + (highway_exit,)
|
| 84 |
+
|
| 85 |
+
if highway_entropy < self.early_exit_entropy[i]:
|
| 86 |
+
new_output = (highway_logits,) + current_outputs[1:] + (all_highway_exits,)
|
| 87 |
+
raise HighwayException(new_output, i + 1)
|
| 88 |
+
else:
|
| 89 |
+
all_highway_exits = all_highway_exits + (highway_exit,)
|
| 90 |
+
|
| 91 |
+
# Add last layer
|
| 92 |
+
if self.output_hidden_states:
|
| 93 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 94 |
+
|
| 95 |
+
outputs = (hidden_states,)
|
| 96 |
+
if self.output_hidden_states:
|
| 97 |
+
outputs = outputs + (all_hidden_states,)
|
| 98 |
+
if self.output_attentions:
|
| 99 |
+
outputs = outputs + (all_attentions,)
|
| 100 |
+
|
| 101 |
+
outputs = outputs + (all_highway_exits,)
|
| 102 |
+
return outputs # last-layer hidden state, (all hidden states), (all attentions), all highway exits
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
@add_start_docstrings(
|
| 106 |
+
"The Bert Model transformer with early exiting (DeeBERT). ",
|
| 107 |
+
BERT_START_DOCSTRING,
|
| 108 |
+
)
|
| 109 |
+
class DeeBertModel(BertPreTrainedModel):
|
| 110 |
+
def __init__(self, config):
|
| 111 |
+
super().__init__(config)
|
| 112 |
+
self.config = config
|
| 113 |
+
|
| 114 |
+
self.embeddings = BertEmbeddings(config)
|
| 115 |
+
self.encoder = DeeBertEncoder(config)
|
| 116 |
+
self.pooler = BertPooler(config)
|
| 117 |
+
|
| 118 |
+
self.init_weights()
|
| 119 |
+
|
| 120 |
+
def init_highway_pooler(self):
|
| 121 |
+
self.encoder.init_highway_pooler(self.pooler)
|
| 122 |
+
|
| 123 |
+
def get_input_embeddings(self):
|
| 124 |
+
return self.embeddings.word_embeddings
|
| 125 |
+
|
| 126 |
+
def set_input_embeddings(self, value):
|
| 127 |
+
self.embeddings.word_embeddings = value
|
| 128 |
+
|
| 129 |
+
def _prune_heads(self, heads_to_prune):
|
| 130 |
+
"""Prunes heads of the model.
|
| 131 |
+
heads_to_prune: dict of {layer_num: list of heads to prune in this layer}
|
| 132 |
+
See base class PreTrainedModel
|
| 133 |
+
"""
|
| 134 |
+
for layer, heads in heads_to_prune.items():
|
| 135 |
+
self.encoder.layer[layer].attention.prune_heads(heads)
|
| 136 |
+
|
| 137 |
+
@add_start_docstrings_to_model_forward(BERT_INPUTS_DOCSTRING)
|
| 138 |
+
def forward(
|
| 139 |
+
self,
|
| 140 |
+
input_ids=None,
|
| 141 |
+
attention_mask=None,
|
| 142 |
+
token_type_ids=None,
|
| 143 |
+
position_ids=None,
|
| 144 |
+
head_mask=None,
|
| 145 |
+
inputs_embeds=None,
|
| 146 |
+
encoder_hidden_states=None,
|
| 147 |
+
encoder_attention_mask=None,
|
| 148 |
+
):
|
| 149 |
+
r"""
|
| 150 |
+
Return:
|
| 151 |
+
:obj:`tuple(torch.FloatTensor)` comprising various elements depending on the configuration (:class:`~transformers.BertConfig`) and inputs:
|
| 152 |
+
last_hidden_state (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`):
|
| 153 |
+
Sequence of hidden-states at the output of the last layer of the model.
|
| 154 |
+
pooler_output (:obj:`torch.FloatTensor`: of shape :obj:`(batch_size, hidden_size)`):
|
| 155 |
+
Last layer hidden-state of the first token of the sequence (classification token)
|
| 156 |
+
further processed by a Linear layer and a Tanh activation function. The Linear
|
| 157 |
+
layer weights are trained from the next sentence prediction (classification)
|
| 158 |
+
objective during pre-training.
|
| 159 |
+
|
| 160 |
+
This output is usually *not* a good summary
|
| 161 |
+
of the semantic content of the input, you're often better with averaging or pooling
|
| 162 |
+
the sequence of hidden-states for the whole input sequence.
|
| 163 |
+
hidden_states (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``output_hidden_states=True`` is passed or when ``config.output_hidden_states=True``):
|
| 164 |
+
Tuple of :obj:`torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer)
|
| 165 |
+
of shape :obj:`(batch_size, sequence_length, hidden_size)`.
|
| 166 |
+
|
| 167 |
+
Hidden-states of the model at the output of each layer plus the initial embedding outputs.
|
| 168 |
+
attentions (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``output_attentions=True`` is passed or when ``config.output_attentions=True``):
|
| 169 |
+
Tuple of :obj:`torch.FloatTensor` (one for each layer) of shape
|
| 170 |
+
:obj:`(batch_size, num_heads, sequence_length, sequence_length)`.
|
| 171 |
+
|
| 172 |
+
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
|
| 173 |
+
heads.
|
| 174 |
+
highway_exits (:obj:`tuple(tuple(torch.Tensor))`:
|
| 175 |
+
Tuple of each early exit's results (total length: number of layers)
|
| 176 |
+
Each tuple is again, a tuple of length 2 - the first entry is logits and the second entry is hidden states.
|
| 177 |
+
"""
|
| 178 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 179 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
| 180 |
+
elif input_ids is not None:
|
| 181 |
+
input_shape = input_ids.size()
|
| 182 |
+
elif inputs_embeds is not None:
|
| 183 |
+
input_shape = inputs_embeds.size()[:-1]
|
| 184 |
+
else:
|
| 185 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
| 186 |
+
|
| 187 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
| 188 |
+
|
| 189 |
+
if attention_mask is None:
|
| 190 |
+
attention_mask = torch.ones(input_shape, device=device)
|
| 191 |
+
if encoder_attention_mask is None:
|
| 192 |
+
encoder_attention_mask = torch.ones(input_shape, device=device)
|
| 193 |
+
if token_type_ids is None:
|
| 194 |
+
token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
|
| 195 |
+
|
| 196 |
+
# We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
|
| 197 |
+
# ourselves in which case we just need to make it broadcastable to all heads.
|
| 198 |
+
extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(attention_mask, input_shape, device)
|
| 199 |
+
|
| 200 |
+
# If a 2D ou 3D attention mask is provided for the cross-attention
|
| 201 |
+
# we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
|
| 202 |
+
if encoder_attention_mask.dim() == 3:
|
| 203 |
+
encoder_extended_attention_mask = encoder_attention_mask[:, None, :, :]
|
| 204 |
+
if encoder_attention_mask.dim() == 2:
|
| 205 |
+
encoder_extended_attention_mask = encoder_attention_mask[:, None, None, :]
|
| 206 |
+
|
| 207 |
+
encoder_extended_attention_mask = encoder_extended_attention_mask.to(
|
| 208 |
+
dtype=next(self.parameters()).dtype
|
| 209 |
+
) # fp16 compatibility
|
| 210 |
+
encoder_extended_attention_mask = (1.0 - encoder_extended_attention_mask) * -10000.0
|
| 211 |
+
|
| 212 |
+
# Prepare head mask if needed
|
| 213 |
+
# 1.0 in head_mask indicate we keep the head
|
| 214 |
+
# attention_probs has shape bsz x n_heads x N x N
|
| 215 |
+
# input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
|
| 216 |
+
# and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
|
| 217 |
+
head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
|
| 218 |
+
|
| 219 |
+
embedding_output = self.embeddings(
|
| 220 |
+
input_ids=input_ids, position_ids=position_ids, token_type_ids=token_type_ids, inputs_embeds=inputs_embeds
|
| 221 |
+
)
|
| 222 |
+
encoder_outputs = self.encoder(
|
| 223 |
+
embedding_output,
|
| 224 |
+
attention_mask=extended_attention_mask,
|
| 225 |
+
head_mask=head_mask,
|
| 226 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 227 |
+
encoder_attention_mask=encoder_extended_attention_mask,
|
| 228 |
+
)
|
| 229 |
+
sequence_output = encoder_outputs[0]
|
| 230 |
+
pooled_output = self.pooler(sequence_output)
|
| 231 |
+
|
| 232 |
+
outputs = (
|
| 233 |
+
sequence_output,
|
| 234 |
+
pooled_output,
|
| 235 |
+
) + encoder_outputs[1:] # add hidden_states and attentions if they are here
|
| 236 |
+
return outputs # sequence_output, pooled_output, (hidden_states), (attentions), highway exits
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
class HighwayException(Exception):
|
| 240 |
+
def __init__(self, message, exit_layer):
|
| 241 |
+
self.message = message
|
| 242 |
+
self.exit_layer = exit_layer # start from 1!
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
class BertHighway(nn.Module):
|
| 246 |
+
"""A module to provide a shortcut
|
| 247 |
+
from (the output of one non-final BertLayer in BertEncoder) to (cross-entropy computation in BertForSequenceClassification)
|
| 248 |
+
"""
|
| 249 |
+
|
| 250 |
+
def __init__(self, config):
|
| 251 |
+
super().__init__()
|
| 252 |
+
self.pooler = BertPooler(config)
|
| 253 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 254 |
+
self.classifier = nn.Linear(config.hidden_size, config.num_labels)
|
| 255 |
+
|
| 256 |
+
def forward(self, encoder_outputs):
|
| 257 |
+
# Pooler
|
| 258 |
+
pooler_input = encoder_outputs[0]
|
| 259 |
+
pooler_output = self.pooler(pooler_input)
|
| 260 |
+
# "return" pooler_output
|
| 261 |
+
|
| 262 |
+
# BertModel
|
| 263 |
+
bmodel_output = (pooler_input, pooler_output) + encoder_outputs[1:]
|
| 264 |
+
# "return" bmodel_output
|
| 265 |
+
|
| 266 |
+
# Dropout and classification
|
| 267 |
+
pooled_output = bmodel_output[1]
|
| 268 |
+
|
| 269 |
+
pooled_output = self.dropout(pooled_output)
|
| 270 |
+
logits = self.classifier(pooled_output)
|
| 271 |
+
|
| 272 |
+
return logits, pooled_output
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
@add_start_docstrings(
|
| 276 |
+
"""Bert Model (with early exiting - DeeBERT) with a classifier on top,
|
| 277 |
+
also takes care of multi-layer training. """,
|
| 278 |
+
BERT_START_DOCSTRING,
|
| 279 |
+
)
|
| 280 |
+
class DeeBertForSequenceClassification(BertPreTrainedModel):
|
| 281 |
+
def __init__(self, config):
|
| 282 |
+
super().__init__(config)
|
| 283 |
+
self.num_labels = config.num_labels
|
| 284 |
+
self.num_layers = config.num_hidden_layers
|
| 285 |
+
|
| 286 |
+
self.bert = DeeBertModel(config)
|
| 287 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 288 |
+
self.classifier = nn.Linear(config.hidden_size, self.config.num_labels)
|
| 289 |
+
|
| 290 |
+
self.init_weights()
|
| 291 |
+
|
| 292 |
+
@add_start_docstrings_to_model_forward(BERT_INPUTS_DOCSTRING)
|
| 293 |
+
def forward(
|
| 294 |
+
self,
|
| 295 |
+
input_ids=None,
|
| 296 |
+
attention_mask=None,
|
| 297 |
+
token_type_ids=None,
|
| 298 |
+
position_ids=None,
|
| 299 |
+
head_mask=None,
|
| 300 |
+
inputs_embeds=None,
|
| 301 |
+
labels=None,
|
| 302 |
+
output_layer=-1,
|
| 303 |
+
train_highway=False,
|
| 304 |
+
):
|
| 305 |
+
r"""
|
| 306 |
+
labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`):
|
| 307 |
+
Labels for computing the sequence classification/regression loss.
|
| 308 |
+
Indices should be in :obj:`[0, ..., config.num_labels - 1]`.
|
| 309 |
+
If :obj:`config.num_labels == 1` a regression loss is computed (Mean-Square loss),
|
| 310 |
+
If :obj:`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
| 311 |
+
|
| 312 |
+
Returns:
|
| 313 |
+
:obj:`tuple(torch.FloatTensor)` comprising various elements depending on the configuration (:class:`~transformers.BertConfig`) and inputs:
|
| 314 |
+
loss (:obj:`torch.FloatTensor` of shape :obj:`(1,)`, `optional`, returned when :obj:`label` is provided):
|
| 315 |
+
Classification (or regression if config.num_labels==1) loss.
|
| 316 |
+
logits (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, config.num_labels)`):
|
| 317 |
+
Classification (or regression if config.num_labels==1) scores (before SoftMax).
|
| 318 |
+
hidden_states (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``output_hidden_states=True`` is passed or when ``config.output_hidden_states=True``):
|
| 319 |
+
Tuple of :obj:`torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer)
|
| 320 |
+
of shape :obj:`(batch_size, sequence_length, hidden_size)`.
|
| 321 |
+
|
| 322 |
+
Hidden-states of the model at the output of each layer plus the initial embedding outputs.
|
| 323 |
+
attentions (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``output_attentions=True`` is passed or when ``config.output_attentions=True``):
|
| 324 |
+
Tuple of :obj:`torch.FloatTensor` (one for each layer) of shape
|
| 325 |
+
:obj:`(batch_size, num_heads, sequence_length, sequence_length)`.
|
| 326 |
+
|
| 327 |
+
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
|
| 328 |
+
heads.
|
| 329 |
+
highway_exits (:obj:`tuple(tuple(torch.Tensor))`:
|
| 330 |
+
Tuple of each early exit's results (total length: number of layers)
|
| 331 |
+
Each tuple is again, a tuple of length 2 - the first entry is logits and the second entry is hidden states.
|
| 332 |
+
"""
|
| 333 |
+
|
| 334 |
+
exit_layer = self.num_layers
|
| 335 |
+
try:
|
| 336 |
+
outputs = self.bert(
|
| 337 |
+
input_ids,
|
| 338 |
+
attention_mask=attention_mask,
|
| 339 |
+
token_type_ids=token_type_ids,
|
| 340 |
+
position_ids=position_ids,
|
| 341 |
+
head_mask=head_mask,
|
| 342 |
+
inputs_embeds=inputs_embeds,
|
| 343 |
+
)
|
| 344 |
+
# sequence_output, pooled_output, (hidden_states), (attentions), highway exits
|
| 345 |
+
|
| 346 |
+
pooled_output = outputs[1]
|
| 347 |
+
|
| 348 |
+
pooled_output = self.dropout(pooled_output)
|
| 349 |
+
logits = self.classifier(pooled_output)
|
| 350 |
+
outputs = (logits,) + outputs[2:] # add hidden states and attention if they are here
|
| 351 |
+
except HighwayException as e:
|
| 352 |
+
outputs = e.message
|
| 353 |
+
exit_layer = e.exit_layer
|
| 354 |
+
logits = outputs[0]
|
| 355 |
+
|
| 356 |
+
if not self.training:
|
| 357 |
+
original_entropy = entropy(logits)
|
| 358 |
+
highway_entropy = []
|
| 359 |
+
highway_logits_all = []
|
| 360 |
+
if labels is not None:
|
| 361 |
+
if self.num_labels == 1:
|
| 362 |
+
# We are doing regression
|
| 363 |
+
loss_fct = MSELoss()
|
| 364 |
+
loss = loss_fct(logits.view(-1), labels.view(-1))
|
| 365 |
+
else:
|
| 366 |
+
loss_fct = CrossEntropyLoss()
|
| 367 |
+
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
|
| 368 |
+
|
| 369 |
+
# work with highway exits
|
| 370 |
+
highway_losses = []
|
| 371 |
+
for highway_exit in outputs[-1]:
|
| 372 |
+
highway_logits = highway_exit[0]
|
| 373 |
+
if not self.training:
|
| 374 |
+
highway_logits_all.append(highway_logits)
|
| 375 |
+
highway_entropy.append(highway_exit[2])
|
| 376 |
+
if self.num_labels == 1:
|
| 377 |
+
# We are doing regression
|
| 378 |
+
loss_fct = MSELoss()
|
| 379 |
+
highway_loss = loss_fct(highway_logits.view(-1), labels.view(-1))
|
| 380 |
+
else:
|
| 381 |
+
loss_fct = CrossEntropyLoss()
|
| 382 |
+
highway_loss = loss_fct(highway_logits.view(-1, self.num_labels), labels.view(-1))
|
| 383 |
+
highway_losses.append(highway_loss)
|
| 384 |
+
|
| 385 |
+
if train_highway:
|
| 386 |
+
outputs = (sum(highway_losses[:-1]),) + outputs
|
| 387 |
+
# exclude the final highway, of course
|
| 388 |
+
else:
|
| 389 |
+
outputs = (loss,) + outputs
|
| 390 |
+
if not self.training:
|
| 391 |
+
outputs = outputs + ((original_entropy, highway_entropy), exit_layer)
|
| 392 |
+
if output_layer >= 0:
|
| 393 |
+
outputs = (
|
| 394 |
+
(outputs[0],) + (highway_logits_all[output_layer],) + outputs[2:]
|
| 395 |
+
) # use the highway of the last layer
|
| 396 |
+
|
| 397 |
+
return outputs # (loss), logits, (hidden_states), (attentions), (highway_exits)
|
tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/deebert/src/modeling_highway_roberta.py
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import absolute_import, division, print_function, unicode_literals
|
| 2 |
+
|
| 3 |
+
from torch import nn
|
| 4 |
+
from torch.nn import CrossEntropyLoss, MSELoss
|
| 5 |
+
|
| 6 |
+
from transformers import RobertaConfig
|
| 7 |
+
from transformers.file_utils import add_start_docstrings, add_start_docstrings_to_model_forward
|
| 8 |
+
from transformers.models.roberta.modeling_roberta import (
|
| 9 |
+
ROBERTA_INPUTS_DOCSTRING,
|
| 10 |
+
ROBERTA_START_DOCSTRING,
|
| 11 |
+
RobertaEmbeddings,
|
| 12 |
+
)
|
| 13 |
+
|
| 14 |
+
from .modeling_highway_bert import BertPreTrainedModel, DeeBertModel, HighwayException, entropy
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
@add_start_docstrings(
|
| 18 |
+
"The RoBERTa Model transformer with early exiting (DeeRoBERTa). ",
|
| 19 |
+
ROBERTA_START_DOCSTRING,
|
| 20 |
+
)
|
| 21 |
+
class DeeRobertaModel(DeeBertModel):
|
| 22 |
+
config_class = RobertaConfig
|
| 23 |
+
base_model_prefix = "roberta"
|
| 24 |
+
|
| 25 |
+
def __init__(self, config):
|
| 26 |
+
super().__init__(config)
|
| 27 |
+
|
| 28 |
+
self.embeddings = RobertaEmbeddings(config)
|
| 29 |
+
self.init_weights()
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
@add_start_docstrings(
|
| 33 |
+
"""RoBERTa Model (with early exiting - DeeRoBERTa) with a classifier on top,
|
| 34 |
+
also takes care of multi-layer training. """,
|
| 35 |
+
ROBERTA_START_DOCSTRING,
|
| 36 |
+
)
|
| 37 |
+
class DeeRobertaForSequenceClassification(BertPreTrainedModel):
|
| 38 |
+
config_class = RobertaConfig
|
| 39 |
+
base_model_prefix = "roberta"
|
| 40 |
+
|
| 41 |
+
def __init__(self, config):
|
| 42 |
+
super().__init__(config)
|
| 43 |
+
self.num_labels = config.num_labels
|
| 44 |
+
self.num_layers = config.num_hidden_layers
|
| 45 |
+
|
| 46 |
+
self.roberta = DeeRobertaModel(config)
|
| 47 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 48 |
+
self.classifier = nn.Linear(config.hidden_size, self.config.num_labels)
|
| 49 |
+
|
| 50 |
+
@add_start_docstrings_to_model_forward(ROBERTA_INPUTS_DOCSTRING)
|
| 51 |
+
def forward(
|
| 52 |
+
self,
|
| 53 |
+
input_ids=None,
|
| 54 |
+
attention_mask=None,
|
| 55 |
+
token_type_ids=None,
|
| 56 |
+
position_ids=None,
|
| 57 |
+
head_mask=None,
|
| 58 |
+
inputs_embeds=None,
|
| 59 |
+
labels=None,
|
| 60 |
+
output_layer=-1,
|
| 61 |
+
train_highway=False,
|
| 62 |
+
):
|
| 63 |
+
r"""
|
| 64 |
+
labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`):
|
| 65 |
+
Labels for computing the sequence classification/regression loss.
|
| 66 |
+
Indices should be in :obj:`[0, ..., config.num_labels - 1]`.
|
| 67 |
+
If :obj:`config.num_labels == 1` a regression loss is computed (Mean-Square loss),
|
| 68 |
+
If :obj:`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
| 69 |
+
|
| 70 |
+
Returns:
|
| 71 |
+
:obj:`tuple(torch.FloatTensor)` comprising various elements depending on the configuration (:class:`~transformers.RobertaConfig`) and inputs:
|
| 72 |
+
loss (:obj:`torch.FloatTensor` of shape :obj:`(1,)`, `optional`, returned when :obj:`label` is provided):
|
| 73 |
+
Classification (or regression if config.num_labels==1) loss.
|
| 74 |
+
logits (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, config.num_labels)`):
|
| 75 |
+
Classification (or regression if config.num_labels==1) scores (before SoftMax).
|
| 76 |
+
hidden_states (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``output_hidden_states=True`` is passed or when ``config.output_hidden_states=True``):
|
| 77 |
+
Tuple of :obj:`torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer)
|
| 78 |
+
of shape :obj:`(batch_size, sequence_length, hidden_size)`.
|
| 79 |
+
|
| 80 |
+
Hidden-states of the model at the output of each layer plus the initial embedding outputs.
|
| 81 |
+
attentions (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``output_attentions=True`` is passed or when ``config.output_attentions=True``):
|
| 82 |
+
Tuple of :obj:`torch.FloatTensor` (one for each layer) of shape
|
| 83 |
+
:obj:`(batch_size, num_heads, sequence_length, sequence_length)`.
|
| 84 |
+
|
| 85 |
+
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
|
| 86 |
+
heads.
|
| 87 |
+
highway_exits (:obj:`tuple(tuple(torch.Tensor))`:
|
| 88 |
+
Tuple of each early exit's results (total length: number of layers)
|
| 89 |
+
Each tuple is again, a tuple of length 2 - the first entry is logits and the second entry is hidden states.
|
| 90 |
+
"""
|
| 91 |
+
|
| 92 |
+
exit_layer = self.num_layers
|
| 93 |
+
try:
|
| 94 |
+
outputs = self.roberta(
|
| 95 |
+
input_ids,
|
| 96 |
+
attention_mask=attention_mask,
|
| 97 |
+
token_type_ids=token_type_ids,
|
| 98 |
+
position_ids=position_ids,
|
| 99 |
+
head_mask=head_mask,
|
| 100 |
+
inputs_embeds=inputs_embeds,
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
pooled_output = outputs[1]
|
| 104 |
+
|
| 105 |
+
pooled_output = self.dropout(pooled_output)
|
| 106 |
+
logits = self.classifier(pooled_output)
|
| 107 |
+
outputs = (logits,) + outputs[2:] # add hidden states and attention if they are here
|
| 108 |
+
except HighwayException as e:
|
| 109 |
+
outputs = e.message
|
| 110 |
+
exit_layer = e.exit_layer
|
| 111 |
+
logits = outputs[0]
|
| 112 |
+
|
| 113 |
+
if not self.training:
|
| 114 |
+
original_entropy = entropy(logits)
|
| 115 |
+
highway_entropy = []
|
| 116 |
+
highway_logits_all = []
|
| 117 |
+
if labels is not None:
|
| 118 |
+
if self.num_labels == 1:
|
| 119 |
+
# We are doing regression
|
| 120 |
+
loss_fct = MSELoss()
|
| 121 |
+
loss = loss_fct(logits.view(-1), labels.view(-1))
|
| 122 |
+
else:
|
| 123 |
+
loss_fct = CrossEntropyLoss()
|
| 124 |
+
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
|
| 125 |
+
|
| 126 |
+
# work with highway exits
|
| 127 |
+
highway_losses = []
|
| 128 |
+
for highway_exit in outputs[-1]:
|
| 129 |
+
highway_logits = highway_exit[0]
|
| 130 |
+
if not self.training:
|
| 131 |
+
highway_logits_all.append(highway_logits)
|
| 132 |
+
highway_entropy.append(highway_exit[2])
|
| 133 |
+
if self.num_labels == 1:
|
| 134 |
+
# We are doing regression
|
| 135 |
+
loss_fct = MSELoss()
|
| 136 |
+
highway_loss = loss_fct(highway_logits.view(-1), labels.view(-1))
|
| 137 |
+
else:
|
| 138 |
+
loss_fct = CrossEntropyLoss()
|
| 139 |
+
highway_loss = loss_fct(highway_logits.view(-1, self.num_labels), labels.view(-1))
|
| 140 |
+
highway_losses.append(highway_loss)
|
| 141 |
+
|
| 142 |
+
if train_highway:
|
| 143 |
+
outputs = (sum(highway_losses[:-1]),) + outputs
|
| 144 |
+
# exclude the final highway, of course
|
| 145 |
+
else:
|
| 146 |
+
outputs = (loss,) + outputs
|
| 147 |
+
if not self.training:
|
| 148 |
+
outputs = outputs + ((original_entropy, highway_entropy), exit_layer)
|
| 149 |
+
if output_layer >= 0:
|
| 150 |
+
outputs = (
|
| 151 |
+
(outputs[0],) + (highway_logits_all[output_layer],) + outputs[2:]
|
| 152 |
+
) # use the highway of the last layer
|
| 153 |
+
|
| 154 |
+
return outputs # (loss), logits, (hidden_states), (attentions), entropy
|
tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/deebert/test_glue_deebert.py
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import logging
|
| 3 |
+
import sys
|
| 4 |
+
from unittest.mock import patch
|
| 5 |
+
|
| 6 |
+
import run_glue_deebert
|
| 7 |
+
|
| 8 |
+
from transformers.testing_utils import TestCasePlus, get_gpu_count, require_torch_non_multi_gpu, slow
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
logging.basicConfig(level=logging.DEBUG)
|
| 12 |
+
|
| 13 |
+
logger = logging.getLogger()
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def get_setup_file():
|
| 17 |
+
parser = argparse.ArgumentParser()
|
| 18 |
+
parser.add_argument("-f")
|
| 19 |
+
args = parser.parse_args()
|
| 20 |
+
return args.f
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class DeeBertTests(TestCasePlus):
|
| 24 |
+
def setup(self) -> None:
|
| 25 |
+
stream_handler = logging.StreamHandler(sys.stdout)
|
| 26 |
+
logger.addHandler(stream_handler)
|
| 27 |
+
|
| 28 |
+
def run_and_check(self, args):
|
| 29 |
+
n_gpu = get_gpu_count()
|
| 30 |
+
|
| 31 |
+
if n_gpu > 1:
|
| 32 |
+
pass
|
| 33 |
+
# XXX: doesn't quite work with n_gpu > 1 https://github.com/huggingface/transformers/issues/10560
|
| 34 |
+
# script = f"{self.examples_dir_str}/research_projects/deebert/run_glue_deebert.py"
|
| 35 |
+
# distributed_args = f"-m torch.distributed.launch --nproc_per_node={n_gpu} {script}".split()
|
| 36 |
+
# cmd = [sys.executable] + distributed_args + args
|
| 37 |
+
# execute_subprocess_async(cmd, env=self.get_env())
|
| 38 |
+
# XXX: test the results - need to save them first into .json file
|
| 39 |
+
else:
|
| 40 |
+
args.insert(0, "run_glue_deebert.py")
|
| 41 |
+
with patch.object(sys, "argv", args):
|
| 42 |
+
result = run_glue_deebert.main()
|
| 43 |
+
for value in result.values():
|
| 44 |
+
self.assertGreaterEqual(value, 0.666)
|
| 45 |
+
|
| 46 |
+
@slow
|
| 47 |
+
@require_torch_non_multi_gpu
|
| 48 |
+
def test_glue_deebert_train(self):
|
| 49 |
+
train_args = """
|
| 50 |
+
--model_type roberta
|
| 51 |
+
--model_name_or_path FacebookAI/roberta-base
|
| 52 |
+
--task_name MRPC
|
| 53 |
+
--do_train
|
| 54 |
+
--do_eval
|
| 55 |
+
--do_lower_case
|
| 56 |
+
--data_dir ./tests/fixtures/tests_samples/MRPC/
|
| 57 |
+
--max_seq_length 128
|
| 58 |
+
--per_gpu_eval_batch_size=1
|
| 59 |
+
--per_gpu_train_batch_size=8
|
| 60 |
+
--learning_rate 2e-4
|
| 61 |
+
--num_train_epochs 3
|
| 62 |
+
--overwrite_output_dir
|
| 63 |
+
--seed 42
|
| 64 |
+
--output_dir ./examples/deebert/saved_models/FacebookAI/roberta-base/MRPC/two_stage
|
| 65 |
+
--plot_data_dir ./examples/deebert/results/
|
| 66 |
+
--save_steps 0
|
| 67 |
+
--overwrite_cache
|
| 68 |
+
--eval_after_first_stage
|
| 69 |
+
""".split()
|
| 70 |
+
self.run_and_check(train_args)
|
| 71 |
+
|
| 72 |
+
eval_args = """
|
| 73 |
+
--model_type roberta
|
| 74 |
+
--model_name_or_path ./examples/deebert/saved_models/FacebookAI/roberta-base/MRPC/two_stage
|
| 75 |
+
--task_name MRPC
|
| 76 |
+
--do_eval
|
| 77 |
+
--do_lower_case
|
| 78 |
+
--data_dir ./tests/fixtures/tests_samples/MRPC/
|
| 79 |
+
--output_dir ./examples/deebert/saved_models/FacebookAI/roberta-base/MRPC/two_stage
|
| 80 |
+
--plot_data_dir ./examples/deebert/results/
|
| 81 |
+
--max_seq_length 128
|
| 82 |
+
--eval_each_highway
|
| 83 |
+
--eval_highway
|
| 84 |
+
--overwrite_cache
|
| 85 |
+
--per_gpu_eval_batch_size=1
|
| 86 |
+
""".split()
|
| 87 |
+
self.run_and_check(eval_args)
|
| 88 |
+
|
| 89 |
+
entropy_eval_args = """
|
| 90 |
+
--model_type roberta
|
| 91 |
+
--model_name_or_path ./examples/deebert/saved_models/FacebookAI/roberta-base/MRPC/two_stage
|
| 92 |
+
--task_name MRPC
|
| 93 |
+
--do_eval
|
| 94 |
+
--do_lower_case
|
| 95 |
+
--data_dir ./tests/fixtures/tests_samples/MRPC/
|
| 96 |
+
--output_dir ./examples/deebert/saved_models/FacebookAI/roberta-base/MRPC/two_stage
|
| 97 |
+
--plot_data_dir ./examples/deebert/results/
|
| 98 |
+
--max_seq_length 128
|
| 99 |
+
--early_exit_entropy 0.1
|
| 100 |
+
--eval_highway
|
| 101 |
+
--overwrite_cache
|
| 102 |
+
--per_gpu_eval_batch_size=1
|
| 103 |
+
""".split()
|
| 104 |
+
self.run_and_check(entropy_eval_args)
|
tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/deebert/train_deebert.sh
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
export CUDA_VISIBLE_DEVICES=0
|
| 3 |
+
|
| 4 |
+
PATH_TO_DATA=/h/xinji/projects/GLUE
|
| 5 |
+
|
| 6 |
+
MODEL_TYPE=bert # bert or roberta
|
| 7 |
+
MODEL_SIZE=base # base or large
|
| 8 |
+
DATASET=MRPC # SST-2, MRPC, RTE, QNLI, QQP, or MNLI
|
| 9 |
+
|
| 10 |
+
MODEL_NAME=${MODEL_TYPE}-${MODEL_SIZE}
|
| 11 |
+
EPOCHS=10
|
| 12 |
+
if [ $MODEL_TYPE = 'bert' ]
|
| 13 |
+
then
|
| 14 |
+
EPOCHS=3
|
| 15 |
+
MODEL_NAME=${MODEL_NAME}-uncased
|
| 16 |
+
fi
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
python -u run_glue_deebert.py \
|
| 20 |
+
--model_type $MODEL_TYPE \
|
| 21 |
+
--model_name_or_path $MODEL_NAME \
|
| 22 |
+
--task_name $DATASET \
|
| 23 |
+
--do_train \
|
| 24 |
+
--do_eval \
|
| 25 |
+
--do_lower_case \
|
| 26 |
+
--data_dir $PATH_TO_DATA/$DATASET \
|
| 27 |
+
--max_seq_length 128 \
|
| 28 |
+
--per_gpu_eval_batch_size=1 \
|
| 29 |
+
--per_gpu_train_batch_size=8 \
|
| 30 |
+
--learning_rate 2e-5 \
|
| 31 |
+
--num_train_epochs $EPOCHS \
|
| 32 |
+
--overwrite_output_dir \
|
| 33 |
+
--seed 42 \
|
| 34 |
+
--output_dir ./saved_models/${MODEL_TYPE}-${MODEL_SIZE}/$DATASET/two_stage \
|
| 35 |
+
--plot_data_dir ./results/ \
|
| 36 |
+
--save_steps 0 \
|
| 37 |
+
--overwrite_cache \
|
| 38 |
+
--eval_after_first_stage
|
tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/distillation/README.md
ADDED
|
@@ -0,0 +1,193 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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istilBERT, DistilRoBERTa and DistilGPT2.
|
| 6 |
+
|
| 7 |
+
**January 20, 2020 - Bug fixing** We have recently discovered and fixed [a bug](https://github.com/huggingface/transformers/commit/48cbf267c988b56c71a2380f748a3e6092ccaed3) in the evaluation of our `run_*.py` scripts that caused the reported metrics to be over-estimated on average. We have updated all the metrics with the latest runs.
|
| 8 |
+
|
| 9 |
+
**December 6, 2019 - Update** We release **DistilmBERT**: 92% of `bert-base-multilingual-cased` on XNLI. The model supports 104 different languages listed [here](https://github.com/google-research/bert/blob/master/multilingual.md#list-of-languages).
|
| 10 |
+
|
| 11 |
+
**November 19, 2019 - Update** We release German **DistilBERT**: 98.8% of `bert-base-german-dbmdz-cased` on NER tasks.
|
| 12 |
+
|
| 13 |
+
**October 23, 2019 - Update** We release **DistilRoBERTa**: 95% of `RoBERTa-base`'s performance on GLUE, twice as fast as RoBERTa while being 35% smaller.
|
| 14 |
+
|
| 15 |
+
**October 3, 2019 - Update** We release our [NeurIPS workshop paper](https://arxiv.org/abs/1910.01108) explaining our approach on **DistilBERT**. It includes updated results and further experiments. We applied the same method to GPT2 and release the weights of **DistilGPT2**. DistilGPT2 is two times faster and 33% smaller than GPT2. **The paper supersedes our [previous blogpost](https://medium.com/huggingface/distilbert-8cf3380435b5) with a different distillation loss and better performances. Please use the paper as a reference when comparing/reporting results on DistilBERT.**
|
| 16 |
+
|
| 17 |
+
**September 19, 2019 - Update:** We fixed bugs in the code and released an updated version of the weights trained with a modification of the distillation loss. DistilBERT now reaches 99% of `BERT-base`'s performance on GLUE, and 86.9 F1 score on SQuAD v1.1 dev set (compared to 88.5 for `BERT-base`). We will publish a formal write-up of our approach in the near future!
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
## What is Distil*
|
| 21 |
+
|
| 22 |
+
Distil* is a class of compressed models that started with DistilBERT. DistilBERT stands for Distilled-BERT. DistilBERT is a small, fast, cheap and light Transformer model based on Bert architecture. It has 40% less parameters than `bert-base-uncased`, runs 60% faster while preserving 97% of BERT's performances as measured on the GLUE language understanding benchmark. DistilBERT is trained using knowledge distillation, a technique to compress a large model called the teacher into a smaller model called the student. By distillating Bert, we obtain a smaller Transformer model that bears a lot of similarities with the original BERT model while being lighter, smaller and faster to run. DistilBERT is thus an interesting option to put large-scaled trained Transformer model into production.
|
| 23 |
+
|
| 24 |
+
We have applied the same method to other Transformer architectures and released the weights:
|
| 25 |
+
- GPT2: on the [WikiText-103](https://blog.einstein.ai/the-wikitext-long-term-dependency-language-modeling-dataset/) benchmark, GPT2 reaches a perplexity on the test set of 16.3 compared to 21.1 for **DistilGPT2** (after fine-tuning on the train set).
|
| 26 |
+
- RoBERTa: **DistilRoBERTa** reaches 95% of `RoBERTa-base`'s performance on GLUE while being twice faster and 35% smaller.
|
| 27 |
+
- German BERT: **German DistilBERT** reaches 99% of `bert-base-german-dbmdz-cased`'s performance on German NER (CoNLL-2003).
|
| 28 |
+
- Multilingual BERT: **DistilmBERT** reaches 92% of Multilingual BERT's performance on XNLI while being twice faster and 25% smaller. The model supports 104 languages listed [here](https://github.com/google-research/bert/blob/master/multilingual.md#list-of-languages).
|
| 29 |
+
|
| 30 |
+
For more information on DistilBERT, please refer to our [NeurIPS workshop paper](https://arxiv.org/abs/1910.01108).
|
| 31 |
+
|
| 32 |
+
Here are the results on the dev sets of GLUE:
|
| 33 |
+
|
| 34 |
+
| Model | Macro-score | CoLA | MNLI | MRPC | QNLI | QQP | RTE | SST-2| STS-B| WNLI |
|
| 35 |
+
| :---: | :---: | :---:| :---:| :---:| :---:| :---:| :---:| :---:| :---:| :---: |
|
| 36 |
+
| BERT-base-uncased | **79.5** | 56.3 | 84.7 | 88.6 | 91.8 | 89.6 | 69.3 | 92.7 | 89.0 | 53.5 |
|
| 37 |
+
| DistilBERT-base-uncased | **77.0** | 51.3 | 82.1 | 87.5 | 89.2 | 88.5 | 59.9 | 91.3 | 86.9 | 56.3 |
|
| 38 |
+
| BERT-base-cased | **78.2** | 58.2 | 83.9 | 87.8 | 91.0 | 89.2 | 66.1 | 91.7 | 89.2 | 46.5 |
|
| 39 |
+
| DistilBERT-base-cased | **75.9** | 47.2 | 81.5 | 85.6 | 88.2 | 87.8 | 60.6 | 90.4 | 85.5 | 56.3 |
|
| 40 |
+
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
| 41 |
+
| RoBERTa-base (reported) | **83.2**/**86.4**<sup>2</sup> | 63.6 | 87.6 | 90.2 | 92.8 | 91.9 | 78.7 | 94.8 | 91.2 | 57.7<sup>3</sup> |
|
| 42 |
+
| DistilRoBERTa<sup>1</sup> | **79.0**/**82.3**<sup>2</sup> | 59.3 | 84.0 | 86.6 | 90.8 | 89.4 | 67.9 | 92.5 | 88.3 | 52.1 |
|
| 43 |
+
|
| 44 |
+
<sup>1</sup> We did not use the MNLI checkpoint for fine-tuning but directly perform transfer learning on the pre-trained DistilRoBERTa.
|
| 45 |
+
|
| 46 |
+
<sup>2</sup> Macro-score computed without WNLI.
|
| 47 |
+
|
| 48 |
+
<sup>3</sup> We compute this score ourselves for completeness.
|
| 49 |
+
|
| 50 |
+
Here are the results on the *test* sets for 6 of the languages available in XNLI. The results are computed in the zero shot setting (trained on the English portion and evaluated on the target language portion):
|
| 51 |
+
|
| 52 |
+
| Model | English | Spanish | Chinese | German | Arabic | Urdu |
|
| 53 |
+
| :---: | :---: | :---: | :---: | :---: | :---: | :---:|
|
| 54 |
+
| mBERT base cased (computed) | 82.1 | 74.6 | 69.1 | 72.3 | 66.4 | 58.5 |
|
| 55 |
+
| mBERT base uncased (reported)| 81.4 | 74.3 | 63.8 | 70.5 | 62.1 | 58.3 |
|
| 56 |
+
| DistilmBERT | 78.2 | 69.1 | 64.0 | 66.3 | 59.1 | 54.7 |
|
| 57 |
+
|
| 58 |
+
## Setup
|
| 59 |
+
|
| 60 |
+
This part of the library has only be tested with Python3.6+. There are few specific dependencies to install before launching a distillation, you can install them with the command `pip install -r requirements.txt`.
|
| 61 |
+
|
| 62 |
+
**Important note:** The training scripts have been updated to support PyTorch v1.2.0 (there are breaking changes compared to v1.1.0).
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
## How to use DistilBERT
|
| 66 |
+
|
| 67 |
+
Transformers includes five pre-trained Distil* models, currently only provided for English and German (we are investigating the possibility to train and release a multilingual version of DistilBERT):
|
| 68 |
+
|
| 69 |
+
- `distilbert-base-uncased`: DistilBERT English language model pretrained on the same data used to pretrain Bert (concatenation of the Toronto Book Corpus and full English Wikipedia) using distillation with the supervision of the `bert-base-uncased` version of Bert. The model has 6 layers, 768 dimension and 12 heads, totalizing 66M parameters.
|
| 70 |
+
- `distilbert-base-uncased-distilled-squad`: A finetuned version of `distilbert-base-uncased` finetuned using (a second step of) knowledge distillation on SQuAD 1.0. This model reaches a F1 score of 86.9 on the dev set (for comparison, Bert `bert-base-uncased` version reaches a 88.5 F1 score).
|
| 71 |
+
- `distilbert-base-cased`: DistilBERT English language model pretrained on the same data used to pretrain Bert (concatenation of the Toronto Book Corpus and full English Wikipedia) using distillation with the supervision of the `bert-base-cased` version of Bert. The model has 6 layers, 768 dimension and 12 heads, totalizing 65M parameters.
|
| 72 |
+
- `distilbert-base-cased-distilled-squad`: A finetuned version of `distilbert-base-cased` finetuned using (a second step of) knowledge distillation on SQuAD 1.0. This model reaches a F1 score of 87.1 on the dev set (for comparison, Bert `bert-base-cased` version reaches a 88.7 F1 score).
|
| 73 |
+
- `distilbert-base-german-cased`: DistilBERT German language model pretrained on 1/2 of the data used to pretrain Bert using distillation with the supervision of the `bert-base-german-dbmdz-cased` version of German DBMDZ Bert. For NER tasks the model reaches a F1 score of 83.49 on the CoNLL-2003 test set (for comparison, `bert-base-german-dbmdz-cased` reaches a 84.52 F1 score), and a F1 score of 85.23 on the GermEval 2014 test set (`bert-base-german-dbmdz-cased` reaches a 86.89 F1 score).
|
| 74 |
+
- `distilgpt2`: DistilGPT2 English language model pretrained with the supervision of `gpt2` (the smallest version of GPT2) on [OpenWebTextCorpus](https://skylion007.github.io/OpenWebTextCorpus/), a reproduction of OpenAI's WebText dataset. The model has 6 layers, 768 dimension and 12 heads, totalizing 82M parameters (compared to 124M parameters for GPT2). On average, DistilGPT2 is two times faster than GPT2.
|
| 75 |
+
- `distilroberta-base`: DistilRoBERTa English language model pretrained with the supervision of `roberta-base` solely on [OpenWebTextCorpus](https://skylion007.github.io/OpenWebTextCorpus/), a reproduction of OpenAI's WebText dataset (it is ~4 times less training data than the teacher RoBERTa). The model has 6 layers, 768 dimension and 12 heads, totalizing 82M parameters (compared to 125M parameters for RoBERTa-base). On average DistilRoBERTa is twice as fast as Roberta-base.
|
| 76 |
+
- `distilbert-base-multilingual-cased`: DistilmBERT multilingual model pretrained with the supervision of `bert-base-multilingual-cased` on the concatenation of Wikipedia in 104 different languages. The model supports the 104 languages listed [here](https://github.com/google-research/bert/blob/master/multilingual.md#list-of-languages). The model has 6 layers, 768 dimension and 12 heads, totalizing 134M parameters (compared to 177M parameters for mBERT-base). On average DistilmBERT is twice as fast as mBERT-base.
|
| 77 |
+
|
| 78 |
+
Using DistilBERT is very similar to using BERT. DistilBERT share the same tokenizer as BERT's `bert-base-uncased` even though we provide a link to this tokenizer under the `DistilBertTokenizer` name to have a consistent naming between the library models.
|
| 79 |
+
|
| 80 |
+
```python
|
| 81 |
+
tokenizer = DistilBertTokenizer.from_pretrained('distilbert-base-cased')
|
| 82 |
+
model = DistilBertModel.from_pretrained('distilbert-base-cased')
|
| 83 |
+
|
| 84 |
+
input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute")).unsqueeze(0)
|
| 85 |
+
outputs = model(input_ids)
|
| 86 |
+
last_hidden_states = outputs[0] # The last hidden-state is the first element of the output tuple
|
| 87 |
+
```
|
| 88 |
+
|
| 89 |
+
Similarly, using the other Distil* models simply consists in calling the base classes with a different pretrained checkpoint:
|
| 90 |
+
- DistilBERT uncased: `model = DistilBertModel.from_pretrained('distilbert-base-uncased')`
|
| 91 |
+
- DistilGPT2: `model = GPT2Model.from_pretrained('distilgpt2')`
|
| 92 |
+
- DistilRoBERTa: `model = RobertaModel.from_pretrained('distilroberta-base')`
|
| 93 |
+
- DistilmBERT: `model = DistilBertModel.from_pretrained('distilbert-base-multilingual-cased')`
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
## How to train Distil*
|
| 97 |
+
|
| 98 |
+
In the following, we will explain how you can train DistilBERT.
|
| 99 |
+
|
| 100 |
+
### A. Preparing the data
|
| 101 |
+
|
| 102 |
+
The weights we release are trained using a concatenation of Toronto Book Corpus and English Wikipedia (same training data as the English version of BERT).
|
| 103 |
+
|
| 104 |
+
To avoid processing the data several time, we do it once and for all before the training. From now on, will suppose that you have a text file `dump.txt` which contains one sequence per line (a sequence being composed of one of several coherent sentences).
|
| 105 |
+
|
| 106 |
+
First, we will binarize the data, i.e. tokenize the data and convert each token in an index in our model's vocabulary.
|
| 107 |
+
|
| 108 |
+
```bash
|
| 109 |
+
python scripts/binarized_data.py \
|
| 110 |
+
--file_path data/dump.txt \
|
| 111 |
+
--tokenizer_type bert \
|
| 112 |
+
--tokenizer_name bert-base-uncased \
|
| 113 |
+
--dump_file data/binarized_text
|
| 114 |
+
```
|
| 115 |
+
|
| 116 |
+
Our implementation of masked language modeling loss follows [XLM](https://github.com/facebookresearch/XLM)'s one and smooths the probability of masking with a factor that put more emphasis on rare words. Thus we count the occurrences of each tokens in the data:
|
| 117 |
+
|
| 118 |
+
```bash
|
| 119 |
+
python scripts/token_counts.py \
|
| 120 |
+
--data_file data/binarized_text.bert-base-uncased.pickle \
|
| 121 |
+
--token_counts_dump data/token_counts.bert-base-uncased.pickle \
|
| 122 |
+
--vocab_size 30522
|
| 123 |
+
```
|
| 124 |
+
|
| 125 |
+
### B. Training
|
| 126 |
+
|
| 127 |
+
Training with distillation is really simple once you have pre-processed the data:
|
| 128 |
+
|
| 129 |
+
```bash
|
| 130 |
+
python train.py \
|
| 131 |
+
--student_type distilbert \
|
| 132 |
+
--student_config training_configs/distilbert-base-uncased.json \
|
| 133 |
+
--teacher_type bert \
|
| 134 |
+
--teacher_name bert-base-uncased \
|
| 135 |
+
--alpha_ce 5.0 --alpha_mlm 2.0 --alpha_cos 1.0 --alpha_clm 0.0 --mlm \
|
| 136 |
+
--freeze_pos_embs \
|
| 137 |
+
--dump_path serialization_dir/my_first_training \
|
| 138 |
+
--data_file data/binarized_text.bert-base-uncased.pickle \
|
| 139 |
+
--token_counts data/token_counts.bert-base-uncased.pickle \
|
| 140 |
+
--force # overwrites the `dump_path` if it already exists.
|
| 141 |
+
```
|
| 142 |
+
|
| 143 |
+
By default, this will launch a training on a single GPU (even if more are available on the cluster). Other parameters are available in the command line, please look in `train.py` or run `python train.py --help` to list them.
|
| 144 |
+
|
| 145 |
+
We highly encourage you to use distributed training for training DistilBERT as the training corpus is quite large. Here's an example that runs a distributed training on a single node having 4 GPUs:
|
| 146 |
+
|
| 147 |
+
```bash
|
| 148 |
+
export NODE_RANK=0
|
| 149 |
+
export N_NODES=1
|
| 150 |
+
|
| 151 |
+
export N_GPU_NODE=4
|
| 152 |
+
export WORLD_SIZE=4
|
| 153 |
+
export MASTER_PORT=<AN_OPEN_PORT>
|
| 154 |
+
export MASTER_ADDR=<I.P.>
|
| 155 |
+
|
| 156 |
+
pkill -f 'python -u train.py'
|
| 157 |
+
|
| 158 |
+
python -m torch.distributed.launch \
|
| 159 |
+
--nproc_per_node=$N_GPU_NODE \
|
| 160 |
+
--nnodes=$N_NODES \
|
| 161 |
+
--node_rank $NODE_RANK \
|
| 162 |
+
--master_addr $MASTER_ADDR \
|
| 163 |
+
--master_port $MASTER_PORT \
|
| 164 |
+
train.py \
|
| 165 |
+
--force \
|
| 166 |
+
--n_gpu $WORLD_SIZE \
|
| 167 |
+
--student_type distilbert \
|
| 168 |
+
--student_config training_configs/distilbert-base-uncased.json \
|
| 169 |
+
--teacher_type bert \
|
| 170 |
+
--teacher_name bert-base-uncased \
|
| 171 |
+
--alpha_ce 0.33 --alpha_mlm 0.33 --alpha_cos 0.33 --alpha_clm 0.0 --mlm \
|
| 172 |
+
--freeze_pos_embs \
|
| 173 |
+
--dump_path serialization_dir/my_first_training \
|
| 174 |
+
--data_file data/binarized_text.bert-base-uncased.pickle \
|
| 175 |
+
--token_counts data/token_counts.bert-base-uncased.pickle
|
| 176 |
+
```
|
| 177 |
+
|
| 178 |
+
**Tips:** Starting distilled training with good initialization of the model weights is crucial to reach decent performance. In our experiments, we initialized our model from a few layers of the teacher (Bert) itself! Please refer to `scripts/extract.py` and `scripts/extract_distilbert.py` to create a valid initialization checkpoint and use `--student_pretrained_weights` argument to use this initialization for the distilled training!
|
| 179 |
+
|
| 180 |
+
Happy distillation!
|
| 181 |
+
|
| 182 |
+
## Citation
|
| 183 |
+
|
| 184 |
+
If you find the resource useful, you should cite the following paper:
|
| 185 |
+
|
| 186 |
+
```bibtex
|
| 187 |
+
@inproceedings{sanh2019distilbert,
|
| 188 |
+
title={DistilBERT, a distilled version of BERT: smaller, faster, cheaper and lighter},
|
| 189 |
+
author={Sanh, Victor and Debut, Lysandre and Chaumond, Julien and Wolf, Thomas},
|
| 190 |
+
booktitle={NeurIPS EMC^2 Workshop},
|
| 191 |
+
year={2019}
|
| 192 |
+
}
|
| 193 |
+
```
|
tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/distillation/distiller.py
ADDED
|
@@ -0,0 +1,601 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2019-present, the HuggingFace Inc. team and Facebook, Inc.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""The distiller to distil the student.
|
| 16 |
+
Adapted in part from Facebook, Inc XLM model (https://github.com/facebookresearch/XLM)
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
import math
|
| 20 |
+
import os
|
| 21 |
+
import time
|
| 22 |
+
|
| 23 |
+
import psutil
|
| 24 |
+
import torch
|
| 25 |
+
from grouped_batch_sampler import GroupedBatchSampler, create_lengths_groups
|
| 26 |
+
from lm_seqs_dataset import LmSeqsDataset
|
| 27 |
+
from torch import nn
|
| 28 |
+
from torch.optim import AdamW
|
| 29 |
+
from torch.utils.data import BatchSampler, DataLoader, RandomSampler
|
| 30 |
+
from torch.utils.data.distributed import DistributedSampler
|
| 31 |
+
from tqdm import tqdm
|
| 32 |
+
|
| 33 |
+
from transformers import get_linear_schedule_with_warmup
|
| 34 |
+
from utils import logger
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
try:
|
| 38 |
+
from torch.utils.tensorboard import SummaryWriter
|
| 39 |
+
except ImportError:
|
| 40 |
+
from tensorboardX import SummaryWriter
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class Distiller:
|
| 44 |
+
def __init__(
|
| 45 |
+
self, params: dict, dataset: LmSeqsDataset, token_probs: torch.tensor, student: nn.Module, teacher: nn.Module
|
| 46 |
+
):
|
| 47 |
+
logger.info("Initializing Distiller")
|
| 48 |
+
self.params = params
|
| 49 |
+
self.dump_path = params.dump_path
|
| 50 |
+
self.multi_gpu = params.multi_gpu
|
| 51 |
+
self.fp16 = params.fp16
|
| 52 |
+
|
| 53 |
+
self.student = student
|
| 54 |
+
self.teacher = teacher
|
| 55 |
+
|
| 56 |
+
self.student_config = student.config
|
| 57 |
+
self.vocab_size = student.config.vocab_size
|
| 58 |
+
|
| 59 |
+
if params.n_gpu <= 1:
|
| 60 |
+
sampler = RandomSampler(dataset)
|
| 61 |
+
else:
|
| 62 |
+
sampler = DistributedSampler(dataset)
|
| 63 |
+
|
| 64 |
+
if params.group_by_size:
|
| 65 |
+
groups = create_lengths_groups(lengths=dataset.lengths, k=params.max_model_input_size)
|
| 66 |
+
sampler = GroupedBatchSampler(sampler=sampler, group_ids=groups, batch_size=params.batch_size)
|
| 67 |
+
else:
|
| 68 |
+
sampler = BatchSampler(sampler=sampler, batch_size=params.batch_size, drop_last=False)
|
| 69 |
+
|
| 70 |
+
self.dataloader = DataLoader(dataset=dataset, batch_sampler=sampler, collate_fn=dataset.batch_sequences)
|
| 71 |
+
|
| 72 |
+
self.temperature = params.temperature
|
| 73 |
+
assert self.temperature > 0.0
|
| 74 |
+
|
| 75 |
+
self.alpha_ce = params.alpha_ce
|
| 76 |
+
self.alpha_mlm = params.alpha_mlm
|
| 77 |
+
self.alpha_clm = params.alpha_clm
|
| 78 |
+
self.alpha_mse = params.alpha_mse
|
| 79 |
+
self.alpha_cos = params.alpha_cos
|
| 80 |
+
|
| 81 |
+
self.mlm = params.mlm
|
| 82 |
+
if self.mlm:
|
| 83 |
+
logger.info("Using MLM loss for LM step.")
|
| 84 |
+
self.mlm_mask_prop = params.mlm_mask_prop
|
| 85 |
+
assert 0.0 <= self.mlm_mask_prop <= 1.0
|
| 86 |
+
assert params.word_mask + params.word_keep + params.word_rand == 1.0
|
| 87 |
+
self.pred_probs = torch.FloatTensor([params.word_mask, params.word_keep, params.word_rand])
|
| 88 |
+
self.pred_probs = self.pred_probs.to(f"cuda:{params.local_rank}") if params.n_gpu > 0 else self.pred_probs
|
| 89 |
+
self.token_probs = token_probs.to(f"cuda:{params.local_rank}") if params.n_gpu > 0 else token_probs
|
| 90 |
+
if self.fp16:
|
| 91 |
+
self.pred_probs = self.pred_probs.half()
|
| 92 |
+
self.token_probs = self.token_probs.half()
|
| 93 |
+
else:
|
| 94 |
+
logger.info("Using CLM loss for LM step.")
|
| 95 |
+
|
| 96 |
+
self.epoch = 0
|
| 97 |
+
self.n_iter = 0
|
| 98 |
+
self.n_total_iter = 0
|
| 99 |
+
self.n_sequences_epoch = 0
|
| 100 |
+
self.total_loss_epoch = 0
|
| 101 |
+
self.last_loss = 0
|
| 102 |
+
self.last_loss_ce = 0
|
| 103 |
+
self.last_loss_mlm = 0
|
| 104 |
+
self.last_loss_clm = 0
|
| 105 |
+
if self.alpha_mse > 0.0:
|
| 106 |
+
self.last_loss_mse = 0
|
| 107 |
+
if self.alpha_cos > 0.0:
|
| 108 |
+
self.last_loss_cos = 0
|
| 109 |
+
self.last_log = 0
|
| 110 |
+
|
| 111 |
+
self.ce_loss_fct = nn.KLDivLoss(reduction="batchmean")
|
| 112 |
+
self.lm_loss_fct = nn.CrossEntropyLoss(ignore_index=-100)
|
| 113 |
+
if self.alpha_mse > 0.0:
|
| 114 |
+
self.mse_loss_fct = nn.MSELoss(reduction="sum")
|
| 115 |
+
if self.alpha_cos > 0.0:
|
| 116 |
+
self.cosine_loss_fct = nn.CosineEmbeddingLoss(reduction="mean")
|
| 117 |
+
|
| 118 |
+
logger.info("--- Initializing model optimizer")
|
| 119 |
+
assert params.gradient_accumulation_steps >= 1
|
| 120 |
+
self.num_steps_epoch = len(self.dataloader)
|
| 121 |
+
num_train_optimization_steps = (
|
| 122 |
+
int(self.num_steps_epoch / params.gradient_accumulation_steps * params.n_epoch) + 1
|
| 123 |
+
)
|
| 124 |
+
|
| 125 |
+
no_decay = ["bias", "LayerNorm.weight"]
|
| 126 |
+
optimizer_grouped_parameters = [
|
| 127 |
+
{
|
| 128 |
+
"params": [
|
| 129 |
+
p for n, p in student.named_parameters() if not any(nd in n for nd in no_decay) and p.requires_grad
|
| 130 |
+
],
|
| 131 |
+
"weight_decay": params.weight_decay,
|
| 132 |
+
},
|
| 133 |
+
{
|
| 134 |
+
"params": [
|
| 135 |
+
p for n, p in student.named_parameters() if any(nd in n for nd in no_decay) and p.requires_grad
|
| 136 |
+
],
|
| 137 |
+
"weight_decay": 0.0,
|
| 138 |
+
},
|
| 139 |
+
]
|
| 140 |
+
logger.info(
|
| 141 |
+
"------ Number of trainable parameters (student): %i"
|
| 142 |
+
% sum([p.numel() for p in self.student.parameters() if p.requires_grad])
|
| 143 |
+
)
|
| 144 |
+
logger.info("------ Number of parameters (student): %i" % sum([p.numel() for p in self.student.parameters()]))
|
| 145 |
+
self.optimizer = AdamW(
|
| 146 |
+
optimizer_grouped_parameters, lr=params.learning_rate, eps=params.adam_epsilon, betas=(0.9, 0.98)
|
| 147 |
+
)
|
| 148 |
+
|
| 149 |
+
warmup_steps = math.ceil(num_train_optimization_steps * params.warmup_prop)
|
| 150 |
+
self.scheduler = get_linear_schedule_with_warmup(
|
| 151 |
+
self.optimizer, num_warmup_steps=warmup_steps, num_training_steps=num_train_optimization_steps
|
| 152 |
+
)
|
| 153 |
+
|
| 154 |
+
if self.fp16:
|
| 155 |
+
try:
|
| 156 |
+
from apex import amp
|
| 157 |
+
except ImportError:
|
| 158 |
+
raise ImportError("Please install apex from https://www.github.com/nvidia/apex to use fp16 training.")
|
| 159 |
+
logger.info(f"Using fp16 training: {self.params.fp16_opt_level} level")
|
| 160 |
+
self.student, self.optimizer = amp.initialize(
|
| 161 |
+
self.student, self.optimizer, opt_level=self.params.fp16_opt_level
|
| 162 |
+
)
|
| 163 |
+
self.teacher = self.teacher.half()
|
| 164 |
+
|
| 165 |
+
if self.multi_gpu:
|
| 166 |
+
if self.fp16:
|
| 167 |
+
from apex.parallel import DistributedDataParallel
|
| 168 |
+
|
| 169 |
+
logger.info("Using apex.parallel.DistributedDataParallel for distributed training.")
|
| 170 |
+
self.student = DistributedDataParallel(self.student)
|
| 171 |
+
else:
|
| 172 |
+
from torch.nn.parallel import DistributedDataParallel
|
| 173 |
+
|
| 174 |
+
logger.info("Using nn.parallel.DistributedDataParallel for distributed training.")
|
| 175 |
+
self.student = DistributedDataParallel(
|
| 176 |
+
self.student,
|
| 177 |
+
device_ids=[params.local_rank],
|
| 178 |
+
output_device=params.local_rank,
|
| 179 |
+
find_unused_parameters=True,
|
| 180 |
+
)
|
| 181 |
+
|
| 182 |
+
self.is_master = params.is_master
|
| 183 |
+
if self.is_master:
|
| 184 |
+
logger.info("--- Initializing Tensorboard")
|
| 185 |
+
self.tensorboard = SummaryWriter(log_dir=os.path.join(self.dump_path, "log", "train"))
|
| 186 |
+
self.tensorboard.add_text(tag="config/training", text_string=str(self.params), global_step=0)
|
| 187 |
+
self.tensorboard.add_text(tag="config/student", text_string=str(self.student_config), global_step=0)
|
| 188 |
+
|
| 189 |
+
def prepare_batch_mlm(self, batch):
|
| 190 |
+
"""
|
| 191 |
+
Prepare the batch: from the token_ids and the lengths, compute the attention mask and the masked label for MLM.
|
| 192 |
+
|
| 193 |
+
Input:
|
| 194 |
+
------
|
| 195 |
+
batch: `Tuple`
|
| 196 |
+
token_ids: `torch.tensor(bs, seq_length)` - The token ids for each of the sequence. It is padded.
|
| 197 |
+
lengths: `torch.tensor(bs)` - The lengths of each of the sequences in the batch.
|
| 198 |
+
|
| 199 |
+
Output:
|
| 200 |
+
-------
|
| 201 |
+
token_ids: `torch.tensor(bs, seq_length)` - The token ids after the modifications for MLM.
|
| 202 |
+
attn_mask: `torch.tensor(bs, seq_length)` - The attention mask for the self-attention.
|
| 203 |
+
mlm_labels: `torch.tensor(bs, seq_length)` - The masked language modeling labels. There is a -100 where there is nothing to predict.
|
| 204 |
+
"""
|
| 205 |
+
token_ids, lengths = batch
|
| 206 |
+
token_ids, lengths = self.round_batch(x=token_ids, lengths=lengths)
|
| 207 |
+
assert token_ids.size(0) == lengths.size(0)
|
| 208 |
+
|
| 209 |
+
attn_mask = torch.arange(token_ids.size(1), dtype=torch.long, device=lengths.device) < lengths[:, None]
|
| 210 |
+
|
| 211 |
+
bs, max_seq_len = token_ids.size()
|
| 212 |
+
mlm_labels = token_ids.new(token_ids.size()).copy_(token_ids)
|
| 213 |
+
|
| 214 |
+
x_prob = self.token_probs[token_ids.flatten()]
|
| 215 |
+
n_tgt = math.ceil(self.mlm_mask_prop * lengths.sum().item())
|
| 216 |
+
tgt_ids = torch.multinomial(x_prob / x_prob.sum(), n_tgt, replacement=False)
|
| 217 |
+
pred_mask = torch.zeros(
|
| 218 |
+
bs * max_seq_len, dtype=torch.bool, device=token_ids.device
|
| 219 |
+
) # previously `dtype=torch.uint8`, cf pytorch 1.2.0 compatibility
|
| 220 |
+
pred_mask[tgt_ids] = 1
|
| 221 |
+
pred_mask = pred_mask.view(bs, max_seq_len)
|
| 222 |
+
|
| 223 |
+
pred_mask[token_ids == self.params.special_tok_ids["pad_token"]] = 0
|
| 224 |
+
|
| 225 |
+
# mask a number of words == 0 [8] (faster with fp16)
|
| 226 |
+
if self.fp16:
|
| 227 |
+
n1 = pred_mask.sum().item()
|
| 228 |
+
if n1 > 8:
|
| 229 |
+
pred_mask = pred_mask.view(-1)
|
| 230 |
+
n2 = max(n1 % 8, 8 * (n1 // 8))
|
| 231 |
+
if n2 != n1:
|
| 232 |
+
pred_mask[torch.nonzero(pred_mask).view(-1)[: n1 - n2]] = 0
|
| 233 |
+
pred_mask = pred_mask.view(bs, max_seq_len)
|
| 234 |
+
assert pred_mask.sum().item() % 8 == 0, pred_mask.sum().item()
|
| 235 |
+
|
| 236 |
+
_token_ids_real = token_ids[pred_mask]
|
| 237 |
+
_token_ids_rand = _token_ids_real.clone().random_(self.vocab_size)
|
| 238 |
+
_token_ids_mask = _token_ids_real.clone().fill_(self.params.special_tok_ids["mask_token"])
|
| 239 |
+
probs = torch.multinomial(self.pred_probs, len(_token_ids_real), replacement=True)
|
| 240 |
+
_token_ids = (
|
| 241 |
+
_token_ids_mask * (probs == 0).long()
|
| 242 |
+
+ _token_ids_real * (probs == 1).long()
|
| 243 |
+
+ _token_ids_rand * (probs == 2).long()
|
| 244 |
+
)
|
| 245 |
+
token_ids = token_ids.masked_scatter(pred_mask, _token_ids)
|
| 246 |
+
|
| 247 |
+
mlm_labels[~pred_mask] = -100 # previously `mlm_labels[1-pred_mask] = -1`, cf pytorch 1.2.0 compatibility
|
| 248 |
+
|
| 249 |
+
# sanity checks
|
| 250 |
+
assert 0 <= token_ids.min() <= token_ids.max() < self.vocab_size
|
| 251 |
+
|
| 252 |
+
return token_ids, attn_mask, mlm_labels
|
| 253 |
+
|
| 254 |
+
def prepare_batch_clm(self, batch):
|
| 255 |
+
"""
|
| 256 |
+
Prepare the batch: from the token_ids and the lengths, compute the attention mask and the labels for CLM.
|
| 257 |
+
|
| 258 |
+
Input:
|
| 259 |
+
------
|
| 260 |
+
batch: `Tuple`
|
| 261 |
+
token_ids: `torch.tensor(bs, seq_length)` - The token ids for each of the sequence. It is padded.
|
| 262 |
+
lengths: `torch.tensor(bs)` - The lengths of each of the sequences in the batch.
|
| 263 |
+
|
| 264 |
+
Output:
|
| 265 |
+
-------
|
| 266 |
+
token_ids: `torch.tensor(bs, seq_length)` - The token ids after the modifications for MLM.
|
| 267 |
+
attn_mask: `torch.tensor(bs, seq_length)` - The attention mask for the self-attention.
|
| 268 |
+
clm_labels: `torch.tensor(bs, seq_length)` - The causal language modeling labels. There is a -100 where there is nothing to predict.
|
| 269 |
+
"""
|
| 270 |
+
token_ids, lengths = batch
|
| 271 |
+
token_ids, lengths = self.round_batch(x=token_ids, lengths=lengths)
|
| 272 |
+
assert token_ids.size(0) == lengths.size(0)
|
| 273 |
+
|
| 274 |
+
attn_mask = torch.arange(token_ids.size(1), dtype=torch.long, device=lengths.device) < lengths[:, None]
|
| 275 |
+
clm_labels = token_ids.new(token_ids.size()).copy_(token_ids)
|
| 276 |
+
clm_labels[~attn_mask] = -100 # previously `clm_labels[1-attn_mask] = -1`, cf pytorch 1.2.0 compatibility
|
| 277 |
+
|
| 278 |
+
# sanity checks
|
| 279 |
+
assert 0 <= token_ids.min() <= token_ids.max() < self.vocab_size
|
| 280 |
+
|
| 281 |
+
return token_ids, attn_mask, clm_labels
|
| 282 |
+
|
| 283 |
+
def round_batch(self, x: torch.tensor, lengths: torch.tensor):
|
| 284 |
+
"""
|
| 285 |
+
For float16 only.
|
| 286 |
+
Sub-sample sentences in a batch, and add padding, so that each dimension is a multiple of 8.
|
| 287 |
+
|
| 288 |
+
Input:
|
| 289 |
+
------
|
| 290 |
+
x: `torch.tensor(bs, seq_length)` - The token ids.
|
| 291 |
+
lengths: `torch.tensor(bs, seq_length)` - The lengths of each of the sequence in the batch.
|
| 292 |
+
|
| 293 |
+
Output:
|
| 294 |
+
-------
|
| 295 |
+
x: `torch.tensor(new_bs, new_seq_length)` - The updated token ids.
|
| 296 |
+
lengths: `torch.tensor(new_bs, new_seq_length)` - The updated lengths.
|
| 297 |
+
"""
|
| 298 |
+
if not self.fp16 or len(lengths) < 8:
|
| 299 |
+
return x, lengths
|
| 300 |
+
|
| 301 |
+
# number of sentences == 0 [8]
|
| 302 |
+
bs1 = len(lengths)
|
| 303 |
+
bs2 = 8 * (bs1 // 8)
|
| 304 |
+
assert bs2 > 0 and bs2 % 8 == 0
|
| 305 |
+
if bs1 != bs2:
|
| 306 |
+
idx = torch.randperm(bs1)[:bs2]
|
| 307 |
+
lengths = lengths[idx]
|
| 308 |
+
slen = lengths.max().item()
|
| 309 |
+
x = x[idx, :slen]
|
| 310 |
+
else:
|
| 311 |
+
idx = None
|
| 312 |
+
|
| 313 |
+
# sequence length == 0 [8]
|
| 314 |
+
ml1 = x.size(1)
|
| 315 |
+
if ml1 % 8 != 0:
|
| 316 |
+
pad = 8 - (ml1 % 8)
|
| 317 |
+
ml2 = ml1 + pad
|
| 318 |
+
if self.mlm:
|
| 319 |
+
pad_id = self.params.special_tok_ids["pad_token"]
|
| 320 |
+
else:
|
| 321 |
+
pad_id = self.params.special_tok_ids["unk_token"]
|
| 322 |
+
padding_tensor = torch.zeros(bs2, pad, dtype=torch.long, device=x.device).fill_(pad_id)
|
| 323 |
+
x = torch.cat([x, padding_tensor], 1)
|
| 324 |
+
assert x.size() == (bs2, ml2)
|
| 325 |
+
|
| 326 |
+
assert x.size(0) % 8 == 0
|
| 327 |
+
assert x.size(1) % 8 == 0
|
| 328 |
+
return x, lengths
|
| 329 |
+
|
| 330 |
+
def train(self):
|
| 331 |
+
"""
|
| 332 |
+
The real training loop.
|
| 333 |
+
"""
|
| 334 |
+
if self.is_master:
|
| 335 |
+
logger.info("Starting training")
|
| 336 |
+
self.last_log = time.time()
|
| 337 |
+
self.student.train()
|
| 338 |
+
self.teacher.eval()
|
| 339 |
+
|
| 340 |
+
for _ in range(self.params.n_epoch):
|
| 341 |
+
if self.is_master:
|
| 342 |
+
logger.info(f"--- Starting epoch {self.epoch}/{self.params.n_epoch-1}")
|
| 343 |
+
if self.multi_gpu:
|
| 344 |
+
torch.distributed.barrier()
|
| 345 |
+
|
| 346 |
+
iter_bar = tqdm(self.dataloader, desc="-Iter", disable=self.params.local_rank not in [-1, 0])
|
| 347 |
+
for batch in iter_bar:
|
| 348 |
+
if self.params.n_gpu > 0:
|
| 349 |
+
batch = tuple(t.to(f"cuda:{self.params.local_rank}") for t in batch)
|
| 350 |
+
|
| 351 |
+
if self.mlm:
|
| 352 |
+
token_ids, attn_mask, lm_labels = self.prepare_batch_mlm(batch=batch)
|
| 353 |
+
else:
|
| 354 |
+
token_ids, attn_mask, lm_labels = self.prepare_batch_clm(batch=batch)
|
| 355 |
+
self.step(input_ids=token_ids, attention_mask=attn_mask, lm_labels=lm_labels)
|
| 356 |
+
|
| 357 |
+
iter_bar.update()
|
| 358 |
+
iter_bar.set_postfix(
|
| 359 |
+
{"Last_loss": f"{self.last_loss:.2f}", "Avg_cum_loss": f"{self.total_loss_epoch/self.n_iter:.2f}"}
|
| 360 |
+
)
|
| 361 |
+
iter_bar.close()
|
| 362 |
+
|
| 363 |
+
if self.is_master:
|
| 364 |
+
logger.info(f"--- Ending epoch {self.epoch}/{self.params.n_epoch-1}")
|
| 365 |
+
self.end_epoch()
|
| 366 |
+
|
| 367 |
+
if self.is_master:
|
| 368 |
+
logger.info("Save very last checkpoint as `pytorch_model.bin`.")
|
| 369 |
+
self.save_checkpoint(checkpoint_name="pytorch_model.bin")
|
| 370 |
+
logger.info("Training is finished")
|
| 371 |
+
|
| 372 |
+
def step(self, input_ids: torch.tensor, attention_mask: torch.tensor, lm_labels: torch.tensor):
|
| 373 |
+
"""
|
| 374 |
+
One optimization step: forward of student AND teacher, backward on the loss (for gradient accumulation),
|
| 375 |
+
and possibly a parameter update (depending on the gradient accumulation).
|
| 376 |
+
|
| 377 |
+
Input:
|
| 378 |
+
------
|
| 379 |
+
input_ids: `torch.tensor(bs, seq_length)` - The token ids.
|
| 380 |
+
attention_mask: `torch.tensor(bs, seq_length)` - The attention mask for self attention.
|
| 381 |
+
lm_labels: `torch.tensor(bs, seq_length)` - The language modeling labels (mlm labels for MLM and clm labels for CLM).
|
| 382 |
+
"""
|
| 383 |
+
if self.mlm:
|
| 384 |
+
student_outputs = self.student(
|
| 385 |
+
input_ids=input_ids, attention_mask=attention_mask
|
| 386 |
+
) # (bs, seq_length, voc_size)
|
| 387 |
+
with torch.no_grad():
|
| 388 |
+
teacher_outputs = self.teacher(
|
| 389 |
+
input_ids=input_ids, attention_mask=attention_mask
|
| 390 |
+
) # (bs, seq_length, voc_size)
|
| 391 |
+
else:
|
| 392 |
+
student_outputs = self.student(input_ids=input_ids, attention_mask=None) # (bs, seq_length, voc_size)
|
| 393 |
+
with torch.no_grad():
|
| 394 |
+
teacher_outputs = self.teacher(input_ids=input_ids, attention_mask=None) # (bs, seq_length, voc_size)
|
| 395 |
+
s_logits, s_hidden_states = student_outputs["logits"], student_outputs["hidden_states"]
|
| 396 |
+
t_logits, t_hidden_states = teacher_outputs["logits"], teacher_outputs["hidden_states"]
|
| 397 |
+
assert s_logits.size() == t_logits.size()
|
| 398 |
+
|
| 399 |
+
# https://github.com/peterliht/knowledge-distillation-pytorch/blob/master/model/net.py#L100
|
| 400 |
+
# https://github.com/peterliht/knowledge-distillation-pytorch/issues/2
|
| 401 |
+
if self.params.restrict_ce_to_mask:
|
| 402 |
+
mask = (lm_labels > -1).unsqueeze(-1).expand_as(s_logits) # (bs, seq_length, voc_size)
|
| 403 |
+
else:
|
| 404 |
+
mask = attention_mask.unsqueeze(-1).expand_as(s_logits) # (bs, seq_length, voc_size)
|
| 405 |
+
s_logits_slct = torch.masked_select(s_logits, mask) # (bs * seq_length * voc_size) modulo the 1s in mask
|
| 406 |
+
s_logits_slct = s_logits_slct.view(-1, s_logits.size(-1)) # (bs * seq_length, voc_size) modulo the 1s in mask
|
| 407 |
+
t_logits_slct = torch.masked_select(t_logits, mask) # (bs * seq_length * voc_size) modulo the 1s in mask
|
| 408 |
+
t_logits_slct = t_logits_slct.view(-1, s_logits.size(-1)) # (bs * seq_length, voc_size) modulo the 1s in mask
|
| 409 |
+
assert t_logits_slct.size() == s_logits_slct.size()
|
| 410 |
+
|
| 411 |
+
loss_ce = (
|
| 412 |
+
self.ce_loss_fct(
|
| 413 |
+
nn.functional.log_softmax(s_logits_slct / self.temperature, dim=-1),
|
| 414 |
+
nn.functional.softmax(t_logits_slct / self.temperature, dim=-1),
|
| 415 |
+
)
|
| 416 |
+
* (self.temperature) ** 2
|
| 417 |
+
)
|
| 418 |
+
loss = self.alpha_ce * loss_ce
|
| 419 |
+
|
| 420 |
+
if self.alpha_mlm > 0.0:
|
| 421 |
+
loss_mlm = self.lm_loss_fct(s_logits.view(-1, s_logits.size(-1)), lm_labels.view(-1))
|
| 422 |
+
loss += self.alpha_mlm * loss_mlm
|
| 423 |
+
if self.alpha_clm > 0.0:
|
| 424 |
+
shift_logits = s_logits[..., :-1, :].contiguous()
|
| 425 |
+
shift_labels = lm_labels[..., 1:].contiguous()
|
| 426 |
+
loss_clm = self.lm_loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
|
| 427 |
+
loss += self.alpha_clm * loss_clm
|
| 428 |
+
|
| 429 |
+
if self.alpha_mse > 0.0:
|
| 430 |
+
loss_mse = self.mse_loss_fct(s_logits_slct, t_logits_slct) / s_logits_slct.size(
|
| 431 |
+
0
|
| 432 |
+
) # Reproducing batchmean reduction
|
| 433 |
+
loss += self.alpha_mse * loss_mse
|
| 434 |
+
if self.alpha_cos > 0.0:
|
| 435 |
+
s_hidden_states = s_hidden_states[-1] # (bs, seq_length, dim)
|
| 436 |
+
t_hidden_states = t_hidden_states[-1] # (bs, seq_length, dim)
|
| 437 |
+
mask = attention_mask.unsqueeze(-1).expand_as(s_hidden_states) # (bs, seq_length, dim)
|
| 438 |
+
assert s_hidden_states.size() == t_hidden_states.size()
|
| 439 |
+
dim = s_hidden_states.size(-1)
|
| 440 |
+
|
| 441 |
+
s_hidden_states_slct = torch.masked_select(s_hidden_states, mask) # (bs * seq_length * dim)
|
| 442 |
+
s_hidden_states_slct = s_hidden_states_slct.view(-1, dim) # (bs * seq_length, dim)
|
| 443 |
+
t_hidden_states_slct = torch.masked_select(t_hidden_states, mask) # (bs * seq_length * dim)
|
| 444 |
+
t_hidden_states_slct = t_hidden_states_slct.view(-1, dim) # (bs * seq_length, dim)
|
| 445 |
+
|
| 446 |
+
target = s_hidden_states_slct.new(s_hidden_states_slct.size(0)).fill_(1) # (bs * seq_length,)
|
| 447 |
+
loss_cos = self.cosine_loss_fct(s_hidden_states_slct, t_hidden_states_slct, target)
|
| 448 |
+
loss += self.alpha_cos * loss_cos
|
| 449 |
+
|
| 450 |
+
self.total_loss_epoch += loss.item()
|
| 451 |
+
self.last_loss = loss.item()
|
| 452 |
+
self.last_loss_ce = loss_ce.item()
|
| 453 |
+
if self.alpha_mlm > 0.0:
|
| 454 |
+
self.last_loss_mlm = loss_mlm.item()
|
| 455 |
+
if self.alpha_clm > 0.0:
|
| 456 |
+
self.last_loss_clm = loss_clm.item()
|
| 457 |
+
if self.alpha_mse > 0.0:
|
| 458 |
+
self.last_loss_mse = loss_mse.item()
|
| 459 |
+
if self.alpha_cos > 0.0:
|
| 460 |
+
self.last_loss_cos = loss_cos.item()
|
| 461 |
+
|
| 462 |
+
self.optimize(loss)
|
| 463 |
+
|
| 464 |
+
self.n_sequences_epoch += input_ids.size(0)
|
| 465 |
+
|
| 466 |
+
def optimize(self, loss):
|
| 467 |
+
"""
|
| 468 |
+
Normalization on the loss (gradient accumulation or distributed training), followed by
|
| 469 |
+
backward pass on the loss, possibly followed by a parameter update (depending on the gradient accumulation).
|
| 470 |
+
Also update the metrics for tensorboard.
|
| 471 |
+
"""
|
| 472 |
+
# Check for NaN
|
| 473 |
+
if (loss != loss).data.any():
|
| 474 |
+
logger.error("NaN detected")
|
| 475 |
+
exit()
|
| 476 |
+
|
| 477 |
+
if self.multi_gpu:
|
| 478 |
+
loss = loss.mean()
|
| 479 |
+
if self.params.gradient_accumulation_steps > 1:
|
| 480 |
+
loss = loss / self.params.gradient_accumulation_steps
|
| 481 |
+
|
| 482 |
+
if self.fp16:
|
| 483 |
+
from apex import amp
|
| 484 |
+
|
| 485 |
+
with amp.scale_loss(loss, self.optimizer) as scaled_loss:
|
| 486 |
+
scaled_loss.backward()
|
| 487 |
+
else:
|
| 488 |
+
loss.backward()
|
| 489 |
+
|
| 490 |
+
self.iter()
|
| 491 |
+
if self.n_iter % self.params.gradient_accumulation_steps == 0:
|
| 492 |
+
if self.fp16:
|
| 493 |
+
nn.utils.clip_grad_norm_(amp.master_params(self.optimizer), self.params.max_grad_norm)
|
| 494 |
+
else:
|
| 495 |
+
nn.utils.clip_grad_norm_(self.student.parameters(), self.params.max_grad_norm)
|
| 496 |
+
self.optimizer.step()
|
| 497 |
+
self.optimizer.zero_grad()
|
| 498 |
+
self.scheduler.step()
|
| 499 |
+
|
| 500 |
+
def iter(self):
|
| 501 |
+
"""
|
| 502 |
+
Update global counts, write to tensorboard and save checkpoint.
|
| 503 |
+
"""
|
| 504 |
+
self.n_iter += 1
|
| 505 |
+
self.n_total_iter += 1
|
| 506 |
+
|
| 507 |
+
if self.n_total_iter % self.params.log_interval == 0:
|
| 508 |
+
self.log_tensorboard()
|
| 509 |
+
self.last_log = time.time()
|
| 510 |
+
if self.n_total_iter % self.params.checkpoint_interval == 0:
|
| 511 |
+
self.save_checkpoint()
|
| 512 |
+
|
| 513 |
+
def log_tensorboard(self):
|
| 514 |
+
"""
|
| 515 |
+
Log into tensorboard. Only by the master process.
|
| 516 |
+
"""
|
| 517 |
+
if not self.is_master:
|
| 518 |
+
return
|
| 519 |
+
|
| 520 |
+
for param_name, param in self.student.named_parameters():
|
| 521 |
+
self.tensorboard.add_scalar(
|
| 522 |
+
tag="parameter_mean/" + param_name, scalar_value=param.data.mean(), global_step=self.n_total_iter
|
| 523 |
+
)
|
| 524 |
+
self.tensorboard.add_scalar(
|
| 525 |
+
tag="parameter_std/" + param_name, scalar_value=param.data.std(), global_step=self.n_total_iter
|
| 526 |
+
)
|
| 527 |
+
if param.grad is None:
|
| 528 |
+
continue
|
| 529 |
+
self.tensorboard.add_scalar(
|
| 530 |
+
tag="grad_mean/" + param_name, scalar_value=param.grad.data.mean(), global_step=self.n_total_iter
|
| 531 |
+
)
|
| 532 |
+
self.tensorboard.add_scalar(
|
| 533 |
+
tag="grad_std/" + param_name, scalar_value=param.grad.data.std(), global_step=self.n_total_iter
|
| 534 |
+
)
|
| 535 |
+
|
| 536 |
+
self.tensorboard.add_scalar(
|
| 537 |
+
tag="losses/cum_avg_loss_epoch",
|
| 538 |
+
scalar_value=self.total_loss_epoch / self.n_iter,
|
| 539 |
+
global_step=self.n_total_iter,
|
| 540 |
+
)
|
| 541 |
+
self.tensorboard.add_scalar(tag="losses/loss", scalar_value=self.last_loss, global_step=self.n_total_iter)
|
| 542 |
+
self.tensorboard.add_scalar(
|
| 543 |
+
tag="losses/loss_ce", scalar_value=self.last_loss_ce, global_step=self.n_total_iter
|
| 544 |
+
)
|
| 545 |
+
if self.alpha_mlm > 0.0:
|
| 546 |
+
self.tensorboard.add_scalar(
|
| 547 |
+
tag="losses/loss_mlm", scalar_value=self.last_loss_mlm, global_step=self.n_total_iter
|
| 548 |
+
)
|
| 549 |
+
if self.alpha_clm > 0.0:
|
| 550 |
+
self.tensorboard.add_scalar(
|
| 551 |
+
tag="losses/loss_clm", scalar_value=self.last_loss_clm, global_step=self.n_total_iter
|
| 552 |
+
)
|
| 553 |
+
if self.alpha_mse > 0.0:
|
| 554 |
+
self.tensorboard.add_scalar(
|
| 555 |
+
tag="losses/loss_mse", scalar_value=self.last_loss_mse, global_step=self.n_total_iter
|
| 556 |
+
)
|
| 557 |
+
if self.alpha_cos > 0.0:
|
| 558 |
+
self.tensorboard.add_scalar(
|
| 559 |
+
tag="losses/loss_cos", scalar_value=self.last_loss_cos, global_step=self.n_total_iter
|
| 560 |
+
)
|
| 561 |
+
self.tensorboard.add_scalar(
|
| 562 |
+
tag="learning_rate/lr", scalar_value=self.scheduler.get_lr()[0], global_step=self.n_total_iter
|
| 563 |
+
)
|
| 564 |
+
|
| 565 |
+
self.tensorboard.add_scalar(
|
| 566 |
+
tag="global/memory_usage",
|
| 567 |
+
scalar_value=psutil.virtual_memory()._asdict()["used"] / 1_000_000,
|
| 568 |
+
global_step=self.n_total_iter,
|
| 569 |
+
)
|
| 570 |
+
self.tensorboard.add_scalar(
|
| 571 |
+
tag="global/speed", scalar_value=time.time() - self.last_log, global_step=self.n_total_iter
|
| 572 |
+
)
|
| 573 |
+
|
| 574 |
+
def end_epoch(self):
|
| 575 |
+
"""
|
| 576 |
+
Finally arrived at the end of epoch (full pass on dataset).
|
| 577 |
+
Do some tensorboard logging and checkpoint saving.
|
| 578 |
+
"""
|
| 579 |
+
logger.info(f"{self.n_sequences_epoch} sequences have been trained during this epoch.")
|
| 580 |
+
|
| 581 |
+
if self.is_master:
|
| 582 |
+
self.save_checkpoint(checkpoint_name=f"model_epoch_{self.epoch}.pth")
|
| 583 |
+
self.tensorboard.add_scalar(
|
| 584 |
+
tag="epoch/loss", scalar_value=self.total_loss_epoch / self.n_iter, global_step=self.epoch
|
| 585 |
+
)
|
| 586 |
+
|
| 587 |
+
self.epoch += 1
|
| 588 |
+
self.n_sequences_epoch = 0
|
| 589 |
+
self.n_iter = 0
|
| 590 |
+
self.total_loss_epoch = 0
|
| 591 |
+
|
| 592 |
+
def save_checkpoint(self, checkpoint_name: str = "checkpoint.pth"):
|
| 593 |
+
"""
|
| 594 |
+
Save the current state. Only by the master process.
|
| 595 |
+
"""
|
| 596 |
+
if not self.is_master:
|
| 597 |
+
return
|
| 598 |
+
mdl_to_save = self.student.module if hasattr(self.student, "module") else self.student
|
| 599 |
+
mdl_to_save.config.save_pretrained(self.dump_path)
|
| 600 |
+
state_dict = mdl_to_save.state_dict()
|
| 601 |
+
torch.save(state_dict, os.path.join(self.dump_path, checkpoint_name))
|
tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/distillation/grouped_batch_sampler.py
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2019-present, the HuggingFace Inc. team and Facebook, Inc.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Adapted from PyTorch Vision (https://github.com/pytorch/vision/blob/master/references/detection/group_by_aspect_ratio.py)"""
|
| 16 |
+
|
| 17 |
+
import bisect
|
| 18 |
+
import copy
|
| 19 |
+
from collections import defaultdict
|
| 20 |
+
|
| 21 |
+
import numpy as np
|
| 22 |
+
from torch.utils.data import BatchSampler, Sampler
|
| 23 |
+
|
| 24 |
+
from utils import logger
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def _quantize(x, bins):
|
| 28 |
+
bins = copy.deepcopy(bins)
|
| 29 |
+
bins = sorted(bins)
|
| 30 |
+
quantized = [bisect.bisect_right(bins, y) for y in x]
|
| 31 |
+
return quantized
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def create_lengths_groups(lengths, k=0):
|
| 35 |
+
bins = np.arange(start=3, stop=k, step=4).tolist() if k > 0 else [10]
|
| 36 |
+
groups = _quantize(lengths, bins)
|
| 37 |
+
# count number of elements per group
|
| 38 |
+
counts = np.unique(groups, return_counts=True)[1]
|
| 39 |
+
fbins = [0] + bins + [np.inf]
|
| 40 |
+
logger.info("Using {} as bins for aspect lengths quantization".format(fbins))
|
| 41 |
+
logger.info("Count of instances per bin: {}".format(counts))
|
| 42 |
+
return groups
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
class GroupedBatchSampler(BatchSampler):
|
| 46 |
+
"""
|
| 47 |
+
Wraps another sampler to yield a mini-batch of indices.
|
| 48 |
+
It enforces that the batch only contain elements from the same group.
|
| 49 |
+
It also tries to provide mini-batches which follows an ordering which is
|
| 50 |
+
as close as possible to the ordering from the original sampler.
|
| 51 |
+
Arguments:
|
| 52 |
+
sampler (Sampler): Base sampler.
|
| 53 |
+
group_ids (list[int]): If the sampler produces indices in range [0, N),
|
| 54 |
+
`group_ids` must be a list of `N` ints which contains the group id of each sample.
|
| 55 |
+
The group ids must be a continuous set of integers starting from
|
| 56 |
+
0, i.e. they must be in the range [0, num_groups).
|
| 57 |
+
batch_size (int): Size of mini-batch.
|
| 58 |
+
"""
|
| 59 |
+
|
| 60 |
+
def __init__(self, sampler, group_ids, batch_size):
|
| 61 |
+
if not isinstance(sampler, Sampler):
|
| 62 |
+
raise TypeError(
|
| 63 |
+
"sampler should be an instance of torch.utils.data.Sampler, but got sampler={}".format(sampler)
|
| 64 |
+
)
|
| 65 |
+
self.sampler = sampler
|
| 66 |
+
self.group_ids = group_ids
|
| 67 |
+
self.batch_size = batch_size
|
| 68 |
+
|
| 69 |
+
def __iter__(self):
|
| 70 |
+
buffer_per_group = defaultdict(list)
|
| 71 |
+
samples_per_group = defaultdict(list)
|
| 72 |
+
|
| 73 |
+
num_batches = 0
|
| 74 |
+
for idx in self.sampler:
|
| 75 |
+
group_id = self.group_ids[idx]
|
| 76 |
+
buffer_per_group[group_id].append(idx)
|
| 77 |
+
samples_per_group[group_id].append(idx)
|
| 78 |
+
if len(buffer_per_group[group_id]) == self.batch_size:
|
| 79 |
+
yield buffer_per_group[group_id] # TODO
|
| 80 |
+
num_batches += 1
|
| 81 |
+
del buffer_per_group[group_id]
|
| 82 |
+
assert len(buffer_per_group[group_id]) < self.batch_size
|
| 83 |
+
|
| 84 |
+
# now we have run out of elements that satisfy
|
| 85 |
+
# the group criteria, let's return the remaining
|
| 86 |
+
# elements so that the size of the sampler is
|
| 87 |
+
# deterministic
|
| 88 |
+
expected_num_batches = len(self)
|
| 89 |
+
num_remaining = expected_num_batches - num_batches
|
| 90 |
+
if num_remaining > 0:
|
| 91 |
+
# for the remaining batches, group the batches by similar lengths
|
| 92 |
+
batch_idx = []
|
| 93 |
+
for group_id, idxs in sorted(buffer_per_group.items(), key=lambda x: x[0]):
|
| 94 |
+
batch_idx.extend(idxs)
|
| 95 |
+
if len(batch_idx) >= self.batch_size:
|
| 96 |
+
yield batch_idx[: self.batch_size]
|
| 97 |
+
batch_idx = batch_idx[self.batch_size :]
|
| 98 |
+
num_remaining -= 1
|
| 99 |
+
if len(batch_idx) > 0:
|
| 100 |
+
yield batch_idx
|
| 101 |
+
num_remaining -= 1
|
| 102 |
+
assert num_remaining == 0
|
| 103 |
+
|
| 104 |
+
def __len__(self):
|
| 105 |
+
"""
|
| 106 |
+
Return the number of mini-batches rather than the number of samples.
|
| 107 |
+
"""
|
| 108 |
+
return (len(self.sampler) + self.batch_size - 1) // self.batch_size
|
tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/distillation/lm_seqs_dataset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|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2019-present, the HuggingFace Inc. team and Facebook, Inc.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Dataset to distilled models
|
| 16 |
+
adapted in part from Facebook, Inc XLM model (https://github.com/facebookresearch/XLM)
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
import numpy as np
|
| 20 |
+
import torch
|
| 21 |
+
from torch.utils.data import Dataset
|
| 22 |
+
|
| 23 |
+
from utils import logger
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class LmSeqsDataset(Dataset):
|
| 27 |
+
"""Custom Dataset wrapping language modeling sequences.
|
| 28 |
+
|
| 29 |
+
Each sample will be retrieved by indexing the list of token_ids and their corresponding lengths.
|
| 30 |
+
|
| 31 |
+
Input:
|
| 32 |
+
------
|
| 33 |
+
params: `NameSpace` parameters
|
| 34 |
+
data: `List[np.array[int]]
|
| 35 |
+
"""
|
| 36 |
+
|
| 37 |
+
def __init__(self, params, data):
|
| 38 |
+
self.params = params
|
| 39 |
+
|
| 40 |
+
self.token_ids = np.array(data)
|
| 41 |
+
self.lengths = np.array([len(t) for t in data])
|
| 42 |
+
|
| 43 |
+
self.check()
|
| 44 |
+
self.remove_long_sequences()
|
| 45 |
+
self.remove_empty_sequences()
|
| 46 |
+
self.remove_unknown_sequences()
|
| 47 |
+
self.check()
|
| 48 |
+
self.print_statistics()
|
| 49 |
+
|
| 50 |
+
def __getitem__(self, index):
|
| 51 |
+
return (self.token_ids[index], self.lengths[index])
|
| 52 |
+
|
| 53 |
+
def __len__(self):
|
| 54 |
+
return len(self.lengths)
|
| 55 |
+
|
| 56 |
+
def check(self):
|
| 57 |
+
"""
|
| 58 |
+
Some sanity checks
|
| 59 |
+
"""
|
| 60 |
+
assert len(self.token_ids) == len(self.lengths)
|
| 61 |
+
assert all(self.lengths[i] == len(self.token_ids[i]) for i in range(len(self.lengths)))
|
| 62 |
+
|
| 63 |
+
def remove_long_sequences(self):
|
| 64 |
+
"""
|
| 65 |
+
Sequences that are too long are split by chunk of max_model_input_size.
|
| 66 |
+
"""
|
| 67 |
+
max_len = self.params.max_model_input_size
|
| 68 |
+
indices = self.lengths > max_len
|
| 69 |
+
logger.info(f"Splitting {sum(indices)} too long sequences.")
|
| 70 |
+
|
| 71 |
+
def divide_chunks(l, n):
|
| 72 |
+
return [l[i : i + n] for i in range(0, len(l), n)]
|
| 73 |
+
|
| 74 |
+
new_tok_ids = []
|
| 75 |
+
new_lengths = []
|
| 76 |
+
if self.params.mlm:
|
| 77 |
+
cls_id, sep_id = self.params.special_tok_ids["cls_token"], self.params.special_tok_ids["sep_token"]
|
| 78 |
+
else:
|
| 79 |
+
cls_id, sep_id = self.params.special_tok_ids["bos_token"], self.params.special_tok_ids["eos_token"]
|
| 80 |
+
|
| 81 |
+
for seq_, len_ in zip(self.token_ids, self.lengths):
|
| 82 |
+
assert (seq_[0] == cls_id) and (seq_[-1] == sep_id), seq_
|
| 83 |
+
if len_ <= max_len:
|
| 84 |
+
new_tok_ids.append(seq_)
|
| 85 |
+
new_lengths.append(len_)
|
| 86 |
+
else:
|
| 87 |
+
sub_seqs = []
|
| 88 |
+
for sub_s in divide_chunks(seq_, max_len - 2):
|
| 89 |
+
if sub_s[0] != cls_id:
|
| 90 |
+
sub_s = np.insert(sub_s, 0, cls_id)
|
| 91 |
+
if sub_s[-1] != sep_id:
|
| 92 |
+
sub_s = np.insert(sub_s, len(sub_s), sep_id)
|
| 93 |
+
assert len(sub_s) <= max_len
|
| 94 |
+
assert (sub_s[0] == cls_id) and (sub_s[-1] == sep_id), sub_s
|
| 95 |
+
sub_seqs.append(sub_s)
|
| 96 |
+
|
| 97 |
+
new_tok_ids.extend(sub_seqs)
|
| 98 |
+
new_lengths.extend([len(l) for l in sub_seqs])
|
| 99 |
+
|
| 100 |
+
self.token_ids = np.array(new_tok_ids)
|
| 101 |
+
self.lengths = np.array(new_lengths)
|
| 102 |
+
|
| 103 |
+
def remove_empty_sequences(self):
|
| 104 |
+
"""
|
| 105 |
+
Too short sequences are simply removed. This could be tuned.
|
| 106 |
+
"""
|
| 107 |
+
init_size = len(self)
|
| 108 |
+
indices = self.lengths > 11
|
| 109 |
+
self.token_ids = self.token_ids[indices]
|
| 110 |
+
self.lengths = self.lengths[indices]
|
| 111 |
+
new_size = len(self)
|
| 112 |
+
logger.info(f"Remove {init_size - new_size} too short (<=11 tokens) sequences.")
|
| 113 |
+
|
| 114 |
+
def remove_unknown_sequences(self):
|
| 115 |
+
"""
|
| 116 |
+
Remove sequences with a (too) high level of unknown tokens.
|
| 117 |
+
"""
|
| 118 |
+
if "unk_token" not in self.params.special_tok_ids:
|
| 119 |
+
return
|
| 120 |
+
else:
|
| 121 |
+
unk_token_id = self.params.special_tok_ids["unk_token"]
|
| 122 |
+
init_size = len(self)
|
| 123 |
+
unk_occs = np.array([np.count_nonzero(a == unk_token_id) for a in self.token_ids])
|
| 124 |
+
indices = (unk_occs / self.lengths) < 0.5
|
| 125 |
+
self.token_ids = self.token_ids[indices]
|
| 126 |
+
self.lengths = self.lengths[indices]
|
| 127 |
+
new_size = len(self)
|
| 128 |
+
logger.info(f"Remove {init_size - new_size} sequences with a high level of unknown tokens (50%).")
|
| 129 |
+
|
| 130 |
+
def print_statistics(self):
|
| 131 |
+
"""
|
| 132 |
+
Print some statistics on the corpus. Only the master process.
|
| 133 |
+
"""
|
| 134 |
+
if not self.params.is_master:
|
| 135 |
+
return
|
| 136 |
+
logger.info(f"{len(self)} sequences")
|
| 137 |
+
# data_len = sum(self.lengths)
|
| 138 |
+
# nb_unique_tokens = len(Counter(list(chain(*self.token_ids))))
|
| 139 |
+
# logger.info(f'{data_len} tokens ({nb_unique_tokens} unique)')
|
| 140 |
+
|
| 141 |
+
# unk_idx = self.params.special_tok_ids['unk_token']
|
| 142 |
+
# nb_unknown = sum([(t==unk_idx).sum() for t in self.token_ids])
|
| 143 |
+
# logger.info(f'{nb_unknown} unknown tokens (covering {100*nb_unknown/data_len:.2f}% of the data)')
|
| 144 |
+
|
| 145 |
+
def batch_sequences(self, batch):
|
| 146 |
+
"""
|
| 147 |
+
Do the padding and transform into torch.tensor.
|
| 148 |
+
"""
|
| 149 |
+
token_ids = [t[0] for t in batch]
|
| 150 |
+
lengths = [t[1] for t in batch]
|
| 151 |
+
assert len(token_ids) == len(lengths)
|
| 152 |
+
|
| 153 |
+
# Max for paddings
|
| 154 |
+
max_seq_len_ = max(lengths)
|
| 155 |
+
|
| 156 |
+
# Pad token ids
|
| 157 |
+
if self.params.mlm:
|
| 158 |
+
pad_idx = self.params.special_tok_ids["pad_token"]
|
| 159 |
+
else:
|
| 160 |
+
pad_idx = self.params.special_tok_ids["unk_token"]
|
| 161 |
+
tk_ = [list(t.astype(int)) + [pad_idx] * (max_seq_len_ - len(t)) for t in token_ids]
|
| 162 |
+
assert len(tk_) == len(token_ids)
|
| 163 |
+
assert all(len(t) == max_seq_len_ for t in tk_)
|
| 164 |
+
|
| 165 |
+
tk_t = torch.tensor(tk_) # (bs, max_seq_len_)
|
| 166 |
+
lg_t = torch.tensor(lengths) # (bs)
|
| 167 |
+
return tk_t, lg_t
|
tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/distillation/requirements.txt
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
transformers
|
| 2 |
+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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
|
| 3 |
+
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
"""This is the exact same script as `examples/question-answering/run_squad.py` (as of 2020, January 8th) with an additional and optional step of distillation."""
|
| 17 |
+
|
| 18 |
+
import argparse
|
| 19 |
+
import glob
|
| 20 |
+
import logging
|
| 21 |
+
import os
|
| 22 |
+
import random
|
| 23 |
+
import timeit
|
| 24 |
+
|
| 25 |
+
import numpy as np
|
| 26 |
+
import torch
|
| 27 |
+
from torch import nn
|
| 28 |
+
from torch.utils.data import DataLoader, RandomSampler, SequentialSampler
|
| 29 |
+
from torch.utils.data.distributed import DistributedSampler
|
| 30 |
+
from tqdm import tqdm, trange
|
| 31 |
+
|
| 32 |
+
import transformers
|
| 33 |
+
from transformers import (
|
| 34 |
+
WEIGHTS_NAME,
|
| 35 |
+
AdamW,
|
| 36 |
+
BertConfig,
|
| 37 |
+
BertForQuestionAnswering,
|
| 38 |
+
BertTokenizer,
|
| 39 |
+
DistilBertConfig,
|
| 40 |
+
DistilBertForQuestionAnswering,
|
| 41 |
+
DistilBertTokenizer,
|
| 42 |
+
RobertaConfig,
|
| 43 |
+
RobertaForQuestionAnswering,
|
| 44 |
+
RobertaTokenizer,
|
| 45 |
+
XLMConfig,
|
| 46 |
+
XLMForQuestionAnswering,
|
| 47 |
+
XLMTokenizer,
|
| 48 |
+
XLNetConfig,
|
| 49 |
+
XLNetForQuestionAnswering,
|
| 50 |
+
XLNetTokenizer,
|
| 51 |
+
get_linear_schedule_with_warmup,
|
| 52 |
+
squad_convert_examples_to_features,
|
| 53 |
+
)
|
| 54 |
+
from transformers.data.metrics.squad_metrics import (
|
| 55 |
+
compute_predictions_log_probs,
|
| 56 |
+
compute_predictions_logits,
|
| 57 |
+
squad_evaluate,
|
| 58 |
+
)
|
| 59 |
+
from transformers.data.processors.squad import SquadResult, SquadV1Processor, SquadV2Processor
|
| 60 |
+
from transformers.trainer_utils import is_main_process
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
try:
|
| 64 |
+
from torch.utils.tensorboard import SummaryWriter
|
| 65 |
+
except ImportError:
|
| 66 |
+
from tensorboardX import SummaryWriter
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
logger = logging.getLogger(__name__)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
MODEL_CLASSES = {
|
| 73 |
+
"bert": (BertConfig, BertForQuestionAnswering, BertTokenizer),
|
| 74 |
+
"xlnet": (XLNetConfig, XLNetForQuestionAnswering, XLNetTokenizer),
|
| 75 |
+
"xlm": (XLMConfig, XLMForQuestionAnswering, XLMTokenizer),
|
| 76 |
+
"distilbert": (DistilBertConfig, DistilBertForQuestionAnswering, DistilBertTokenizer),
|
| 77 |
+
"roberta": (RobertaConfig, RobertaForQuestionAnswering, RobertaTokenizer),
|
| 78 |
+
}
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def set_seed(args):
|
| 82 |
+
random.seed(args.seed)
|
| 83 |
+
np.random.seed(args.seed)
|
| 84 |
+
torch.manual_seed(args.seed)
|
| 85 |
+
if args.n_gpu > 0:
|
| 86 |
+
torch.cuda.manual_seed_all(args.seed)
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def to_list(tensor):
|
| 90 |
+
return tensor.detach().cpu().tolist()
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def train(args, train_dataset, model, tokenizer, teacher=None):
|
| 94 |
+
"""Train the model"""
|
| 95 |
+
if args.local_rank in [-1, 0]:
|
| 96 |
+
tb_writer = SummaryWriter()
|
| 97 |
+
|
| 98 |
+
args.train_batch_size = args.per_gpu_train_batch_size * max(1, args.n_gpu)
|
| 99 |
+
train_sampler = RandomSampler(train_dataset) if args.local_rank == -1 else DistributedSampler(train_dataset)
|
| 100 |
+
train_dataloader = DataLoader(train_dataset, sampler=train_sampler, batch_size=args.train_batch_size)
|
| 101 |
+
|
| 102 |
+
if args.max_steps > 0:
|
| 103 |
+
t_total = args.max_steps
|
| 104 |
+
args.num_train_epochs = args.max_steps // (len(train_dataloader) // args.gradient_accumulation_steps) + 1
|
| 105 |
+
else:
|
| 106 |
+
t_total = len(train_dataloader) // args.gradient_accumulation_steps * args.num_train_epochs
|
| 107 |
+
|
| 108 |
+
# Prepare optimizer and schedule (linear warmup and decay)
|
| 109 |
+
no_decay = ["bias", "LayerNorm.weight"]
|
| 110 |
+
optimizer_grouped_parameters = [
|
| 111 |
+
{
|
| 112 |
+
"params": [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay)],
|
| 113 |
+
"weight_decay": args.weight_decay,
|
| 114 |
+
},
|
| 115 |
+
{"params": [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay)], "weight_decay": 0.0},
|
| 116 |
+
]
|
| 117 |
+
optimizer = AdamW(optimizer_grouped_parameters, lr=args.learning_rate, eps=args.adam_epsilon)
|
| 118 |
+
scheduler = get_linear_schedule_with_warmup(
|
| 119 |
+
optimizer, num_warmup_steps=args.warmup_steps, num_training_steps=t_total
|
| 120 |
+
)
|
| 121 |
+
|
| 122 |
+
# Check if saved optimizer or scheduler states exist
|
| 123 |
+
if os.path.isfile(os.path.join(args.model_name_or_path, "optimizer.pt")) and os.path.isfile(
|
| 124 |
+
os.path.join(args.model_name_or_path, "scheduler.pt")
|
| 125 |
+
):
|
| 126 |
+
# Load in optimizer and scheduler states
|
| 127 |
+
optimizer.load_state_dict(torch.load(os.path.join(args.model_name_or_path, "optimizer.pt")))
|
| 128 |
+
scheduler.load_state_dict(torch.load(os.path.join(args.model_name_or_path, "scheduler.pt")))
|
| 129 |
+
|
| 130 |
+
if args.fp16:
|
| 131 |
+
try:
|
| 132 |
+
from apex import amp
|
| 133 |
+
except ImportError:
|
| 134 |
+
raise ImportError("Please install apex from https://www.github.com/nvidia/apex to use fp16 training.")
|
| 135 |
+
|
| 136 |
+
model, optimizer = amp.initialize(model, optimizer, opt_level=args.fp16_opt_level)
|
| 137 |
+
|
| 138 |
+
# multi-gpu training (should be after apex fp16 initialization)
|
| 139 |
+
if args.n_gpu > 1:
|
| 140 |
+
model = nn.DataParallel(model)
|
| 141 |
+
|
| 142 |
+
# Distributed training (should be after apex fp16 initialization)
|
| 143 |
+
if args.local_rank != -1:
|
| 144 |
+
model = nn.parallel.DistributedDataParallel(
|
| 145 |
+
model, device_ids=[args.local_rank], output_device=args.local_rank, find_unused_parameters=True
|
| 146 |
+
)
|
| 147 |
+
|
| 148 |
+
# Train!
|
| 149 |
+
logger.info("***** Running training *****")
|
| 150 |
+
logger.info(" Num examples = %d", len(train_dataset))
|
| 151 |
+
logger.info(" Num Epochs = %d", args.num_train_epochs)
|
| 152 |
+
logger.info(" Instantaneous batch size per GPU = %d", args.per_gpu_train_batch_size)
|
| 153 |
+
logger.info(
|
| 154 |
+
" Total train batch size (w. parallel, distributed & accumulation) = %d",
|
| 155 |
+
args.train_batch_size
|
| 156 |
+
* args.gradient_accumulation_steps
|
| 157 |
+
* (torch.distributed.get_world_size() if args.local_rank != -1 else 1),
|
| 158 |
+
)
|
| 159 |
+
logger.info(" Gradient Accumulation steps = %d", args.gradient_accumulation_steps)
|
| 160 |
+
logger.info(" Total optimization steps = %d", t_total)
|
| 161 |
+
|
| 162 |
+
global_step = 1
|
| 163 |
+
epochs_trained = 0
|
| 164 |
+
steps_trained_in_current_epoch = 0
|
| 165 |
+
# Check if continuing training from a checkpoint
|
| 166 |
+
if os.path.exists(args.model_name_or_path):
|
| 167 |
+
try:
|
| 168 |
+
# set global_step to global_step of last saved checkpoint from model path
|
| 169 |
+
checkpoint_suffix = args.model_name_or_path.split("-")[-1].split("/")[0]
|
| 170 |
+
global_step = int(checkpoint_suffix)
|
| 171 |
+
epochs_trained = global_step // (len(train_dataloader) // args.gradient_accumulation_steps)
|
| 172 |
+
steps_trained_in_current_epoch = global_step % (len(train_dataloader) // args.gradient_accumulation_steps)
|
| 173 |
+
|
| 174 |
+
logger.info(" Continuing training from checkpoint, will skip to saved global_step")
|
| 175 |
+
logger.info(" Continuing training from epoch %d", epochs_trained)
|
| 176 |
+
logger.info(" Continuing training from global step %d", global_step)
|
| 177 |
+
logger.info(" Will skip the first %d steps in the first epoch", steps_trained_in_current_epoch)
|
| 178 |
+
except ValueError:
|
| 179 |
+
logger.info(" Starting fine-tuning.")
|
| 180 |
+
|
| 181 |
+
tr_loss, logging_loss = 0.0, 0.0
|
| 182 |
+
model.zero_grad()
|
| 183 |
+
train_iterator = trange(
|
| 184 |
+
epochs_trained, int(args.num_train_epochs), desc="Epoch", disable=args.local_rank not in [-1, 0]
|
| 185 |
+
)
|
| 186 |
+
# Added here for reproducibility
|
| 187 |
+
set_seed(args)
|
| 188 |
+
|
| 189 |
+
for _ in train_iterator:
|
| 190 |
+
epoch_iterator = tqdm(train_dataloader, desc="Iteration", disable=args.local_rank not in [-1, 0])
|
| 191 |
+
for step, batch in enumerate(epoch_iterator):
|
| 192 |
+
# Skip past any already trained steps if resuming training
|
| 193 |
+
if steps_trained_in_current_epoch > 0:
|
| 194 |
+
steps_trained_in_current_epoch -= 1
|
| 195 |
+
continue
|
| 196 |
+
|
| 197 |
+
model.train()
|
| 198 |
+
if teacher is not None:
|
| 199 |
+
teacher.eval()
|
| 200 |
+
batch = tuple(t.to(args.device) for t in batch)
|
| 201 |
+
|
| 202 |
+
inputs = {
|
| 203 |
+
"input_ids": batch[0],
|
| 204 |
+
"attention_mask": batch[1],
|
| 205 |
+
"start_positions": batch[3],
|
| 206 |
+
"end_positions": batch[4],
|
| 207 |
+
}
|
| 208 |
+
if args.model_type != "distilbert":
|
| 209 |
+
inputs["token_type_ids"] = None if args.model_type == "xlm" else batch[2]
|
| 210 |
+
if args.model_type in ["xlnet", "xlm"]:
|
| 211 |
+
inputs.update({"cls_index": batch[5], "p_mask": batch[6]})
|
| 212 |
+
if args.version_2_with_negative:
|
| 213 |
+
inputs.update({"is_impossible": batch[7]})
|
| 214 |
+
outputs = model(**inputs)
|
| 215 |
+
loss, start_logits_stu, end_logits_stu = outputs
|
| 216 |
+
|
| 217 |
+
# Distillation loss
|
| 218 |
+
if teacher is not None:
|
| 219 |
+
if "token_type_ids" not in inputs:
|
| 220 |
+
inputs["token_type_ids"] = None if args.teacher_type == "xlm" else batch[2]
|
| 221 |
+
with torch.no_grad():
|
| 222 |
+
start_logits_tea, end_logits_tea = teacher(
|
| 223 |
+
input_ids=inputs["input_ids"],
|
| 224 |
+
token_type_ids=inputs["token_type_ids"],
|
| 225 |
+
attention_mask=inputs["attention_mask"],
|
| 226 |
+
)
|
| 227 |
+
assert start_logits_tea.size() == start_logits_stu.size()
|
| 228 |
+
assert end_logits_tea.size() == end_logits_stu.size()
|
| 229 |
+
|
| 230 |
+
loss_fct = nn.KLDivLoss(reduction="batchmean")
|
| 231 |
+
loss_start = loss_fct(
|
| 232 |
+
nn.functional.log_softmax(start_logits_stu / args.temperature, dim=-1),
|
| 233 |
+
nn.functional.softmax(start_logits_tea / args.temperature, dim=-1),
|
| 234 |
+
) * (args.temperature**2)
|
| 235 |
+
loss_end = loss_fct(
|
| 236 |
+
nn.functional.log_softmax(end_logits_stu / args.temperature, dim=-1),
|
| 237 |
+
nn.functional.softmax(end_logits_tea / args.temperature, dim=-1),
|
| 238 |
+
) * (args.temperature**2)
|
| 239 |
+
loss_ce = (loss_start + loss_end) / 2.0
|
| 240 |
+
|
| 241 |
+
loss = args.alpha_ce * loss_ce + args.alpha_squad * loss
|
| 242 |
+
|
| 243 |
+
if args.n_gpu > 1:
|
| 244 |
+
loss = loss.mean() # mean() to average on multi-gpu parallel (not distributed) training
|
| 245 |
+
if args.gradient_accumulation_steps > 1:
|
| 246 |
+
loss = loss / args.gradient_accumulation_steps
|
| 247 |
+
|
| 248 |
+
if args.fp16:
|
| 249 |
+
with amp.scale_loss(loss, optimizer) as scaled_loss:
|
| 250 |
+
scaled_loss.backward()
|
| 251 |
+
else:
|
| 252 |
+
loss.backward()
|
| 253 |
+
|
| 254 |
+
tr_loss += loss.item()
|
| 255 |
+
if (step + 1) % args.gradient_accumulation_steps == 0:
|
| 256 |
+
if args.fp16:
|
| 257 |
+
nn.utils.clip_grad_norm_(amp.master_params(optimizer), args.max_grad_norm)
|
| 258 |
+
else:
|
| 259 |
+
nn.utils.clip_grad_norm_(model.parameters(), args.max_grad_norm)
|
| 260 |
+
|
| 261 |
+
optimizer.step()
|
| 262 |
+
scheduler.step() # Update learning rate schedule
|
| 263 |
+
model.zero_grad()
|
| 264 |
+
global_step += 1
|
| 265 |
+
|
| 266 |
+
# Log metrics
|
| 267 |
+
if args.local_rank in [-1, 0] and args.logging_steps > 0 and global_step % args.logging_steps == 0:
|
| 268 |
+
# Only evaluate when single GPU otherwise metrics may not average well
|
| 269 |
+
if args.local_rank == -1 and args.evaluate_during_training:
|
| 270 |
+
results = evaluate(args, model, tokenizer)
|
| 271 |
+
for key, value in results.items():
|
| 272 |
+
tb_writer.add_scalar("eval_{}".format(key), value, global_step)
|
| 273 |
+
tb_writer.add_scalar("lr", scheduler.get_lr()[0], global_step)
|
| 274 |
+
tb_writer.add_scalar("loss", (tr_loss - logging_loss) / args.logging_steps, global_step)
|
| 275 |
+
logging_loss = tr_loss
|
| 276 |
+
|
| 277 |
+
if args.local_rank in [-1, 0] and args.save_steps > 0 and global_step % args.save_steps == 0:
|
| 278 |
+
# Save model checkpoint
|
| 279 |
+
output_dir = os.path.join(args.output_dir, "checkpoint-{}".format(global_step))
|
| 280 |
+
if not os.path.exists(output_dir):
|
| 281 |
+
os.makedirs(output_dir)
|
| 282 |
+
model_to_save = (
|
| 283 |
+
model.module if hasattr(model, "module") else model
|
| 284 |
+
) # Take care of distributed/parallel training
|
| 285 |
+
model_to_save.save_pretrained(output_dir)
|
| 286 |
+
tokenizer.save_pretrained(output_dir)
|
| 287 |
+
|
| 288 |
+
torch.save(args, os.path.join(output_dir, "training_args.bin"))
|
| 289 |
+
logger.info("Saving model checkpoint to %s", output_dir)
|
| 290 |
+
|
| 291 |
+
torch.save(optimizer.state_dict(), os.path.join(output_dir, "optimizer.pt"))
|
| 292 |
+
torch.save(scheduler.state_dict(), os.path.join(output_dir, "scheduler.pt"))
|
| 293 |
+
logger.info("Saving optimizer and scheduler states to %s", output_dir)
|
| 294 |
+
|
| 295 |
+
if args.max_steps > 0 and global_step > args.max_steps:
|
| 296 |
+
epoch_iterator.close()
|
| 297 |
+
break
|
| 298 |
+
if args.max_steps > 0 and global_step > args.max_steps:
|
| 299 |
+
train_iterator.close()
|
| 300 |
+
break
|
| 301 |
+
|
| 302 |
+
if args.local_rank in [-1, 0]:
|
| 303 |
+
tb_writer.close()
|
| 304 |
+
|
| 305 |
+
return global_step, tr_loss / global_step
|
| 306 |
+
|
| 307 |
+
|
| 308 |
+
def evaluate(args, model, tokenizer, prefix=""):
|
| 309 |
+
dataset, examples, features = load_and_cache_examples(args, tokenizer, evaluate=True, output_examples=True)
|
| 310 |
+
|
| 311 |
+
if not os.path.exists(args.output_dir) and args.local_rank in [-1, 0]:
|
| 312 |
+
os.makedirs(args.output_dir)
|
| 313 |
+
|
| 314 |
+
args.eval_batch_size = args.per_gpu_eval_batch_size * max(1, args.n_gpu)
|
| 315 |
+
|
| 316 |
+
# Note that DistributedSampler samples randomly
|
| 317 |
+
eval_sampler = SequentialSampler(dataset)
|
| 318 |
+
eval_dataloader = DataLoader(dataset, sampler=eval_sampler, batch_size=args.eval_batch_size)
|
| 319 |
+
|
| 320 |
+
# multi-gpu evaluate
|
| 321 |
+
if args.n_gpu > 1 and not isinstance(model, nn.DataParallel):
|
| 322 |
+
model = nn.DataParallel(model)
|
| 323 |
+
|
| 324 |
+
# Eval!
|
| 325 |
+
logger.info("***** Running evaluation {} *****".format(prefix))
|
| 326 |
+
logger.info(" Num examples = %d", len(dataset))
|
| 327 |
+
logger.info(" Batch size = %d", args.eval_batch_size)
|
| 328 |
+
|
| 329 |
+
all_results = []
|
| 330 |
+
start_time = timeit.default_timer()
|
| 331 |
+
|
| 332 |
+
for batch in tqdm(eval_dataloader, desc="Evaluating"):
|
| 333 |
+
model.eval()
|
| 334 |
+
batch = tuple(t.to(args.device) for t in batch)
|
| 335 |
+
|
| 336 |
+
with torch.no_grad():
|
| 337 |
+
inputs = {"input_ids": batch[0], "attention_mask": batch[1]}
|
| 338 |
+
if args.model_type != "distilbert":
|
| 339 |
+
inputs["token_type_ids"] = None if args.model_type == "xlm" else batch[2] # XLM don't use segment_ids
|
| 340 |
+
example_indices = batch[3]
|
| 341 |
+
if args.model_type in ["xlnet", "xlm"]:
|
| 342 |
+
inputs.update({"cls_index": batch[4], "p_mask": batch[5]})
|
| 343 |
+
|
| 344 |
+
outputs = model(**inputs)
|
| 345 |
+
|
| 346 |
+
for i, example_index in enumerate(example_indices):
|
| 347 |
+
eval_feature = features[example_index.item()]
|
| 348 |
+
unique_id = int(eval_feature.unique_id)
|
| 349 |
+
|
| 350 |
+
output = [to_list(output[i]) for output in outputs]
|
| 351 |
+
|
| 352 |
+
# Some models (XLNet, XLM) use 5 arguments for their predictions, while the other "simpler"
|
| 353 |
+
# models only use two.
|
| 354 |
+
if len(output) >= 5:
|
| 355 |
+
start_logits = output[0]
|
| 356 |
+
start_top_index = output[1]
|
| 357 |
+
end_logits = output[2]
|
| 358 |
+
end_top_index = output[3]
|
| 359 |
+
cls_logits = output[4]
|
| 360 |
+
|
| 361 |
+
result = SquadResult(
|
| 362 |
+
unique_id,
|
| 363 |
+
start_logits,
|
| 364 |
+
end_logits,
|
| 365 |
+
start_top_index=start_top_index,
|
| 366 |
+
end_top_index=end_top_index,
|
| 367 |
+
cls_logits=cls_logits,
|
| 368 |
+
)
|
| 369 |
+
|
| 370 |
+
else:
|
| 371 |
+
start_logits, end_logits = output
|
| 372 |
+
result = SquadResult(unique_id, start_logits, end_logits)
|
| 373 |
+
|
| 374 |
+
all_results.append(result)
|
| 375 |
+
|
| 376 |
+
evalTime = timeit.default_timer() - start_time
|
| 377 |
+
logger.info(" Evaluation done in total %f secs (%f sec per example)", evalTime, evalTime / len(dataset))
|
| 378 |
+
|
| 379 |
+
# Compute predictions
|
| 380 |
+
output_prediction_file = os.path.join(args.output_dir, "predictions_{}.json".format(prefix))
|
| 381 |
+
output_nbest_file = os.path.join(args.output_dir, "nbest_predictions_{}.json".format(prefix))
|
| 382 |
+
|
| 383 |
+
if args.version_2_with_negative:
|
| 384 |
+
output_null_log_odds_file = os.path.join(args.output_dir, "null_odds_{}.json".format(prefix))
|
| 385 |
+
else:
|
| 386 |
+
output_null_log_odds_file = None
|
| 387 |
+
|
| 388 |
+
if args.model_type in ["xlnet", "xlm"]:
|
| 389 |
+
# XLNet uses a more complex post-processing procedure
|
| 390 |
+
predictions = compute_predictions_log_probs(
|
| 391 |
+
examples,
|
| 392 |
+
features,
|
| 393 |
+
all_results,
|
| 394 |
+
args.n_best_size,
|
| 395 |
+
args.max_answer_length,
|
| 396 |
+
output_prediction_file,
|
| 397 |
+
output_nbest_file,
|
| 398 |
+
output_null_log_odds_file,
|
| 399 |
+
model.config.start_n_top,
|
| 400 |
+
model.config.end_n_top,
|
| 401 |
+
args.version_2_with_negative,
|
| 402 |
+
tokenizer,
|
| 403 |
+
args.verbose_logging,
|
| 404 |
+
)
|
| 405 |
+
else:
|
| 406 |
+
predictions = compute_predictions_logits(
|
| 407 |
+
examples,
|
| 408 |
+
features,
|
| 409 |
+
all_results,
|
| 410 |
+
args.n_best_size,
|
| 411 |
+
args.max_answer_length,
|
| 412 |
+
args.do_lower_case,
|
| 413 |
+
output_prediction_file,
|
| 414 |
+
output_nbest_file,
|
| 415 |
+
output_null_log_odds_file,
|
| 416 |
+
args.verbose_logging,
|
| 417 |
+
args.version_2_with_negative,
|
| 418 |
+
args.null_score_diff_threshold,
|
| 419 |
+
tokenizer,
|
| 420 |
+
)
|
| 421 |
+
|
| 422 |
+
# Compute the F1 and exact scores.
|
| 423 |
+
results = squad_evaluate(examples, predictions)
|
| 424 |
+
return results
|
| 425 |
+
|
| 426 |
+
|
| 427 |
+
def load_and_cache_examples(args, tokenizer, evaluate=False, output_examples=False):
|
| 428 |
+
if args.local_rank not in [-1, 0] and not evaluate:
|
| 429 |
+
# Make sure only the first process in distributed training process the dataset, and the others will use the cache
|
| 430 |
+
torch.distributed.barrier()
|
| 431 |
+
|
| 432 |
+
# Load data features from cache or dataset file
|
| 433 |
+
input_file = args.predict_file if evaluate else args.train_file
|
| 434 |
+
cached_features_file = os.path.join(
|
| 435 |
+
os.path.dirname(input_file),
|
| 436 |
+
"cached_distillation_{}_{}_{}".format(
|
| 437 |
+
"dev" if evaluate else "train",
|
| 438 |
+
list(filter(None, args.model_name_or_path.split("/"))).pop(),
|
| 439 |
+
str(args.max_seq_length),
|
| 440 |
+
),
|
| 441 |
+
)
|
| 442 |
+
if os.path.exists(cached_features_file) and not args.overwrite_cache:
|
| 443 |
+
logger.info("Loading features from cached file %s", cached_features_file)
|
| 444 |
+
features_and_dataset = torch.load(cached_features_file)
|
| 445 |
+
|
| 446 |
+
try:
|
| 447 |
+
features, dataset, examples = (
|
| 448 |
+
features_and_dataset["features"],
|
| 449 |
+
features_and_dataset["dataset"],
|
| 450 |
+
features_and_dataset["examples"],
|
| 451 |
+
)
|
| 452 |
+
except KeyError:
|
| 453 |
+
raise DeprecationWarning(
|
| 454 |
+
"You seem to be loading features from an older version of this script please delete the "
|
| 455 |
+
"file %s in order for it to be created again" % cached_features_file
|
| 456 |
+
)
|
| 457 |
+
else:
|
| 458 |
+
logger.info("Creating features from dataset file at %s", input_file)
|
| 459 |
+
processor = SquadV2Processor() if args.version_2_with_negative else SquadV1Processor()
|
| 460 |
+
if evaluate:
|
| 461 |
+
examples = processor.get_dev_examples(args.data_dir, filename=args.predict_file)
|
| 462 |
+
else:
|
| 463 |
+
examples = processor.get_train_examples(args.data_dir, filename=args.train_file)
|
| 464 |
+
|
| 465 |
+
features, dataset = squad_convert_examples_to_features(
|
| 466 |
+
examples=examples,
|
| 467 |
+
tokenizer=tokenizer,
|
| 468 |
+
max_seq_length=args.max_seq_length,
|
| 469 |
+
doc_stride=args.doc_stride,
|
| 470 |
+
max_query_length=args.max_query_length,
|
| 471 |
+
is_training=not evaluate,
|
| 472 |
+
return_dataset="pt",
|
| 473 |
+
threads=args.threads,
|
| 474 |
+
)
|
| 475 |
+
|
| 476 |
+
if args.local_rank in [-1, 0]:
|
| 477 |
+
logger.info("Saving features into cached file %s", cached_features_file)
|
| 478 |
+
torch.save({"features": features, "dataset": dataset, "examples": examples}, cached_features_file)
|
| 479 |
+
|
| 480 |
+
if args.local_rank == 0 and not evaluate:
|
| 481 |
+
# Make sure only the first process in distributed training process the dataset, and the others will use the cache
|
| 482 |
+
torch.distributed.barrier()
|
| 483 |
+
|
| 484 |
+
if output_examples:
|
| 485 |
+
return dataset, examples, features
|
| 486 |
+
return dataset
|
| 487 |
+
|
| 488 |
+
|
| 489 |
+
def main():
|
| 490 |
+
parser = argparse.ArgumentParser()
|
| 491 |
+
|
| 492 |
+
# Required parameters
|
| 493 |
+
parser.add_argument(
|
| 494 |
+
"--model_type",
|
| 495 |
+
default=None,
|
| 496 |
+
type=str,
|
| 497 |
+
required=True,
|
| 498 |
+
help="Model type selected in the list: " + ", ".join(MODEL_CLASSES.keys()),
|
| 499 |
+
)
|
| 500 |
+
parser.add_argument(
|
| 501 |
+
"--model_name_or_path",
|
| 502 |
+
default=None,
|
| 503 |
+
type=str,
|
| 504 |
+
required=True,
|
| 505 |
+
help="Path to pretrained model or model identifier from huggingface.co/models",
|
| 506 |
+
)
|
| 507 |
+
parser.add_argument(
|
| 508 |
+
"--output_dir",
|
| 509 |
+
default=None,
|
| 510 |
+
type=str,
|
| 511 |
+
required=True,
|
| 512 |
+
help="The output directory where the model checkpoints and predictions will be written.",
|
| 513 |
+
)
|
| 514 |
+
|
| 515 |
+
# Distillation parameters (optional)
|
| 516 |
+
parser.add_argument(
|
| 517 |
+
"--teacher_type",
|
| 518 |
+
default=None,
|
| 519 |
+
type=str,
|
| 520 |
+
help=(
|
| 521 |
+
"Teacher type. Teacher tokenizer and student (model) tokenizer must output the same tokenization. Only for"
|
| 522 |
+
" distillation."
|
| 523 |
+
),
|
| 524 |
+
)
|
| 525 |
+
parser.add_argument(
|
| 526 |
+
"--teacher_name_or_path",
|
| 527 |
+
default=None,
|
| 528 |
+
type=str,
|
| 529 |
+
help="Path to the already SQuAD fine-tuned teacher model. Only for distillation.",
|
| 530 |
+
)
|
| 531 |
+
parser.add_argument(
|
| 532 |
+
"--alpha_ce", default=0.5, type=float, help="Distillation loss linear weight. Only for distillation."
|
| 533 |
+
)
|
| 534 |
+
parser.add_argument(
|
| 535 |
+
"--alpha_squad", default=0.5, type=float, help="True SQuAD loss linear weight. Only for distillation."
|
| 536 |
+
)
|
| 537 |
+
parser.add_argument(
|
| 538 |
+
"--temperature", default=2.0, type=float, help="Distillation temperature. Only for distillation."
|
| 539 |
+
)
|
| 540 |
+
|
| 541 |
+
# Other parameters
|
| 542 |
+
parser.add_argument(
|
| 543 |
+
"--data_dir",
|
| 544 |
+
default=None,
|
| 545 |
+
type=str,
|
| 546 |
+
help="The input data dir. Should contain the .json files for the task."
|
| 547 |
+
+ "If no data dir or train/predict files are specified, will run with tensorflow_datasets.",
|
| 548 |
+
)
|
| 549 |
+
parser.add_argument(
|
| 550 |
+
"--train_file",
|
| 551 |
+
default=None,
|
| 552 |
+
type=str,
|
| 553 |
+
help="The input training file. If a data dir is specified, will look for the file there"
|
| 554 |
+
+ "If no data dir or train/predict files are specified, will run with tensorflow_datasets.",
|
| 555 |
+
)
|
| 556 |
+
parser.add_argument(
|
| 557 |
+
"--predict_file",
|
| 558 |
+
default=None,
|
| 559 |
+
type=str,
|
| 560 |
+
help="The input evaluation file. If a data dir is specified, will look for the file there"
|
| 561 |
+
+ "If no data dir or train/predict files are specified, will run with tensorflow_datasets.",
|
| 562 |
+
)
|
| 563 |
+
parser.add_argument(
|
| 564 |
+
"--config_name", default="", type=str, help="Pretrained config name or path if not the same as model_name"
|
| 565 |
+
)
|
| 566 |
+
parser.add_argument(
|
| 567 |
+
"--tokenizer_name",
|
| 568 |
+
default="",
|
| 569 |
+
type=str,
|
| 570 |
+
help="Pretrained tokenizer name or path if not the same as model_name",
|
| 571 |
+
)
|
| 572 |
+
parser.add_argument(
|
| 573 |
+
"--cache_dir",
|
| 574 |
+
default="",
|
| 575 |
+
type=str,
|
| 576 |
+
help="Where do you want to store the pre-trained models downloaded from huggingface.co",
|
| 577 |
+
)
|
| 578 |
+
|
| 579 |
+
parser.add_argument(
|
| 580 |
+
"--version_2_with_negative",
|
| 581 |
+
action="store_true",
|
| 582 |
+
help="If true, the SQuAD examples contain some that do not have an answer.",
|
| 583 |
+
)
|
| 584 |
+
parser.add_argument(
|
| 585 |
+
"--null_score_diff_threshold",
|
| 586 |
+
type=float,
|
| 587 |
+
default=0.0,
|
| 588 |
+
help="If null_score - best_non_null is greater than the threshold predict null.",
|
| 589 |
+
)
|
| 590 |
+
|
| 591 |
+
parser.add_argument(
|
| 592 |
+
"--max_seq_length",
|
| 593 |
+
default=384,
|
| 594 |
+
type=int,
|
| 595 |
+
help=(
|
| 596 |
+
"The maximum total input sequence length after WordPiece tokenization. Sequences "
|
| 597 |
+
"longer than this will be truncated, and sequences shorter than this will be padded."
|
| 598 |
+
),
|
| 599 |
+
)
|
| 600 |
+
parser.add_argument(
|
| 601 |
+
"--doc_stride",
|
| 602 |
+
default=128,
|
| 603 |
+
type=int,
|
| 604 |
+
help="When splitting up a long document into chunks, how much stride to take between chunks.",
|
| 605 |
+
)
|
| 606 |
+
parser.add_argument(
|
| 607 |
+
"--max_query_length",
|
| 608 |
+
default=64,
|
| 609 |
+
type=int,
|
| 610 |
+
help=(
|
| 611 |
+
"The maximum number of tokens for the question. Questions longer than this will "
|
| 612 |
+
"be truncated to this length."
|
| 613 |
+
),
|
| 614 |
+
)
|
| 615 |
+
parser.add_argument("--do_train", action="store_true", help="Whether to run training.")
|
| 616 |
+
parser.add_argument("--do_eval", action="store_true", help="Whether to run eval on the dev set.")
|
| 617 |
+
parser.add_argument(
|
| 618 |
+
"--evaluate_during_training", action="store_true", help="Rul evaluation during training at each logging step."
|
| 619 |
+
)
|
| 620 |
+
parser.add_argument(
|
| 621 |
+
"--do_lower_case", action="store_true", help="Set this flag if you are using an uncased model."
|
| 622 |
+
)
|
| 623 |
+
|
| 624 |
+
parser.add_argument("--per_gpu_train_batch_size", default=8, type=int, help="Batch size per GPU/CPU for training.")
|
| 625 |
+
parser.add_argument(
|
| 626 |
+
"--per_gpu_eval_batch_size", default=8, type=int, help="Batch size per GPU/CPU for evaluation."
|
| 627 |
+
)
|
| 628 |
+
parser.add_argument("--learning_rate", default=5e-5, type=float, help="The initial learning rate for Adam.")
|
| 629 |
+
parser.add_argument(
|
| 630 |
+
"--gradient_accumulation_steps",
|
| 631 |
+
type=int,
|
| 632 |
+
default=1,
|
| 633 |
+
help="Number of updates steps to accumulate before performing a backward/update pass.",
|
| 634 |
+
)
|
| 635 |
+
parser.add_argument("--weight_decay", default=0.0, type=float, help="Weight decay if we apply some.")
|
| 636 |
+
parser.add_argument("--adam_epsilon", default=1e-8, type=float, help="Epsilon for Adam optimizer.")
|
| 637 |
+
parser.add_argument("--max_grad_norm", default=1.0, type=float, help="Max gradient norm.")
|
| 638 |
+
parser.add_argument(
|
| 639 |
+
"--num_train_epochs", default=3.0, type=float, help="Total number of training epochs to perform."
|
| 640 |
+
)
|
| 641 |
+
parser.add_argument(
|
| 642 |
+
"--max_steps",
|
| 643 |
+
default=-1,
|
| 644 |
+
type=int,
|
| 645 |
+
help="If > 0: set total number of training steps to perform. Override num_train_epochs.",
|
| 646 |
+
)
|
| 647 |
+
parser.add_argument("--warmup_steps", default=0, type=int, help="Linear warmup over warmup_steps.")
|
| 648 |
+
parser.add_argument(
|
| 649 |
+
"--n_best_size",
|
| 650 |
+
default=20,
|
| 651 |
+
type=int,
|
| 652 |
+
help="The total number of n-best predictions to generate in the nbest_predictions.json output file.",
|
| 653 |
+
)
|
| 654 |
+
parser.add_argument(
|
| 655 |
+
"--max_answer_length",
|
| 656 |
+
default=30,
|
| 657 |
+
type=int,
|
| 658 |
+
help=(
|
| 659 |
+
"The maximum length of an answer that can be generated. This is needed because the start "
|
| 660 |
+
"and end predictions are not conditioned on one another."
|
| 661 |
+
),
|
| 662 |
+
)
|
| 663 |
+
parser.add_argument(
|
| 664 |
+
"--verbose_logging",
|
| 665 |
+
action="store_true",
|
| 666 |
+
help=(
|
| 667 |
+
"If true, all of the warnings related to data processing will be printed. "
|
| 668 |
+
"A number of warnings are expected for a normal SQuAD evaluation."
|
| 669 |
+
),
|
| 670 |
+
)
|
| 671 |
+
|
| 672 |
+
parser.add_argument("--logging_steps", type=int, default=50, help="Log every X updates steps.")
|
| 673 |
+
parser.add_argument("--save_steps", type=int, default=50, help="Save checkpoint every X updates steps.")
|
| 674 |
+
parser.add_argument(
|
| 675 |
+
"--eval_all_checkpoints",
|
| 676 |
+
action="store_true",
|
| 677 |
+
help="Evaluate all checkpoints starting with the same prefix as model_name ending and ending with step number",
|
| 678 |
+
)
|
| 679 |
+
parser.add_argument("--no_cuda", action="store_true", help="Whether not to use CUDA when available")
|
| 680 |
+
parser.add_argument(
|
| 681 |
+
"--overwrite_output_dir", action="store_true", help="Overwrite the content of the output directory"
|
| 682 |
+
)
|
| 683 |
+
parser.add_argument(
|
| 684 |
+
"--overwrite_cache", action="store_true", help="Overwrite the cached training and evaluation sets"
|
| 685 |
+
)
|
| 686 |
+
parser.add_argument("--seed", type=int, default=42, help="random seed for initialization")
|
| 687 |
+
|
| 688 |
+
parser.add_argument("--local_rank", type=int, default=-1, help="local_rank for distributed training on gpus")
|
| 689 |
+
parser.add_argument(
|
| 690 |
+
"--fp16",
|
| 691 |
+
action="store_true",
|
| 692 |
+
help="Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit",
|
| 693 |
+
)
|
| 694 |
+
parser.add_argument(
|
| 695 |
+
"--fp16_opt_level",
|
| 696 |
+
type=str,
|
| 697 |
+
default="O1",
|
| 698 |
+
help=(
|
| 699 |
+
"For fp16: Apex AMP optimization level selected in ['O0', 'O1', 'O2', and 'O3']. "
|
| 700 |
+
"See details at https://nvidia.github.io/apex/amp.html"
|
| 701 |
+
),
|
| 702 |
+
)
|
| 703 |
+
parser.add_argument("--server_ip", type=str, default="", help="Can be used for distant debugging.")
|
| 704 |
+
parser.add_argument("--server_port", type=str, default="", help="Can be used for distant debugging.")
|
| 705 |
+
|
| 706 |
+
parser.add_argument("--threads", type=int, default=1, help="multiple threads for converting example to features")
|
| 707 |
+
args = parser.parse_args()
|
| 708 |
+
|
| 709 |
+
if (
|
| 710 |
+
os.path.exists(args.output_dir)
|
| 711 |
+
and os.listdir(args.output_dir)
|
| 712 |
+
and args.do_train
|
| 713 |
+
and not args.overwrite_output_dir
|
| 714 |
+
):
|
| 715 |
+
raise ValueError(
|
| 716 |
+
"Output directory ({}) already exists and is not empty. Use --overwrite_output_dir to overcome.".format(
|
| 717 |
+
args.output_dir
|
| 718 |
+
)
|
| 719 |
+
)
|
| 720 |
+
|
| 721 |
+
# Setup distant debugging if needed
|
| 722 |
+
if args.server_ip and args.server_port:
|
| 723 |
+
# Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script
|
| 724 |
+
import ptvsd
|
| 725 |
+
|
| 726 |
+
print("Waiting for debugger attach")
|
| 727 |
+
ptvsd.enable_attach(address=(args.server_ip, args.server_port), redirect_output=True)
|
| 728 |
+
ptvsd.wait_for_attach()
|
| 729 |
+
|
| 730 |
+
# Setup CUDA, GPU & distributed training
|
| 731 |
+
if args.local_rank == -1 or args.no_cuda:
|
| 732 |
+
device = torch.device("cuda" if torch.cuda.is_available() and not args.no_cuda else "cpu")
|
| 733 |
+
args.n_gpu = 0 if args.no_cuda else torch.cuda.device_count()
|
| 734 |
+
else: # Initializes the distributed backend which will take care of synchronizing nodes/GPUs
|
| 735 |
+
torch.cuda.set_device(args.local_rank)
|
| 736 |
+
device = torch.device("cuda", args.local_rank)
|
| 737 |
+
torch.distributed.init_process_group(backend="nccl")
|
| 738 |
+
args.n_gpu = 1
|
| 739 |
+
args.device = device
|
| 740 |
+
|
| 741 |
+
# Setup logging
|
| 742 |
+
logging.basicConfig(
|
| 743 |
+
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
|
| 744 |
+
datefmt="%m/%d/%Y %H:%M:%S",
|
| 745 |
+
level=logging.INFO if args.local_rank in [-1, 0] else logging.WARN,
|
| 746 |
+
)
|
| 747 |
+
logger.warning(
|
| 748 |
+
"Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s",
|
| 749 |
+
args.local_rank,
|
| 750 |
+
device,
|
| 751 |
+
args.n_gpu,
|
| 752 |
+
bool(args.local_rank != -1),
|
| 753 |
+
args.fp16,
|
| 754 |
+
)
|
| 755 |
+
# Set the verbosity to info of the Transformers logger (on main process only):
|
| 756 |
+
if is_main_process(args.local_rank):
|
| 757 |
+
transformers.utils.logging.set_verbosity_info()
|
| 758 |
+
transformers.utils.logging.enable_default_handler()
|
| 759 |
+
transformers.utils.logging.enable_explicit_format()
|
| 760 |
+
# Set seed
|
| 761 |
+
set_seed(args)
|
| 762 |
+
|
| 763 |
+
# Load pretrained model and tokenizer
|
| 764 |
+
if args.local_rank not in [-1, 0]:
|
| 765 |
+
# Make sure only the first process in distributed training will download model & vocab
|
| 766 |
+
torch.distributed.barrier()
|
| 767 |
+
|
| 768 |
+
args.model_type = args.model_type.lower()
|
| 769 |
+
config_class, model_class, tokenizer_class = MODEL_CLASSES[args.model_type]
|
| 770 |
+
config = config_class.from_pretrained(
|
| 771 |
+
args.config_name if args.config_name else args.model_name_or_path,
|
| 772 |
+
cache_dir=args.cache_dir if args.cache_dir else None,
|
| 773 |
+
)
|
| 774 |
+
tokenizer = tokenizer_class.from_pretrained(
|
| 775 |
+
args.tokenizer_name if args.tokenizer_name else args.model_name_or_path,
|
| 776 |
+
do_lower_case=args.do_lower_case,
|
| 777 |
+
cache_dir=args.cache_dir if args.cache_dir else None,
|
| 778 |
+
)
|
| 779 |
+
model = model_class.from_pretrained(
|
| 780 |
+
args.model_name_or_path,
|
| 781 |
+
from_tf=bool(".ckpt" in args.model_name_or_path),
|
| 782 |
+
config=config,
|
| 783 |
+
cache_dir=args.cache_dir if args.cache_dir else None,
|
| 784 |
+
)
|
| 785 |
+
|
| 786 |
+
if args.teacher_type is not None:
|
| 787 |
+
assert args.teacher_name_or_path is not None
|
| 788 |
+
assert args.alpha_ce > 0.0
|
| 789 |
+
assert args.alpha_ce + args.alpha_squad > 0.0
|
| 790 |
+
assert args.teacher_type != "distilbert", "We constraint teachers not to be of type DistilBERT."
|
| 791 |
+
teacher_config_class, teacher_model_class, _ = MODEL_CLASSES[args.teacher_type]
|
| 792 |
+
teacher_config = teacher_config_class.from_pretrained(
|
| 793 |
+
args.teacher_name_or_path, cache_dir=args.cache_dir if args.cache_dir else None
|
| 794 |
+
)
|
| 795 |
+
teacher = teacher_model_class.from_pretrained(
|
| 796 |
+
args.teacher_name_or_path, config=teacher_config, cache_dir=args.cache_dir if args.cache_dir else None
|
| 797 |
+
)
|
| 798 |
+
teacher.to(args.device)
|
| 799 |
+
else:
|
| 800 |
+
teacher = None
|
| 801 |
+
|
| 802 |
+
if args.local_rank == 0:
|
| 803 |
+
# Make sure only the first process in distributed training will download model & vocab
|
| 804 |
+
torch.distributed.barrier()
|
| 805 |
+
|
| 806 |
+
model.to(args.device)
|
| 807 |
+
|
| 808 |
+
logger.info("Training/evaluation parameters %s", args)
|
| 809 |
+
|
| 810 |
+
# Before we do anything with models, we want to ensure that we get fp16 execution of torch.einsum if args.fp16 is set.
|
| 811 |
+
# Otherwise it'll default to "promote" mode, and we'll get fp32 operations. Note that running `--fp16_opt_level="O2"` will
|
| 812 |
+
# remove the need for this code, but it is still valid.
|
| 813 |
+
if args.fp16:
|
| 814 |
+
try:
|
| 815 |
+
import apex
|
| 816 |
+
|
| 817 |
+
apex.amp.register_half_function(torch, "einsum")
|
| 818 |
+
except ImportError:
|
| 819 |
+
raise ImportError("Please install apex from https://www.github.com/nvidia/apex to use fp16 training.")
|
| 820 |
+
|
| 821 |
+
# Training
|
| 822 |
+
if args.do_train:
|
| 823 |
+
train_dataset = load_and_cache_examples(args, tokenizer, evaluate=False, output_examples=False)
|
| 824 |
+
global_step, tr_loss = train(args, train_dataset, model, tokenizer, teacher=teacher)
|
| 825 |
+
logger.info(" global_step = %s, average loss = %s", global_step, tr_loss)
|
| 826 |
+
|
| 827 |
+
# Save the trained model and the tokenizer
|
| 828 |
+
if args.do_train and (args.local_rank == -1 or torch.distributed.get_rank() == 0):
|
| 829 |
+
logger.info("Saving model checkpoint to %s", args.output_dir)
|
| 830 |
+
# Save a trained model, configuration and tokenizer using `save_pretrained()`.
|
| 831 |
+
# They can then be reloaded using `from_pretrained()`
|
| 832 |
+
model_to_save = (
|
| 833 |
+
model.module if hasattr(model, "module") else model
|
| 834 |
+
) # Take care of distributed/parallel training
|
| 835 |
+
model_to_save.save_pretrained(args.output_dir)
|
| 836 |
+
tokenizer.save_pretrained(args.output_dir)
|
| 837 |
+
|
| 838 |
+
# Good practice: save your training arguments together with the trained model
|
| 839 |
+
torch.save(args, os.path.join(args.output_dir, "training_args.bin"))
|
| 840 |
+
|
| 841 |
+
# Load a trained model and vocabulary that you have fine-tuned
|
| 842 |
+
model = model_class.from_pretrained(args.output_dir)
|
| 843 |
+
tokenizer = tokenizer_class.from_pretrained(args.output_dir, do_lower_case=args.do_lower_case)
|
| 844 |
+
model.to(args.device)
|
| 845 |
+
|
| 846 |
+
# Evaluation - we can ask to evaluate all the checkpoints (sub-directories) in a directory
|
| 847 |
+
results = {}
|
| 848 |
+
if args.do_eval and args.local_rank in [-1, 0]:
|
| 849 |
+
if args.do_train:
|
| 850 |
+
logger.info("Loading checkpoints saved during training for evaluation")
|
| 851 |
+
checkpoints = [args.output_dir]
|
| 852 |
+
if args.eval_all_checkpoints:
|
| 853 |
+
checkpoints = [
|
| 854 |
+
os.path.dirname(c) for c in sorted(glob.glob(args.output_dir + "/**/" + WEIGHTS_NAME, recursive=True))
|
| 855 |
+
]
|
| 856 |
+
|
| 857 |
+
logger.info("Evaluate the following checkpoints: %s", checkpoints)
|
| 858 |
+
|
| 859 |
+
for checkpoint in checkpoints:
|
| 860 |
+
# Reload the model
|
| 861 |
+
global_step = checkpoint.split("-")[-1] if len(checkpoints) > 1 else ""
|
| 862 |
+
model = model_class.from_pretrained(checkpoint)
|
| 863 |
+
model.to(args.device)
|
| 864 |
+
|
| 865 |
+
# Evaluate
|
| 866 |
+
result = evaluate(args, model, tokenizer, prefix=global_step)
|
| 867 |
+
|
| 868 |
+
result = {k + ("_{}".format(global_step) if global_step else ""): v for k, v in result.items()}
|
| 869 |
+
results.update(result)
|
| 870 |
+
|
| 871 |
+
logger.info("Results: {}".format(results))
|
| 872 |
+
|
| 873 |
+
return results
|
| 874 |
+
|
| 875 |
+
|
| 876 |
+
if __name__ == "__main__":
|
| 877 |
+
main()
|
tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/distillation/scripts/binarized_data.py
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2019-present, the HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""
|
| 16 |
+
Preprocessing script before distillation.
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
import argparse
|
| 20 |
+
import logging
|
| 21 |
+
import pickle
|
| 22 |
+
import random
|
| 23 |
+
import time
|
| 24 |
+
|
| 25 |
+
import numpy as np
|
| 26 |
+
|
| 27 |
+
from transformers import BertTokenizer, GPT2Tokenizer, RobertaTokenizer
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
logging.basicConfig(
|
| 31 |
+
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", level=logging.INFO
|
| 32 |
+
)
|
| 33 |
+
logger = logging.getLogger(__name__)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def main():
|
| 37 |
+
parser = argparse.ArgumentParser(
|
| 38 |
+
description="Preprocess the data to avoid re-doing it several times by (tokenization + token_to_ids)."
|
| 39 |
+
)
|
| 40 |
+
parser.add_argument("--file_path", type=str, default="data/dump.txt", help="The path to the data.")
|
| 41 |
+
parser.add_argument("--tokenizer_type", type=str, default="bert", choices=["bert", "roberta", "gpt2"])
|
| 42 |
+
parser.add_argument("--tokenizer_name", type=str, default="bert-base-uncased", help="The tokenizer to use.")
|
| 43 |
+
parser.add_argument("--dump_file", type=str, default="data/dump", help="The dump file prefix.")
|
| 44 |
+
args = parser.parse_args()
|
| 45 |
+
|
| 46 |
+
logger.info(f"Loading Tokenizer ({args.tokenizer_name})")
|
| 47 |
+
if args.tokenizer_type == "bert":
|
| 48 |
+
tokenizer = BertTokenizer.from_pretrained(args.tokenizer_name)
|
| 49 |
+
bos = tokenizer.special_tokens_map["cls_token"] # `[CLS]`
|
| 50 |
+
sep = tokenizer.special_tokens_map["sep_token"] # `[SEP]`
|
| 51 |
+
elif args.tokenizer_type == "roberta":
|
| 52 |
+
tokenizer = RobertaTokenizer.from_pretrained(args.tokenizer_name)
|
| 53 |
+
bos = tokenizer.special_tokens_map["cls_token"] # `<s>`
|
| 54 |
+
sep = tokenizer.special_tokens_map["sep_token"] # `</s>`
|
| 55 |
+
elif args.tokenizer_type == "gpt2":
|
| 56 |
+
tokenizer = GPT2Tokenizer.from_pretrained(args.tokenizer_name)
|
| 57 |
+
bos = tokenizer.special_tokens_map["bos_token"] # `<|endoftext|>`
|
| 58 |
+
sep = tokenizer.special_tokens_map["eos_token"] # `<|endoftext|>`
|
| 59 |
+
|
| 60 |
+
logger.info(f"Loading text from {args.file_path}")
|
| 61 |
+
with open(args.file_path, "r", encoding="utf8") as fp:
|
| 62 |
+
data = fp.readlines()
|
| 63 |
+
|
| 64 |
+
logger.info("Start encoding")
|
| 65 |
+
logger.info(f"{len(data)} examples to process.")
|
| 66 |
+
|
| 67 |
+
rslt = []
|
| 68 |
+
iter = 0
|
| 69 |
+
interval = 10000
|
| 70 |
+
start = time.time()
|
| 71 |
+
for text in data:
|
| 72 |
+
text = f"{bos} {text.strip()} {sep}"
|
| 73 |
+
token_ids = tokenizer.encode(text, add_special_tokens=False)
|
| 74 |
+
rslt.append(token_ids)
|
| 75 |
+
|
| 76 |
+
iter += 1
|
| 77 |
+
if iter % interval == 0:
|
| 78 |
+
end = time.time()
|
| 79 |
+
logger.info(f"{iter} examples processed. - {(end-start):.2f}s/{interval}expl")
|
| 80 |
+
start = time.time()
|
| 81 |
+
logger.info("Finished binarization")
|
| 82 |
+
logger.info(f"{len(data)} examples processed.")
|
| 83 |
+
|
| 84 |
+
dp_file = f"{args.dump_file}.{args.tokenizer_name}.pickle"
|
| 85 |
+
vocab_size = tokenizer.vocab_size
|
| 86 |
+
if vocab_size < (1 << 16):
|
| 87 |
+
rslt_ = [np.uint16(d) for d in rslt]
|
| 88 |
+
else:
|
| 89 |
+
rslt_ = [np.int32(d) for d in rslt]
|
| 90 |
+
random.shuffle(rslt_)
|
| 91 |
+
logger.info(f"Dump to {dp_file}")
|
| 92 |
+
with open(dp_file, "wb") as handle:
|
| 93 |
+
pickle.dump(rslt_, handle, protocol=pickle.HIGHEST_PROTOCOL)
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
if __name__ == "__main__":
|
| 97 |
+
main()
|
tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/distillation/scripts/extract.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2019-present, the HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""
|
| 16 |
+
Preprocessing script before training the distilled model.
|
| 17 |
+
Specific to RoBERTa -> DistilRoBERTa and GPT2 -> DistilGPT2.
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
import argparse
|
| 21 |
+
|
| 22 |
+
import torch
|
| 23 |
+
|
| 24 |
+
from transformers import GPT2LMHeadModel, RobertaForMaskedLM
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
if __name__ == "__main__":
|
| 28 |
+
parser = argparse.ArgumentParser(
|
| 29 |
+
description=(
|
| 30 |
+
"Extraction some layers of the full RobertaForMaskedLM or GPT2LMHeadModel for Transfer Learned"
|
| 31 |
+
" Distillation"
|
| 32 |
+
)
|
| 33 |
+
)
|
| 34 |
+
parser.add_argument("--model_type", default="roberta", choices=["roberta", "gpt2"])
|
| 35 |
+
parser.add_argument("--model_name", default="roberta-large", type=str)
|
| 36 |
+
parser.add_argument("--dump_checkpoint", default="serialization_dir/tf_roberta_048131723.pth", type=str)
|
| 37 |
+
parser.add_argument("--vocab_transform", action="store_true")
|
| 38 |
+
args = parser.parse_args()
|
| 39 |
+
|
| 40 |
+
if args.model_type == "roberta":
|
| 41 |
+
model = RobertaForMaskedLM.from_pretrained(args.model_name)
|
| 42 |
+
prefix = "roberta"
|
| 43 |
+
elif args.model_type == "gpt2":
|
| 44 |
+
model = GPT2LMHeadModel.from_pretrained(args.model_name)
|
| 45 |
+
prefix = "transformer"
|
| 46 |
+
|
| 47 |
+
state_dict = model.state_dict()
|
| 48 |
+
compressed_sd = {}
|
| 49 |
+
|
| 50 |
+
# Embeddings #
|
| 51 |
+
if args.model_type == "gpt2":
|
| 52 |
+
for param_name in ["wte.weight", "wpe.weight"]:
|
| 53 |
+
compressed_sd[f"{prefix}.{param_name}"] = state_dict[f"{prefix}.{param_name}"]
|
| 54 |
+
else:
|
| 55 |
+
for w in ["word_embeddings", "position_embeddings", "token_type_embeddings"]:
|
| 56 |
+
param_name = f"{prefix}.embeddings.{w}.weight"
|
| 57 |
+
compressed_sd[param_name] = state_dict[param_name]
|
| 58 |
+
for w in ["weight", "bias"]:
|
| 59 |
+
param_name = f"{prefix}.embeddings.LayerNorm.{w}"
|
| 60 |
+
compressed_sd[param_name] = state_dict[param_name]
|
| 61 |
+
|
| 62 |
+
# Transformer Blocks #
|
| 63 |
+
std_idx = 0
|
| 64 |
+
for teacher_idx in [0, 2, 4, 7, 9, 11]:
|
| 65 |
+
if args.model_type == "gpt2":
|
| 66 |
+
for layer in ["ln_1", "attn.c_attn", "attn.c_proj", "ln_2", "mlp.c_fc", "mlp.c_proj"]:
|
| 67 |
+
for w in ["weight", "bias"]:
|
| 68 |
+
compressed_sd[f"{prefix}.h.{std_idx}.{layer}.{w}"] = state_dict[
|
| 69 |
+
f"{prefix}.h.{teacher_idx}.{layer}.{w}"
|
| 70 |
+
]
|
| 71 |
+
compressed_sd[f"{prefix}.h.{std_idx}.attn.bias"] = state_dict[f"{prefix}.h.{teacher_idx}.attn.bias"]
|
| 72 |
+
else:
|
| 73 |
+
for layer in [
|
| 74 |
+
"attention.self.query",
|
| 75 |
+
"attention.self.key",
|
| 76 |
+
"attention.self.value",
|
| 77 |
+
"attention.output.dense",
|
| 78 |
+
"attention.output.LayerNorm",
|
| 79 |
+
"intermediate.dense",
|
| 80 |
+
"output.dense",
|
| 81 |
+
"output.LayerNorm",
|
| 82 |
+
]:
|
| 83 |
+
for w in ["weight", "bias"]:
|
| 84 |
+
compressed_sd[f"{prefix}.encoder.layer.{std_idx}.{layer}.{w}"] = state_dict[
|
| 85 |
+
f"{prefix}.encoder.layer.{teacher_idx}.{layer}.{w}"
|
| 86 |
+
]
|
| 87 |
+
std_idx += 1
|
| 88 |
+
|
| 89 |
+
# Language Modeling Head ###s
|
| 90 |
+
if args.model_type == "roberta":
|
| 91 |
+
for layer in ["lm_head.decoder.weight", "lm_head.bias"]:
|
| 92 |
+
compressed_sd[f"{layer}"] = state_dict[f"{layer}"]
|
| 93 |
+
if args.vocab_transform:
|
| 94 |
+
for w in ["weight", "bias"]:
|
| 95 |
+
compressed_sd[f"lm_head.dense.{w}"] = state_dict[f"lm_head.dense.{w}"]
|
| 96 |
+
compressed_sd[f"lm_head.layer_norm.{w}"] = state_dict[f"lm_head.layer_norm.{w}"]
|
| 97 |
+
elif args.model_type == "gpt2":
|
| 98 |
+
for w in ["weight", "bias"]:
|
| 99 |
+
compressed_sd[f"{prefix}.ln_f.{w}"] = state_dict[f"{prefix}.ln_f.{w}"]
|
| 100 |
+
compressed_sd["lm_head.weight"] = state_dict["lm_head.weight"]
|
| 101 |
+
|
| 102 |
+
print(f"N layers selected for distillation: {std_idx}")
|
| 103 |
+
print(f"Number of params transferred for distillation: {len(compressed_sd.keys())}")
|
| 104 |
+
|
| 105 |
+
print(f"Save transferred checkpoint to {args.dump_checkpoint}.")
|
| 106 |
+
torch.save(compressed_sd, args.dump_checkpoint)
|
tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/distillation/scripts/extract_distilbert.py
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2019-present, the HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""
|
| 16 |
+
Preprocessing script before training DistilBERT.
|
| 17 |
+
Specific to BERT -> DistilBERT.
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
import argparse
|
| 21 |
+
|
| 22 |
+
import torch
|
| 23 |
+
|
| 24 |
+
from transformers import BertForMaskedLM
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
if __name__ == "__main__":
|
| 28 |
+
parser = argparse.ArgumentParser(
|
| 29 |
+
description=(
|
| 30 |
+
"Extraction some layers of the full BertForMaskedLM or RObertaForMaskedLM for Transfer Learned"
|
| 31 |
+
" Distillation"
|
| 32 |
+
)
|
| 33 |
+
)
|
| 34 |
+
parser.add_argument("--model_type", default="bert", choices=["bert"])
|
| 35 |
+
parser.add_argument("--model_name", default="bert-base-uncased", type=str)
|
| 36 |
+
parser.add_argument("--dump_checkpoint", default="serialization_dir/tf_bert-base-uncased_0247911.pth", type=str)
|
| 37 |
+
parser.add_argument("--vocab_transform", action="store_true")
|
| 38 |
+
args = parser.parse_args()
|
| 39 |
+
|
| 40 |
+
if args.model_type == "bert":
|
| 41 |
+
model = BertForMaskedLM.from_pretrained(args.model_name)
|
| 42 |
+
prefix = "bert"
|
| 43 |
+
else:
|
| 44 |
+
raise ValueError('args.model_type should be "bert".')
|
| 45 |
+
|
| 46 |
+
state_dict = model.state_dict()
|
| 47 |
+
compressed_sd = {}
|
| 48 |
+
|
| 49 |
+
for w in ["word_embeddings", "position_embeddings"]:
|
| 50 |
+
compressed_sd[f"distilbert.embeddings.{w}.weight"] = state_dict[f"{prefix}.embeddings.{w}.weight"]
|
| 51 |
+
for w in ["weight", "bias"]:
|
| 52 |
+
compressed_sd[f"distilbert.embeddings.LayerNorm.{w}"] = state_dict[f"{prefix}.embeddings.LayerNorm.{w}"]
|
| 53 |
+
|
| 54 |
+
std_idx = 0
|
| 55 |
+
for teacher_idx in [0, 2, 4, 7, 9, 11]:
|
| 56 |
+
for w in ["weight", "bias"]:
|
| 57 |
+
compressed_sd[f"distilbert.transformer.layer.{std_idx}.attention.q_lin.{w}"] = state_dict[
|
| 58 |
+
f"{prefix}.encoder.layer.{teacher_idx}.attention.self.query.{w}"
|
| 59 |
+
]
|
| 60 |
+
compressed_sd[f"distilbert.transformer.layer.{std_idx}.attention.k_lin.{w}"] = state_dict[
|
| 61 |
+
f"{prefix}.encoder.layer.{teacher_idx}.attention.self.key.{w}"
|
| 62 |
+
]
|
| 63 |
+
compressed_sd[f"distilbert.transformer.layer.{std_idx}.attention.v_lin.{w}"] = state_dict[
|
| 64 |
+
f"{prefix}.encoder.layer.{teacher_idx}.attention.self.value.{w}"
|
| 65 |
+
]
|
| 66 |
+
|
| 67 |
+
compressed_sd[f"distilbert.transformer.layer.{std_idx}.attention.out_lin.{w}"] = state_dict[
|
| 68 |
+
f"{prefix}.encoder.layer.{teacher_idx}.attention.output.dense.{w}"
|
| 69 |
+
]
|
| 70 |
+
compressed_sd[f"distilbert.transformer.layer.{std_idx}.sa_layer_norm.{w}"] = state_dict[
|
| 71 |
+
f"{prefix}.encoder.layer.{teacher_idx}.attention.output.LayerNorm.{w}"
|
| 72 |
+
]
|
| 73 |
+
|
| 74 |
+
compressed_sd[f"distilbert.transformer.layer.{std_idx}.ffn.lin1.{w}"] = state_dict[
|
| 75 |
+
f"{prefix}.encoder.layer.{teacher_idx}.intermediate.dense.{w}"
|
| 76 |
+
]
|
| 77 |
+
compressed_sd[f"distilbert.transformer.layer.{std_idx}.ffn.lin2.{w}"] = state_dict[
|
| 78 |
+
f"{prefix}.encoder.layer.{teacher_idx}.output.dense.{w}"
|
| 79 |
+
]
|
| 80 |
+
compressed_sd[f"distilbert.transformer.layer.{std_idx}.output_layer_norm.{w}"] = state_dict[
|
| 81 |
+
f"{prefix}.encoder.layer.{teacher_idx}.output.LayerNorm.{w}"
|
| 82 |
+
]
|
| 83 |
+
std_idx += 1
|
| 84 |
+
|
| 85 |
+
compressed_sd["vocab_projector.weight"] = state_dict["cls.predictions.decoder.weight"]
|
| 86 |
+
compressed_sd["vocab_projector.bias"] = state_dict["cls.predictions.bias"]
|
| 87 |
+
if args.vocab_transform:
|
| 88 |
+
for w in ["weight", "bias"]:
|
| 89 |
+
compressed_sd[f"vocab_transform.{w}"] = state_dict[f"cls.predictions.transform.dense.{w}"]
|
| 90 |
+
compressed_sd[f"vocab_layer_norm.{w}"] = state_dict[f"cls.predictions.transform.LayerNorm.{w}"]
|
| 91 |
+
|
| 92 |
+
print(f"N layers selected for distillation: {std_idx}")
|
| 93 |
+
print(f"Number of params transferred for distillation: {len(compressed_sd.keys())}")
|
| 94 |
+
|
| 95 |
+
print(f"Save transferred checkpoint to {args.dump_checkpoint}.")
|
| 96 |
+
torch.save(compressed_sd, args.dump_checkpoint)
|
tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/distillation/scripts/token_counts.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2019-present, the HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""
|
| 16 |
+
Preprocessing script before training the distilled model.
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
import argparse
|
| 20 |
+
import logging
|
| 21 |
+
import pickle
|
| 22 |
+
from collections import Counter
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
logging.basicConfig(
|
| 26 |
+
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", level=logging.INFO
|
| 27 |
+
)
|
| 28 |
+
logger = logging.getLogger(__name__)
|
| 29 |
+
|
| 30 |
+
if __name__ == "__main__":
|
| 31 |
+
parser = argparse.ArgumentParser(
|
| 32 |
+
description="Token Counts for smoothing the masking probabilities in MLM (cf XLM/word2vec)"
|
| 33 |
+
)
|
| 34 |
+
parser.add_argument(
|
| 35 |
+
"--data_file", type=str, default="data/dump.bert-base-uncased.pickle", help="The binarized dataset."
|
| 36 |
+
)
|
| 37 |
+
parser.add_argument(
|
| 38 |
+
"--token_counts_dump", type=str, default="data/token_counts.bert-base-uncased.pickle", help="The dump file."
|
| 39 |
+
)
|
| 40 |
+
parser.add_argument("--vocab_size", default=30522, type=int)
|
| 41 |
+
args = parser.parse_args()
|
| 42 |
+
|
| 43 |
+
logger.info(f"Loading data from {args.data_file}")
|
| 44 |
+
with open(args.data_file, "rb") as fp:
|
| 45 |
+
data = pickle.load(fp)
|
| 46 |
+
|
| 47 |
+
logger.info("Counting occurrences for MLM.")
|
| 48 |
+
counter = Counter()
|
| 49 |
+
for tk_ids in data:
|
| 50 |
+
counter.update(tk_ids)
|
| 51 |
+
counts = [0] * args.vocab_size
|
| 52 |
+
for k, v in counter.items():
|
| 53 |
+
counts[k] = v
|
| 54 |
+
|
| 55 |
+
logger.info(f"Dump to {args.token_counts_dump}")
|
| 56 |
+
with open(args.token_counts_dump, "wb") as handle:
|
| 57 |
+
pickle.dump(counts, handle, protocol=pickle.HIGHEST_PROTOCOL)
|
tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/distillation/train.py
ADDED
|
@@ -0,0 +1,325 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2019-present, the HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""
|
| 16 |
+
Training the distilled model.
|
| 17 |
+
Supported architectures include: BERT -> DistilBERT, RoBERTa -> DistilRoBERTa, GPT2 -> DistilGPT2.
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
import argparse
|
| 21 |
+
import json
|
| 22 |
+
import os
|
| 23 |
+
import pickle
|
| 24 |
+
import shutil
|
| 25 |
+
|
| 26 |
+
import numpy as np
|
| 27 |
+
import torch
|
| 28 |
+
from distiller import Distiller
|
| 29 |
+
from lm_seqs_dataset import LmSeqsDataset
|
| 30 |
+
|
| 31 |
+
from transformers import (
|
| 32 |
+
BertConfig,
|
| 33 |
+
BertForMaskedLM,
|
| 34 |
+
BertTokenizer,
|
| 35 |
+
DistilBertConfig,
|
| 36 |
+
DistilBertForMaskedLM,
|
| 37 |
+
DistilBertTokenizer,
|
| 38 |
+
GPT2Config,
|
| 39 |
+
GPT2LMHeadModel,
|
| 40 |
+
GPT2Tokenizer,
|
| 41 |
+
RobertaConfig,
|
| 42 |
+
RobertaForMaskedLM,
|
| 43 |
+
RobertaTokenizer,
|
| 44 |
+
)
|
| 45 |
+
from utils import git_log, init_gpu_params, logger, set_seed
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
MODEL_CLASSES = {
|
| 49 |
+
"distilbert": (DistilBertConfig, DistilBertForMaskedLM, DistilBertTokenizer),
|
| 50 |
+
"roberta": (RobertaConfig, RobertaForMaskedLM, RobertaTokenizer),
|
| 51 |
+
"bert": (BertConfig, BertForMaskedLM, BertTokenizer),
|
| 52 |
+
"gpt2": (GPT2Config, GPT2LMHeadModel, GPT2Tokenizer),
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def sanity_checks(args):
|
| 57 |
+
"""
|
| 58 |
+
A bunch of args sanity checks to perform even starting...
|
| 59 |
+
"""
|
| 60 |
+
assert (args.mlm and args.alpha_mlm > 0.0) or (not args.mlm and args.alpha_mlm == 0.0)
|
| 61 |
+
assert (args.alpha_mlm > 0.0 and args.alpha_clm == 0.0) or (args.alpha_mlm == 0.0 and args.alpha_clm > 0.0)
|
| 62 |
+
if args.mlm:
|
| 63 |
+
assert os.path.isfile(args.token_counts)
|
| 64 |
+
assert (args.student_type in ["roberta", "distilbert"]) and (args.teacher_type in ["roberta", "bert"])
|
| 65 |
+
else:
|
| 66 |
+
assert (args.student_type in ["gpt2"]) and (args.teacher_type in ["gpt2"])
|
| 67 |
+
|
| 68 |
+
assert args.teacher_type == args.student_type or (
|
| 69 |
+
args.student_type == "distilbert" and args.teacher_type == "bert"
|
| 70 |
+
)
|
| 71 |
+
assert os.path.isfile(args.student_config)
|
| 72 |
+
if args.student_pretrained_weights is not None:
|
| 73 |
+
assert os.path.isfile(args.student_pretrained_weights)
|
| 74 |
+
|
| 75 |
+
if args.freeze_token_type_embds:
|
| 76 |
+
assert args.student_type in ["roberta"]
|
| 77 |
+
|
| 78 |
+
assert args.alpha_ce >= 0.0
|
| 79 |
+
assert args.alpha_mlm >= 0.0
|
| 80 |
+
assert args.alpha_clm >= 0.0
|
| 81 |
+
assert args.alpha_mse >= 0.0
|
| 82 |
+
assert args.alpha_cos >= 0.0
|
| 83 |
+
assert args.alpha_ce + args.alpha_mlm + args.alpha_clm + args.alpha_mse + args.alpha_cos > 0.0
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def freeze_pos_embeddings(student, args):
|
| 87 |
+
if args.student_type == "roberta":
|
| 88 |
+
student.roberta.embeddings.position_embeddings.weight.requires_grad = False
|
| 89 |
+
elif args.student_type == "gpt2":
|
| 90 |
+
student.transformer.wpe.weight.requires_grad = False
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def freeze_token_type_embeddings(student, args):
|
| 94 |
+
if args.student_type == "roberta":
|
| 95 |
+
student.roberta.embeddings.token_type_embeddings.weight.requires_grad = False
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def main():
|
| 99 |
+
parser = argparse.ArgumentParser(description="Training")
|
| 100 |
+
parser.add_argument("--force", action="store_true", help="Overwrite dump_path if it already exists.")
|
| 101 |
+
|
| 102 |
+
parser.add_argument(
|
| 103 |
+
"--dump_path", type=str, required=True, help="The output directory (log, checkpoints, parameters, etc.)"
|
| 104 |
+
)
|
| 105 |
+
parser.add_argument(
|
| 106 |
+
"--data_file",
|
| 107 |
+
type=str,
|
| 108 |
+
required=True,
|
| 109 |
+
help="The binarized file (tokenized + tokens_to_ids) and grouped by sequence.",
|
| 110 |
+
)
|
| 111 |
+
|
| 112 |
+
parser.add_argument(
|
| 113 |
+
"--student_type",
|
| 114 |
+
type=str,
|
| 115 |
+
choices=["distilbert", "roberta", "gpt2"],
|
| 116 |
+
required=True,
|
| 117 |
+
help="The student type (DistilBERT, RoBERTa).",
|
| 118 |
+
)
|
| 119 |
+
parser.add_argument("--student_config", type=str, required=True, help="Path to the student configuration.")
|
| 120 |
+
parser.add_argument(
|
| 121 |
+
"--student_pretrained_weights", default=None, type=str, help="Load student initialization checkpoint."
|
| 122 |
+
)
|
| 123 |
+
|
| 124 |
+
parser.add_argument(
|
| 125 |
+
"--teacher_type", choices=["bert", "roberta", "gpt2"], required=True, help="Teacher type (BERT, RoBERTa)."
|
| 126 |
+
)
|
| 127 |
+
parser.add_argument("--teacher_name", type=str, required=True, help="The teacher model.")
|
| 128 |
+
|
| 129 |
+
parser.add_argument("--temperature", default=2.0, type=float, help="Temperature for the softmax temperature.")
|
| 130 |
+
parser.add_argument(
|
| 131 |
+
"--alpha_ce", default=0.5, type=float, help="Linear weight for the distillation loss. Must be >=0."
|
| 132 |
+
)
|
| 133 |
+
parser.add_argument(
|
| 134 |
+
"--alpha_mlm",
|
| 135 |
+
default=0.0,
|
| 136 |
+
type=float,
|
| 137 |
+
help="Linear weight for the MLM loss. Must be >=0. Should be used in conjunction with `mlm` flag.",
|
| 138 |
+
)
|
| 139 |
+
parser.add_argument("--alpha_clm", default=0.5, type=float, help="Linear weight for the CLM loss. Must be >=0.")
|
| 140 |
+
parser.add_argument("--alpha_mse", default=0.0, type=float, help="Linear weight of the MSE loss. Must be >=0.")
|
| 141 |
+
parser.add_argument(
|
| 142 |
+
"--alpha_cos", default=0.0, type=float, help="Linear weight of the cosine embedding loss. Must be >=0."
|
| 143 |
+
)
|
| 144 |
+
|
| 145 |
+
parser.add_argument(
|
| 146 |
+
"--mlm", action="store_true", help="The LM step: MLM or CLM. If `mlm` is True, the MLM is used over CLM."
|
| 147 |
+
)
|
| 148 |
+
parser.add_argument(
|
| 149 |
+
"--mlm_mask_prop",
|
| 150 |
+
default=0.15,
|
| 151 |
+
type=float,
|
| 152 |
+
help="Proportion of tokens for which we need to make a prediction.",
|
| 153 |
+
)
|
| 154 |
+
parser.add_argument("--word_mask", default=0.8, type=float, help="Proportion of tokens to mask out.")
|
| 155 |
+
parser.add_argument("--word_keep", default=0.1, type=float, help="Proportion of tokens to keep.")
|
| 156 |
+
parser.add_argument("--word_rand", default=0.1, type=float, help="Proportion of tokens to randomly replace.")
|
| 157 |
+
parser.add_argument(
|
| 158 |
+
"--mlm_smoothing",
|
| 159 |
+
default=0.7,
|
| 160 |
+
type=float,
|
| 161 |
+
help="Smoothing parameter to emphasize more rare tokens (see XLM, similar to word2vec).",
|
| 162 |
+
)
|
| 163 |
+
parser.add_argument("--token_counts", type=str, help="The token counts in the data_file for MLM.")
|
| 164 |
+
|
| 165 |
+
parser.add_argument(
|
| 166 |
+
"--restrict_ce_to_mask",
|
| 167 |
+
action="store_true",
|
| 168 |
+
help="If true, compute the distillation loss only the [MLM] prediction distribution.",
|
| 169 |
+
)
|
| 170 |
+
parser.add_argument(
|
| 171 |
+
"--freeze_pos_embs",
|
| 172 |
+
action="store_true",
|
| 173 |
+
help="Freeze positional embeddings during distillation. For student_type in ['roberta', 'gpt2'] only.",
|
| 174 |
+
)
|
| 175 |
+
parser.add_argument(
|
| 176 |
+
"--freeze_token_type_embds",
|
| 177 |
+
action="store_true",
|
| 178 |
+
help="Freeze token type embeddings during distillation if existent. For student_type in ['roberta'] only.",
|
| 179 |
+
)
|
| 180 |
+
|
| 181 |
+
parser.add_argument("--n_epoch", type=int, default=3, help="Number of pass on the whole dataset.")
|
| 182 |
+
parser.add_argument("--batch_size", type=int, default=5, help="Batch size (for each process).")
|
| 183 |
+
parser.add_argument(
|
| 184 |
+
"--group_by_size",
|
| 185 |
+
action="store_false",
|
| 186 |
+
help="If true, group sequences that have similar length into the same batch. Default is true.",
|
| 187 |
+
)
|
| 188 |
+
|
| 189 |
+
parser.add_argument(
|
| 190 |
+
"--gradient_accumulation_steps",
|
| 191 |
+
type=int,
|
| 192 |
+
default=50,
|
| 193 |
+
help="Gradient accumulation for larger training batches.",
|
| 194 |
+
)
|
| 195 |
+
parser.add_argument("--warmup_prop", default=0.05, type=float, help="Linear warmup proportion.")
|
| 196 |
+
parser.add_argument("--weight_decay", default=0.0, type=float, help="Weight decay if we apply some.")
|
| 197 |
+
parser.add_argument("--learning_rate", default=5e-4, type=float, help="The initial learning rate for Adam.")
|
| 198 |
+
parser.add_argument("--adam_epsilon", default=1e-6, type=float, help="Epsilon for Adam optimizer.")
|
| 199 |
+
parser.add_argument("--max_grad_norm", default=5.0, type=float, help="Max gradient norm.")
|
| 200 |
+
parser.add_argument("--initializer_range", default=0.02, type=float, help="Random initialization range.")
|
| 201 |
+
|
| 202 |
+
parser.add_argument(
|
| 203 |
+
"--fp16",
|
| 204 |
+
action="store_true",
|
| 205 |
+
help="Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit",
|
| 206 |
+
)
|
| 207 |
+
parser.add_argument(
|
| 208 |
+
"--fp16_opt_level",
|
| 209 |
+
type=str,
|
| 210 |
+
default="O1",
|
| 211 |
+
help=(
|
| 212 |
+
"For fp16: Apex AMP optimization level selected in ['O0', 'O1', 'O2', and 'O3']. "
|
| 213 |
+
"See details at https://nvidia.github.io/apex/amp.html"
|
| 214 |
+
),
|
| 215 |
+
)
|
| 216 |
+
parser.add_argument("--n_gpu", type=int, default=1, help="Number of GPUs in the node.")
|
| 217 |
+
parser.add_argument("--local_rank", type=int, default=-1, help="Distributed training - Local rank")
|
| 218 |
+
parser.add_argument("--seed", type=int, default=56, help="Random seed")
|
| 219 |
+
|
| 220 |
+
parser.add_argument("--log_interval", type=int, default=500, help="Tensorboard logging interval.")
|
| 221 |
+
parser.add_argument("--checkpoint_interval", type=int, default=4000, help="Checkpoint interval.")
|
| 222 |
+
args = parser.parse_args()
|
| 223 |
+
sanity_checks(args)
|
| 224 |
+
|
| 225 |
+
# ARGS #
|
| 226 |
+
init_gpu_params(args)
|
| 227 |
+
set_seed(args)
|
| 228 |
+
if args.is_master:
|
| 229 |
+
if os.path.exists(args.dump_path):
|
| 230 |
+
if not args.force:
|
| 231 |
+
raise ValueError(
|
| 232 |
+
f"Serialization dir {args.dump_path} already exists, but you have not precised wheter to overwrite"
|
| 233 |
+
" itUse `--force` if you want to overwrite it"
|
| 234 |
+
)
|
| 235 |
+
else:
|
| 236 |
+
shutil.rmtree(args.dump_path)
|
| 237 |
+
|
| 238 |
+
if not os.path.exists(args.dump_path):
|
| 239 |
+
os.makedirs(args.dump_path)
|
| 240 |
+
logger.info(f"Experiment will be dumped and logged in {args.dump_path}")
|
| 241 |
+
|
| 242 |
+
# SAVE PARAMS #
|
| 243 |
+
logger.info(f"Param: {args}")
|
| 244 |
+
with open(os.path.join(args.dump_path, "parameters.json"), "w") as f:
|
| 245 |
+
json.dump(vars(args), f, indent=4)
|
| 246 |
+
git_log(args.dump_path)
|
| 247 |
+
|
| 248 |
+
student_config_class, student_model_class, _ = MODEL_CLASSES[args.student_type]
|
| 249 |
+
teacher_config_class, teacher_model_class, teacher_tokenizer_class = MODEL_CLASSES[args.teacher_type]
|
| 250 |
+
|
| 251 |
+
# TOKENIZER #
|
| 252 |
+
tokenizer = teacher_tokenizer_class.from_pretrained(args.teacher_name)
|
| 253 |
+
special_tok_ids = {}
|
| 254 |
+
for tok_name, tok_symbol in tokenizer.special_tokens_map.items():
|
| 255 |
+
idx = tokenizer.all_special_tokens.index(tok_symbol)
|
| 256 |
+
special_tok_ids[tok_name] = tokenizer.all_special_ids[idx]
|
| 257 |
+
logger.info(f"Special tokens {special_tok_ids}")
|
| 258 |
+
args.special_tok_ids = special_tok_ids
|
| 259 |
+
args.max_model_input_size = tokenizer.max_model_input_sizes[args.teacher_name]
|
| 260 |
+
|
| 261 |
+
# DATA LOADER #
|
| 262 |
+
logger.info(f"Loading data from {args.data_file}")
|
| 263 |
+
with open(args.data_file, "rb") as fp:
|
| 264 |
+
data = pickle.load(fp)
|
| 265 |
+
|
| 266 |
+
if args.mlm:
|
| 267 |
+
logger.info(f"Loading token counts from {args.token_counts} (already pre-computed)")
|
| 268 |
+
with open(args.token_counts, "rb") as fp:
|
| 269 |
+
counts = pickle.load(fp)
|
| 270 |
+
|
| 271 |
+
token_probs = np.maximum(counts, 1) ** -args.mlm_smoothing
|
| 272 |
+
for idx in special_tok_ids.values():
|
| 273 |
+
token_probs[idx] = 0.0 # do not predict special tokens
|
| 274 |
+
token_probs = torch.from_numpy(token_probs)
|
| 275 |
+
else:
|
| 276 |
+
token_probs = None
|
| 277 |
+
|
| 278 |
+
train_lm_seq_dataset = LmSeqsDataset(params=args, data=data)
|
| 279 |
+
logger.info("Data loader created.")
|
| 280 |
+
|
| 281 |
+
# STUDENT #
|
| 282 |
+
logger.info(f"Loading student config from {args.student_config}")
|
| 283 |
+
stu_architecture_config = student_config_class.from_pretrained(args.student_config)
|
| 284 |
+
stu_architecture_config.output_hidden_states = True
|
| 285 |
+
|
| 286 |
+
if args.student_pretrained_weights is not None:
|
| 287 |
+
logger.info(f"Loading pretrained weights from {args.student_pretrained_weights}")
|
| 288 |
+
student = student_model_class.from_pretrained(args.student_pretrained_weights, config=stu_architecture_config)
|
| 289 |
+
else:
|
| 290 |
+
student = student_model_class(stu_architecture_config)
|
| 291 |
+
|
| 292 |
+
if args.n_gpu > 0:
|
| 293 |
+
student.to(f"cuda:{args.local_rank}")
|
| 294 |
+
logger.info("Student loaded.")
|
| 295 |
+
|
| 296 |
+
# TEACHER #
|
| 297 |
+
teacher = teacher_model_class.from_pretrained(args.teacher_name, output_hidden_states=True)
|
| 298 |
+
if args.n_gpu > 0:
|
| 299 |
+
teacher.to(f"cuda:{args.local_rank}")
|
| 300 |
+
logger.info(f"Teacher loaded from {args.teacher_name}.")
|
| 301 |
+
|
| 302 |
+
# FREEZING #
|
| 303 |
+
if args.freeze_pos_embs:
|
| 304 |
+
freeze_pos_embeddings(student, args)
|
| 305 |
+
if args.freeze_token_type_embds:
|
| 306 |
+
freeze_token_type_embeddings(student, args)
|
| 307 |
+
|
| 308 |
+
# SANITY CHECKS #
|
| 309 |
+
assert student.config.vocab_size == teacher.config.vocab_size
|
| 310 |
+
assert student.config.hidden_size == teacher.config.hidden_size
|
| 311 |
+
assert student.config.max_position_embeddings == teacher.config.max_position_embeddings
|
| 312 |
+
if args.mlm:
|
| 313 |
+
assert token_probs.size(0) == stu_architecture_config.vocab_size
|
| 314 |
+
|
| 315 |
+
# DISTILLER #
|
| 316 |
+
torch.cuda.empty_cache()
|
| 317 |
+
distiller = Distiller(
|
| 318 |
+
params=args, dataset=train_lm_seq_dataset, token_probs=token_probs, student=student, teacher=teacher
|
| 319 |
+
)
|
| 320 |
+
distiller.train()
|
| 321 |
+
logger.info("Let's go get some drinks.")
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
if __name__ == "__main__":
|
| 325 |
+
main()
|
tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/distillation/training_configs/distilbert-base-cased.json
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"activation": "gelu",
|
| 3 |
+
"attention_dropout": 0.1,
|
| 4 |
+
"dim": 768,
|
| 5 |
+
"dropout": 0.1,
|
| 6 |
+
"hidden_dim": 3072,
|
| 7 |
+
"initializer_range": 0.02,
|
| 8 |
+
"max_position_embeddings": 512,
|
| 9 |
+
"n_heads": 12,
|
| 10 |
+
"n_layers": 6,
|
| 11 |
+
"sinusoidal_pos_embds": true,
|
| 12 |
+
"tie_weights_": true,
|
| 13 |
+
"vocab_size": 28996
|
| 14 |
+
}
|
| 15 |
+
|
tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/distillation/training_configs/distilbert-base-multilingual-cased.json
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"activation": "gelu",
|
| 3 |
+
"attention_dropout": 0.1,
|
| 4 |
+
"dim": 768,
|
| 5 |
+
"dropout": 0.1,
|
| 6 |
+
"hidden_dim": 3072,
|
| 7 |
+
"initializer_range": 0.02,
|
| 8 |
+
"max_position_embeddings": 512,
|
| 9 |
+
"n_heads": 12,
|
| 10 |
+
"n_layers": 6,
|
| 11 |
+
"sinusoidal_pos_embds": true,
|
| 12 |
+
"tie_weights_": true,
|
| 13 |
+
"vocab_size": 119547
|
| 14 |
+
}
|
| 15 |
+
|
tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/distillation/training_configs/distilbert-base-uncased.json
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"activation": "gelu",
|
| 3 |
+
"attention_dropout": 0.1,
|
| 4 |
+
"dim": 768,
|
| 5 |
+
"dropout": 0.1,
|
| 6 |
+
"hidden_dim": 3072,
|
| 7 |
+
"initializer_range": 0.02,
|
| 8 |
+
"max_position_embeddings": 512,
|
| 9 |
+
"n_heads": 12,
|
| 10 |
+
"n_layers": 6,
|
| 11 |
+
"sinusoidal_pos_embds": true,
|
| 12 |
+
"tie_weights_": true,
|
| 13 |
+
"vocab_size": 30522
|
| 14 |
+
}
|
| 15 |
+
|
tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/distillation/training_configs/distilgpt2.json
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"initializer_range": 0.02,
|
| 3 |
+
"layer_norm_epsilon": 0.00001,
|
| 4 |
+
"n_embd": 768,
|
| 5 |
+
"n_head": 12,
|
| 6 |
+
"n_layer": 6,
|
| 7 |
+
"n_positions": 1024,
|
| 8 |
+
"vocab_size": 50257
|
| 9 |
+
}
|
tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/distillation/training_configs/distilroberta-base.json
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"vocab_size": 50265,
|
| 3 |
+
"hidden_size": 768,
|
| 4 |
+
"num_hidden_layers": 6,
|
| 5 |
+
"num_attention_heads": 12,
|
| 6 |
+
"intermediate_size": 3072,
|
| 7 |
+
"hidden_act": "gelu",
|
| 8 |
+
"hidden_dropout_prob": 0.1,
|
| 9 |
+
"attention_probs_dropout_prob": 0.1,
|
| 10 |
+
"max_position_embeddings": 514,
|
| 11 |
+
"type_vocab_size": 1,
|
| 12 |
+
"initializer_range": 0.02,
|
| 13 |
+
"layer_norm_eps": 0.00001
|
| 14 |
+
}
|
tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/distillation/utils.py
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2019-present, the HuggingFace Inc. team and Facebook, Inc.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Utils to train DistilBERT
|
| 16 |
+
adapted in part from Facebook, Inc XLM model (https://github.com/facebookresearch/XLM)
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
import json
|
| 20 |
+
import logging
|
| 21 |
+
import os
|
| 22 |
+
import socket
|
| 23 |
+
|
| 24 |
+
import git
|
| 25 |
+
import numpy as np
|
| 26 |
+
import torch
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
logging.basicConfig(
|
| 30 |
+
format="%(asctime)s - %(levelname)s - %(name)s - PID: %(process)d - %(message)s",
|
| 31 |
+
datefmt="%m/%d/%Y %H:%M:%S",
|
| 32 |
+
level=logging.INFO,
|
| 33 |
+
)
|
| 34 |
+
logger = logging.getLogger(__name__)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def git_log(folder_path: str):
|
| 38 |
+
"""
|
| 39 |
+
Log commit info.
|
| 40 |
+
"""
|
| 41 |
+
repo = git.Repo(search_parent_directories=True)
|
| 42 |
+
repo_infos = {
|
| 43 |
+
"repo_id": str(repo),
|
| 44 |
+
"repo_sha": str(repo.head.object.hexsha),
|
| 45 |
+
"repo_branch": str(repo.active_branch),
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
with open(os.path.join(folder_path, "git_log.json"), "w") as f:
|
| 49 |
+
json.dump(repo_infos, f, indent=4)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def init_gpu_params(params):
|
| 53 |
+
"""
|
| 54 |
+
Handle single and multi-GPU / multi-node.
|
| 55 |
+
"""
|
| 56 |
+
if params.n_gpu <= 0:
|
| 57 |
+
params.local_rank = 0
|
| 58 |
+
params.master_port = -1
|
| 59 |
+
params.is_master = True
|
| 60 |
+
params.multi_gpu = False
|
| 61 |
+
return
|
| 62 |
+
|
| 63 |
+
assert torch.cuda.is_available()
|
| 64 |
+
|
| 65 |
+
logger.info("Initializing GPUs")
|
| 66 |
+
if params.n_gpu > 1:
|
| 67 |
+
assert params.local_rank != -1
|
| 68 |
+
|
| 69 |
+
params.world_size = int(os.environ["WORLD_SIZE"])
|
| 70 |
+
params.n_gpu_per_node = int(os.environ["N_GPU_NODE"])
|
| 71 |
+
params.global_rank = int(os.environ["RANK"])
|
| 72 |
+
|
| 73 |
+
# number of nodes / node ID
|
| 74 |
+
params.n_nodes = params.world_size // params.n_gpu_per_node
|
| 75 |
+
params.node_id = params.global_rank // params.n_gpu_per_node
|
| 76 |
+
params.multi_gpu = True
|
| 77 |
+
|
| 78 |
+
assert params.n_nodes == int(os.environ["N_NODES"])
|
| 79 |
+
assert params.node_id == int(os.environ["NODE_RANK"])
|
| 80 |
+
|
| 81 |
+
# local job (single GPU)
|
| 82 |
+
else:
|
| 83 |
+
assert params.local_rank == -1
|
| 84 |
+
|
| 85 |
+
params.n_nodes = 1
|
| 86 |
+
params.node_id = 0
|
| 87 |
+
params.local_rank = 0
|
| 88 |
+
params.global_rank = 0
|
| 89 |
+
params.world_size = 1
|
| 90 |
+
params.n_gpu_per_node = 1
|
| 91 |
+
params.multi_gpu = False
|
| 92 |
+
|
| 93 |
+
# sanity checks
|
| 94 |
+
assert params.n_nodes >= 1
|
| 95 |
+
assert 0 <= params.node_id < params.n_nodes
|
| 96 |
+
assert 0 <= params.local_rank <= params.global_rank < params.world_size
|
| 97 |
+
assert params.world_size == params.n_nodes * params.n_gpu_per_node
|
| 98 |
+
|
| 99 |
+
# define whether this is the master process / if we are in multi-node distributed mode
|
| 100 |
+
params.is_master = params.node_id == 0 and params.local_rank == 0
|
| 101 |
+
params.multi_node = params.n_nodes > 1
|
| 102 |
+
|
| 103 |
+
# summary
|
| 104 |
+
PREFIX = f"--- Global rank: {params.global_rank} - "
|
| 105 |
+
logger.info(PREFIX + "Number of nodes: %i" % params.n_nodes)
|
| 106 |
+
logger.info(PREFIX + "Node ID : %i" % params.node_id)
|
| 107 |
+
logger.info(PREFIX + "Local rank : %i" % params.local_rank)
|
| 108 |
+
logger.info(PREFIX + "World size : %i" % params.world_size)
|
| 109 |
+
logger.info(PREFIX + "GPUs per node : %i" % params.n_gpu_per_node)
|
| 110 |
+
logger.info(PREFIX + "Master : %s" % str(params.is_master))
|
| 111 |
+
logger.info(PREFIX + "Multi-node : %s" % str(params.multi_node))
|
| 112 |
+
logger.info(PREFIX + "Multi-GPU : %s" % str(params.multi_gpu))
|
| 113 |
+
logger.info(PREFIX + "Hostname : %s" % socket.gethostname())
|
| 114 |
+
|
| 115 |
+
# set GPU device
|
| 116 |
+
torch.cuda.set_device(params.local_rank)
|
| 117 |
+
|
| 118 |
+
# initialize multi-GPU
|
| 119 |
+
if params.multi_gpu:
|
| 120 |
+
logger.info("Initializing PyTorch distributed")
|
| 121 |
+
torch.distributed.init_process_group(
|
| 122 |
+
init_method="env://",
|
| 123 |
+
backend="nccl",
|
| 124 |
+
)
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def set_seed(args):
|
| 128 |
+
"""
|
| 129 |
+
Set the random seed.
|
| 130 |
+
"""
|
| 131 |
+
np.random.seed(args.seed)
|
| 132 |
+
torch.manual_seed(args.seed)
|
| 133 |
+
if args.n_gpu > 0:
|
| 134 |
+
torch.cuda.manual_seed_all(args.seed)
|
tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/fsner/README.md
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<p align="center"> <img src="http://sayef.tech:8082/uploads/FSNER-LOGO-2.png" alt="FSNER LOGO"> </p>
|
| 2 |
+
|
| 3 |
+
<p align="center">
|
| 4 |
+
Implemented by <a href="https://huggingface.co/sayef"> sayef </a>.
|
| 5 |
+
</p>
|
| 6 |
+
|
| 7 |
+
## Overview
|
| 8 |
+
|
| 9 |
+
The FSNER model was proposed in [Example-Based Named Entity Recognition](https://arxiv.org/abs/2008.10570) by Morteza Ziyadi, Yuting Sun, Abhishek Goswami, Jade Huang, Weizhu Chen. To identify entity spans in a new domain, it uses a train-free few-shot learning approach inspired by question-answering.
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
## Abstract
|
| 14 |
+
----
|
| 15 |
+
> We present a novel approach to named entity recognition (NER) in the presence of scarce data that we call example-based NER. Our train-free few-shot learning approach takes inspiration from question-answering to identify entity spans in a new and unseen domain. In comparison with the current state-of-the-art, the proposed method performs significantly better, especially when using a low number of support examples.
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
## Model Training Details
|
| 20 |
+
-----
|
| 21 |
+
|
| 22 |
+
| identifier | epochs | datasets |
|
| 23 |
+
| ---------- |:----------:| :-----:|
|
| 24 |
+
| [sayef/fsner-bert-base-uncased](https://huggingface.co/sayef/fsner-bert-base-uncased) | 10 | ontonotes5, conll2003, wnut2017, and fin (Alvarado et al.). |
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
## Installation and Example Usage
|
| 28 |
+
------
|
| 29 |
+
|
| 30 |
+
You can use the FSNER model in 3 ways:
|
| 31 |
+
|
| 32 |
+
1. Install directly from PyPI: `pip install fsner` and import the model as shown in the code example below
|
| 33 |
+
|
| 34 |
+
or
|
| 35 |
+
|
| 36 |
+
2. Install from source: `python setup.py install` and import the model as shown in the code example below
|
| 37 |
+
|
| 38 |
+
or
|
| 39 |
+
|
| 40 |
+
3. Clone repo and change directory to `src` and import the model as shown in the code example below
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
```python
|
| 45 |
+
from fsner import FSNERModel, FSNERTokenizerUtils
|
| 46 |
+
|
| 47 |
+
model = FSNERModel("sayef/fsner-bert-base-uncased")
|
| 48 |
+
|
| 49 |
+
tokenizer = FSNERTokenizerUtils("sayef/fsner-bert-base-uncased")
|
| 50 |
+
|
| 51 |
+
# size of query and supports must be the same. If you want to find all the entitites in one particular query, just repeat the same query n times where n is equal to the number of supports (or entities).
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
query = [
|
| 55 |
+
'KWE 4000 can reach with a maximum speed from up to 450 P/min an accuracy from 50 mg',
|
| 56 |
+
'I would like to order a computer from eBay.',
|
| 57 |
+
]
|
| 58 |
+
|
| 59 |
+
# each list in supports are the examples of one entity type
|
| 60 |
+
# wrap entities around with [E] and [/E] in the examples
|
| 61 |
+
|
| 62 |
+
supports = [
|
| 63 |
+
[
|
| 64 |
+
'Horizontal flow wrapper [E] Pack 403 [/E] features the new retrofit-kit „paper-ON-form“',
|
| 65 |
+
'[E] Paloma Pick-and-Place-Roboter [/E] arranges the bakery products for the downstream tray-forming equipment',
|
| 66 |
+
'Finally, the new [E] Kliklok ACE [/E] carton former forms cartons and trays without the use of glue',
|
| 67 |
+
'We set up our pilot plant with the right [E] FibreForm® [/E] configuration to make prototypes for your marketing tests and package validation',
|
| 68 |
+
'The [E] CAR-T5 [/E] is a reliable, purely mechanically driven cartoning machine for versatile application fields'
|
| 69 |
+
],
|
| 70 |
+
[
|
| 71 |
+
"[E] Walmart [/E] is a leading e-commerce company",
|
| 72 |
+
"I recently ordered a book from [E] Amazon [/E]",
|
| 73 |
+
"I ordered this from [E] ShopClues [/E]",
|
| 74 |
+
"[E] Flipkart [/E] started it's journey from zero"
|
| 75 |
+
]
|
| 76 |
+
]
|
| 77 |
+
|
| 78 |
+
device = 'cpu'
|
| 79 |
+
|
| 80 |
+
W_query = tokenizer.tokenize(query).to(device)
|
| 81 |
+
W_supports = tokenizer.tokenize(supports).to(device)
|
| 82 |
+
|
| 83 |
+
start_prob, end_prob = model(W_query, W_supports)
|
| 84 |
+
|
| 85 |
+
output = tokenizer.extract_entity_from_scores(query, W_query, start_prob, end_prob, thresh=0.50)
|
| 86 |
+
|
| 87 |
+
print(output)
|
| 88 |
+
```
|
tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/fsner/pyproject.toml
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[build-system]
|
| 2 |
+
requires = [
|
| 3 |
+
"setuptools>=57.4.0",
|
| 4 |
+
"wheel>=0.37.0",
|
| 5 |
+
"transformers>=4.9.2"
|
| 6 |
+
]
|
| 7 |
+
build-backend = "setuptools.build_meta"
|
tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/fsner/requirements.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
transformers>=4.9.2
|
tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/fsner/setup.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import setuptools
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
with open("README.md", "r", encoding="utf-8") as fh:
|
| 5 |
+
long_description = fh.read()
|
| 6 |
+
|
| 7 |
+
setuptools.setup(
|
| 8 |
+
name="fsner",
|
| 9 |
+
version="0.0.1",
|
| 10 |
+
author="msi sayef",
|
| 11 |
+
author_email="msi.sayef@gmail.com",
|
| 12 |
+
description="Few-shot Named Entity Recognition",
|
| 13 |
+
long_description=long_description,
|
| 14 |
+
long_description_content_type="text/markdown",
|
| 15 |
+
url="https://github.com/huggingface/transformers/tree/main/examples/research_projects/fsner",
|
| 16 |
+
project_urls={
|
| 17 |
+
"Bug Tracker": "https://github.com/huggingface/transformers/issues",
|
| 18 |
+
},
|
| 19 |
+
classifiers=[
|
| 20 |
+
"Programming Language :: Python :: 3",
|
| 21 |
+
"Operating System :: OS Independent",
|
| 22 |
+
],
|
| 23 |
+
package_dir={"": "src"},
|
| 24 |
+
packages=setuptools.find_packages(where="src"),
|
| 25 |
+
python_requires=">=3.6",
|
| 26 |
+
install_requires=["torch>=1.9.0", "transformers>=4.9.2"],
|
| 27 |
+
)
|
tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/fsner/src/fsner/__init__.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .model import FSNERModel
|
| 2 |
+
from .tokenizer_utils import FSNERTokenizerUtils
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
__all__ = ["FSNERModel", "FSNERTokenizerUtils"]
|
tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/fsner/src/fsner/model.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
|
| 3 |
+
from transformers import AutoModel
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class FSNERModel(torch.nn.Module):
|
| 7 |
+
"""
|
| 8 |
+
The FSNER model implements a few-shot named entity recognition method from the paper `Example-Based Named Entity Recognition <https://arxiv.org/abs/2008.10570>`__ by
|
| 9 |
+
Morteza Ziyadi, Yuting Sun, Abhishek Goswami, Jade Huang, Weizhu Chen. To identify entity spans in a new domain, it
|
| 10 |
+
uses a train-free few-shot learning approach inspired by question-answering.
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
def __init__(self, pretrained_model_name_or_path="sayef/fsner-bert-base-uncased"):
|
| 14 |
+
super(FSNERModel, self).__init__()
|
| 15 |
+
|
| 16 |
+
self.bert = AutoModel.from_pretrained(pretrained_model_name_or_path, return_dict=True)
|
| 17 |
+
self.cos = torch.nn.CosineSimilarity(3, 1e-08)
|
| 18 |
+
self.softmax = torch.nn.Softmax(dim=1)
|
| 19 |
+
|
| 20 |
+
def BERT(self, **inputs):
|
| 21 |
+
return self.bert(**inputs).last_hidden_state
|
| 22 |
+
|
| 23 |
+
def VectorSum(self, token_embeddings):
|
| 24 |
+
return token_embeddings.sum(2, keepdim=True)
|
| 25 |
+
|
| 26 |
+
def Atten(self, q_rep, S_rep, T=1):
|
| 27 |
+
return self.softmax(T * self.cos(q_rep, S_rep))
|
| 28 |
+
|
| 29 |
+
def forward(self, W_query, W_supports):
|
| 30 |
+
"""
|
| 31 |
+
Find scores of each token being start and end token for an entity.
|
| 32 |
+
Args:
|
| 33 |
+
W_query (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 34 |
+
Indices of query sequence tokens in the vocabulary.
|
| 35 |
+
W_supports (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 36 |
+
Indices of support sequence tokens in the vocabulary.
|
| 37 |
+
Returns:
|
| 38 |
+
p_start (`torch.FloatTensor` of shape `(batch_size, sequence_length)`): Scores of each token as
|
| 39 |
+
being start token of an entity
|
| 40 |
+
p_end (`torch.FloatTensor` of shape `(batch_size, sequence_length)`): Scores of each token as
|
| 41 |
+
being end token of an entity
|
| 42 |
+
"""
|
| 43 |
+
|
| 44 |
+
support_sizes = W_supports["sizes"].tolist()
|
| 45 |
+
start_token_id = W_supports["start_token_id"].item()
|
| 46 |
+
end_token_id = W_supports["end_token_id"].item()
|
| 47 |
+
|
| 48 |
+
del W_supports["sizes"]
|
| 49 |
+
del W_supports["start_token_id"]
|
| 50 |
+
del W_supports["end_token_id"]
|
| 51 |
+
|
| 52 |
+
q = self.BERT(**W_query)
|
| 53 |
+
S = self.BERT(**W_supports)
|
| 54 |
+
|
| 55 |
+
p_starts = None
|
| 56 |
+
p_ends = None
|
| 57 |
+
|
| 58 |
+
start_token_masks = W_supports["input_ids"] == start_token_id
|
| 59 |
+
end_token_masks = W_supports["input_ids"] == end_token_id
|
| 60 |
+
|
| 61 |
+
for i, size in enumerate(support_sizes):
|
| 62 |
+
if i == 0:
|
| 63 |
+
s = 0
|
| 64 |
+
else:
|
| 65 |
+
s = support_sizes[i - 1]
|
| 66 |
+
|
| 67 |
+
s_start = S[s : s + size][start_token_masks[s : s + size]]
|
| 68 |
+
s_end = S[s : s + size][end_token_masks[s : s + size]]
|
| 69 |
+
|
| 70 |
+
p_start = torch.matmul(q[i], s_start.T).sum(1).softmax(0)
|
| 71 |
+
p_end = torch.matmul(q[i], s_end.T).sum(1).softmax(0)
|
| 72 |
+
|
| 73 |
+
if p_starts is not None:
|
| 74 |
+
p_starts = torch.vstack((p_starts, p_start))
|
| 75 |
+
p_ends = torch.vstack((p_ends, p_end))
|
| 76 |
+
else:
|
| 77 |
+
p_starts = p_start
|
| 78 |
+
p_ends = p_end
|
| 79 |
+
|
| 80 |
+
return p_starts, p_ends
|
tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/fsner/src/fsner/tokenizer_utils.py
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
|
| 3 |
+
from transformers import AutoTokenizer
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class FSNERTokenizerUtils:
|
| 7 |
+
def __init__(self, pretrained_model_name_or_path):
|
| 8 |
+
self.tokenizer = AutoTokenizer.from_pretrained(pretrained_model_name_or_path)
|
| 9 |
+
|
| 10 |
+
def tokenize(self, x):
|
| 11 |
+
"""
|
| 12 |
+
Wrapper function for tokenizing query and supports
|
| 13 |
+
Args:
|
| 14 |
+
x (`List[str] or List[List[str]]`):
|
| 15 |
+
List of strings for query or list of lists of strings for supports.
|
| 16 |
+
Returns:
|
| 17 |
+
`transformers.tokenization_utils_base.BatchEncoding` dict with additional keys and values for start_token_id, end_token_id and sizes of example lists for each entity type
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
if isinstance(x, list) and all(isinstance(_x, list) for _x in x):
|
| 21 |
+
d = None
|
| 22 |
+
for l in x:
|
| 23 |
+
t = self.tokenizer(
|
| 24 |
+
l,
|
| 25 |
+
padding="max_length",
|
| 26 |
+
max_length=384,
|
| 27 |
+
truncation=True,
|
| 28 |
+
return_tensors="pt",
|
| 29 |
+
)
|
| 30 |
+
t["sizes"] = torch.tensor([len(l)])
|
| 31 |
+
if d is not None:
|
| 32 |
+
for k in d.keys():
|
| 33 |
+
d[k] = torch.cat((d[k], t[k]), 0)
|
| 34 |
+
else:
|
| 35 |
+
d = t
|
| 36 |
+
|
| 37 |
+
d["start_token_id"] = torch.tensor(self.tokenizer.convert_tokens_to_ids("[E]"))
|
| 38 |
+
d["end_token_id"] = torch.tensor(self.tokenizer.convert_tokens_to_ids("[/E]"))
|
| 39 |
+
|
| 40 |
+
elif isinstance(x, list) and all(isinstance(_x, str) for _x in x):
|
| 41 |
+
d = self.tokenizer(
|
| 42 |
+
x,
|
| 43 |
+
padding="max_length",
|
| 44 |
+
max_length=384,
|
| 45 |
+
truncation=True,
|
| 46 |
+
return_tensors="pt",
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
else:
|
| 50 |
+
raise Exception(
|
| 51 |
+
"Type of parameter x was not recognized! Only `list of strings` for query or `list of lists of"
|
| 52 |
+
" strings` for supports are supported."
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
return d
|
| 56 |
+
|
| 57 |
+
def extract_entity_from_scores(self, query, W_query, p_start, p_end, thresh=0.70):
|
| 58 |
+
"""
|
| 59 |
+
Extracts entities from query and scores given a threshold.
|
| 60 |
+
Args:
|
| 61 |
+
query (`List[str]`):
|
| 62 |
+
List of query strings.
|
| 63 |
+
W_query (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 64 |
+
Indices of query sequence tokens in the vocabulary.
|
| 65 |
+
p_start (`torch.FloatTensor` of shape `(batch_size, sequence_length)`):
|
| 66 |
+
Scores of each token as being start token of an entity
|
| 67 |
+
p_end (`torch.FloatTensor` of shape `(batch_size, sequence_length)`):
|
| 68 |
+
Scores of each token as being end token of an entity
|
| 69 |
+
thresh (`float`):
|
| 70 |
+
Score threshold value
|
| 71 |
+
Returns:
|
| 72 |
+
A list of lists of tuples(decoded entity, score)
|
| 73 |
+
"""
|
| 74 |
+
|
| 75 |
+
final_outputs = []
|
| 76 |
+
for idx in range(len(W_query["input_ids"])):
|
| 77 |
+
start_indexes = end_indexes = range(p_start.shape[1])
|
| 78 |
+
|
| 79 |
+
output = []
|
| 80 |
+
for start_id in start_indexes:
|
| 81 |
+
for end_id in end_indexes:
|
| 82 |
+
if start_id < end_id:
|
| 83 |
+
output.append(
|
| 84 |
+
(
|
| 85 |
+
start_id,
|
| 86 |
+
end_id,
|
| 87 |
+
p_start[idx][start_id].item(),
|
| 88 |
+
p_end[idx][end_id].item(),
|
| 89 |
+
)
|
| 90 |
+
)
|
| 91 |
+
|
| 92 |
+
output.sort(key=lambda tup: (tup[2] * tup[3]), reverse=True)
|
| 93 |
+
temp = []
|
| 94 |
+
for k in range(len(output)):
|
| 95 |
+
if output[k][2] * output[k][3] >= thresh:
|
| 96 |
+
c_start_pos, c_end_pos = output[k][0], output[k][1]
|
| 97 |
+
decoded = self.tokenizer.decode(W_query["input_ids"][idx][c_start_pos:c_end_pos])
|
| 98 |
+
temp.append((decoded, output[k][2] * output[k][3]))
|
| 99 |
+
|
| 100 |
+
final_outputs.append(temp)
|
| 101 |
+
|
| 102 |
+
return final_outputs
|
tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/information-gain-filtration/README.md
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
# Information Gain Filtration(IGF)
|
| 3 |
+
|
| 4 |
+
Authors @Tuko @mraunak
|
| 5 |
+
|
| 6 |
+
This folder contains the code how to implement IGF for finetuning on GPT-2.
|
| 7 |
+
|
| 8 |
+
## What is IGF?
|
| 9 |
+
|
| 10 |
+
Here we present a general fine-tuning method that we call information gain filtration for improving the overall training efficiency and final
|
| 11 |
+
performance of language model fine-tuning(see paper below). The method is an alternative fine-tuning method that trains
|
| 12 |
+
a secondary model (e.g., a simple convolutional network) to predict the amount of information
|
| 13 |
+
gained over a given pre-trained model. The secondary model is lightweight and trained to
|
| 14 |
+
predict the Information Gain measure. Information Gain is defined as the change in a loss
|
| 15 |
+
function for a model before and after an SGD update with a sample (Equation X in the paper).
|
| 16 |
+
A small subset of the training set named the “objective” set, is used to measure information
|
| 17 |
+
gain on the pre-trained model, and consequently to train the secondary model. After
|
| 18 |
+
training, the model is used for filtering samples for the fine-tuning process. Therefore,
|
| 19 |
+
a high information gain value would suggest a sample is informative, whereas a low value
|
| 20 |
+
would suggest a non-informative sample that should be filtered out. Thus, a thresholding
|
| 21 |
+
strategy is defined to select informative samples. With such a strategy, samples are filtered
|
| 22 |
+
and once enough samples are selected to form a mini-batch and a usual fine-tuning/optimization
|
| 23 |
+
step is applied. The filtration process is repeated until the fine-tuning process is over.
|
| 24 |
+
|
| 25 |
+
Paper [Selecting Informative Contexts Improves Language Model Finetuning](https://arxiv.org/abs/2005.00175)
|
| 26 |
+
|
| 27 |
+
# Results
|
| 28 |
+
|
| 29 |
+
Several experiments were conducted to show the robustness of the IGF method versus the
|
| 30 |
+
standard fine-tuning process. For example, we achieve a median perplexity of 54.0 on the
|
| 31 |
+
Books dataset compared to 57.3 for standard fine-tuning on GPT-2 Small. The code was
|
| 32 |
+
implemented using the Transformers library and Pytorch. While the method may seem more
|
| 33 |
+
expensive, we saw enough evidence that it may lead to a performance benefit in the final models.
|
| 34 |
+
|
| 35 |
+

|
| 36 |
+
|
| 37 |
+
Figure 1: Comparing IGF to Standard Fine-tuning:
|
| 38 |
+
IGF with constant (p < 10−3 , t-test) and shifting(p < 10−6 , t-test) thresholding significantly outperform standard fine-tuning. The left-hand figure shows
|
| 39 |
+
test-set perplexity after each fine-tuning batch, averaged over 50 runs (error bars denote ± one standard error). The right-hand figure shows the perplexity of each
|
| 40 |
+
method after 60 batches. IGF with shifting thresholding (red) clearly improves over standard batched fine-tuning with Adam
|
| 41 |
+
|
| 42 |
+
## How to use this project?
|
| 43 |
+
|
| 44 |
+
To fine-tune a transformer model with IGF on a language modeling task, use the following script:
|
| 45 |
+
|
| 46 |
+
- `model_name_or_path`: Path to pretrained model or model identifier from huggingface.co/models
|
| 47 |
+
- `data_file`: A jbl file containing tokenized data which can be split as objective dataset,
|
| 48 |
+
train_dataset and test_dataset
|
| 49 |
+
- `igf_data_file`: A jbl file containing the context and information gain pairs to train secondary learner.
|
| 50 |
+
- `context_len`: The maximum total input sequence length after tokenization. Sequences longer
|
| 51 |
+
than this will be truncated, sequences shorter will be padded.
|
| 52 |
+
- `size_objective_set`: Number of articles that are long enough to be used as our objective set"
|
| 53 |
+
- `min_len`: The minimum length of the article to be used as objective set
|
| 54 |
+
- `trim`: Truncate the example if it exceeds context length
|
| 55 |
+
- `eval_freq`: Secondary model evaluation can be triggered at eval_freq
|
| 56 |
+
- `max_steps`: To calculate training epochs
|
| 57 |
+
- `number`: The number of examples split to be used as objective_set/test_data
|
| 58 |
+
- `secondary_learner_batch_size`: The batch size of training data for secondary learner
|
| 59 |
+
- `secondary_learner_max_epochs`: The number of epochs to train secondary learner
|
| 60 |
+
- `recopy_model`: Reset the model to the original pretrained GPT-2 weights after each iteration
|
| 61 |
+
- `eval_interval`: Decay the selectivity of our secondary learner filter from"
|
| 62 |
+
1 standard deviation above average to 1 below average after eval_interval(10) batches"
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
```python
|
| 66 |
+
python run_clm_igf.py\
|
| 67 |
+
--model_name_or_path "openai-community/gpt2" \
|
| 68 |
+
--data_file="data/tokenized_stories_train_wikitext103" \
|
| 69 |
+
--igf_data_file="data/IGF_values" \
|
| 70 |
+
--context_len 32 \
|
| 71 |
+
--size_objective_set 100 \
|
| 72 |
+
--min_len 1026 \
|
| 73 |
+
--trim True \
|
| 74 |
+
--eval_freq 100 \
|
| 75 |
+
--max_steps 1000 \
|
| 76 |
+
--secondary_learner_batch_size 128 \
|
| 77 |
+
--secondary_learner_max_epochs 15 \
|
| 78 |
+
--number 100 \
|
| 79 |
+
--recopy_model \
|
| 80 |
+
--eval_interval 10 \
|
| 81 |
+
```
|
| 82 |
+
|
| 83 |
+
## Citation
|
| 84 |
+
|
| 85 |
+
If you find the resource useful, please cite the following paper
|
| 86 |
+
|
| 87 |
+
```bibtex
|
| 88 |
+
@inproceedings{antonello-etal-2021-selecting,
|
| 89 |
+
title = "Selecting Informative Contexts Improves Language Model Fine-tuning",
|
| 90 |
+
author = "Antonello, Richard and Beckage, Nicole and Turek, Javier and Huth, Alexander",
|
| 91 |
+
booktitle = "Proceedings of the 59th Annual Meeting of the Association for Computational Linguistics and the 11th International Joint Conference on Natural Language Processing (Volume 1: Long Papers)",
|
| 92 |
+
month = aug,
|
| 93 |
+
year = "2021",
|
| 94 |
+
address = "Online",
|
| 95 |
+
publisher = "Association for Computational Linguistics",
|
| 96 |
+
url = "https://aclanthology.org/2021.acl-long.87",
|
| 97 |
+
doi = "10.18653/v1/2021.acl-long.87",
|
| 98 |
+
pages = "1072--1085",
|
| 99 |
+
}
|
| 100 |
+
```
|
tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/information-gain-filtration/igf/__init__.py
ADDED
|
File without changes
|
tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/information-gain-filtration/igf/igf.py
ADDED
|
@@ -0,0 +1,416 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2022 - Intel Corp. All rights reserved.
|
| 2 |
+
# Authors: Mayank Kumar Raunak, Javier Turek, Nicole Backage
|
| 3 |
+
|
| 4 |
+
import copy
|
| 5 |
+
import logging
|
| 6 |
+
import random
|
| 7 |
+
|
| 8 |
+
import joblib
|
| 9 |
+
import numpy as np
|
| 10 |
+
import torch
|
| 11 |
+
import torch.nn as nn
|
| 12 |
+
from torch.utils.data import DataLoader
|
| 13 |
+
from tqdm import tqdm
|
| 14 |
+
|
| 15 |
+
from transformers import AdamW, GPT2LMHeadModel, get_linear_schedule_with_warmup
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
logger = logging.getLogger(__name__)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def set_seed(seed):
|
| 22 |
+
"""
|
| 23 |
+
For reproducible training
|
| 24 |
+
|
| 25 |
+
Args:
|
| 26 |
+
seed: A seed for reproducible training
|
| 27 |
+
|
| 28 |
+
"""
|
| 29 |
+
random.seed(seed)
|
| 30 |
+
np.random.seed(seed)
|
| 31 |
+
torch.manual_seed(seed)
|
| 32 |
+
torch.cuda.manual_seed_all(seed)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def compute_perplexity(model, test_data, context_len):
|
| 36 |
+
"""
|
| 37 |
+
Computes perplexity of the transformer model on data in test_data
|
| 38 |
+
|
| 39 |
+
Args:
|
| 40 |
+
model: Pre-trained GPT2 model
|
| 41 |
+
test_data: Data on which perplexity calculation is required
|
| 42 |
+
context_len: The maximum total input sequence length after tokenization. Sequences longer
|
| 43 |
+
than this will be truncated, sequences shorter will be padded
|
| 44 |
+
|
| 45 |
+
Returns:
|
| 46 |
+
Perplexity on input test data
|
| 47 |
+
|
| 48 |
+
"""
|
| 49 |
+
|
| 50 |
+
model.eval()
|
| 51 |
+
device = next(model.parameters()).device
|
| 52 |
+
eval_batch_size = 1
|
| 53 |
+
context = torch.zeros((eval_batch_size, context_len), dtype=torch.long, device=device)
|
| 54 |
+
eval_dataloader = DataLoader(test_data, shuffle=False, batch_size=eval_batch_size)
|
| 55 |
+
eval_loss = torch.zeros(1, device=device)
|
| 56 |
+
nb_eval_examples = 0
|
| 57 |
+
for batch in eval_dataloader:
|
| 58 |
+
batch.to(device)
|
| 59 |
+
# pad
|
| 60 |
+
context.zero_()
|
| 61 |
+
for i in range(eval_batch_size):
|
| 62 |
+
context[i, :] = batch[i]
|
| 63 |
+
outputs = model(context, labels=context)
|
| 64 |
+
eval_loss += outputs[0].sum().item()
|
| 65 |
+
nb_eval_examples += batch.size(0)
|
| 66 |
+
eval_loss = eval_loss / nb_eval_examples
|
| 67 |
+
perplexity = torch.exp(eval_loss)
|
| 68 |
+
model.train()
|
| 69 |
+
return perplexity
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def load_gpt2(model_name="openai-community/gpt2"):
|
| 73 |
+
"""
|
| 74 |
+
load original openai-community/gpt2 and save off for quicker loading
|
| 75 |
+
|
| 76 |
+
Args:
|
| 77 |
+
model_name: GPT-2
|
| 78 |
+
|
| 79 |
+
Returns:
|
| 80 |
+
GPT-2 model
|
| 81 |
+
|
| 82 |
+
"""
|
| 83 |
+
|
| 84 |
+
model = GPT2LMHeadModel.from_pretrained(model_name, output_hidden_states=True)
|
| 85 |
+
torch.save(model.state_dict(), model_name + "local.pt")
|
| 86 |
+
return model
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def recopy_gpt2(orig_model, device, max_steps):
|
| 90 |
+
"""
|
| 91 |
+
Reset the model to the original pretrained GPT-2 weights after each iteration
|
| 92 |
+
|
| 93 |
+
Args:
|
| 94 |
+
orig_model: Original pretrained GPT-2 model imported from Transformers library
|
| 95 |
+
device: CPU/GPU
|
| 96 |
+
max_steps: number of training steps
|
| 97 |
+
|
| 98 |
+
Returns:
|
| 99 |
+
Original PreTrained GPT-2 model,
|
| 100 |
+
lm_optimizer: Adam optimizer with Decoupled weight decay
|
| 101 |
+
lm_scheduler: linear scheduler with the appropriate schedule
|
| 102 |
+
|
| 103 |
+
"""
|
| 104 |
+
model = copy.deepcopy(orig_model)
|
| 105 |
+
model.to(device)
|
| 106 |
+
|
| 107 |
+
no_decay = ["bias", "LayerNorm.weight"]
|
| 108 |
+
optimizer_grouped_parameters = [
|
| 109 |
+
{
|
| 110 |
+
"params": [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay)],
|
| 111 |
+
"weight_decay": 0.0,
|
| 112 |
+
},
|
| 113 |
+
{"params": [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay)], "weight_decay": 0.0},
|
| 114 |
+
]
|
| 115 |
+
lm_optimizer = AdamW(optimizer_grouped_parameters, lr=5e-5, eps=1e-8)
|
| 116 |
+
lm_scheduler = get_linear_schedule_with_warmup(lm_optimizer, 0, max_steps)
|
| 117 |
+
torch.cuda.empty_cache()
|
| 118 |
+
return model, lm_optimizer, lm_scheduler
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def intermittent_save(contexts, real_perps, past_perps, filename):
|
| 122 |
+
"""
|
| 123 |
+
save the perplexity differences to filename
|
| 124 |
+
|
| 125 |
+
Args:
|
| 126 |
+
contexts: Example on which the perplexity is calculated
|
| 127 |
+
real_perps: Perplexity after back-propagating on the selected context
|
| 128 |
+
past_perps: Perplexity of model before training on the context
|
| 129 |
+
filename: File to store perplexity differences
|
| 130 |
+
|
| 131 |
+
Returns:
|
| 132 |
+
file with perplexity differences
|
| 133 |
+
|
| 134 |
+
"""
|
| 135 |
+
# save the perplexity differences to filename
|
| 136 |
+
avg = np.array(real_perps).mean()
|
| 137 |
+
std = np.array(real_perps).std()
|
| 138 |
+
perp_diff = (real_perps - avg) / std
|
| 139 |
+
data_final = list(zip(contexts, perp_diff, past_perps))
|
| 140 |
+
joblib.dump(data_final, filename)
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def collect_objective_set(
|
| 144 |
+
model,
|
| 145 |
+
orig_perp,
|
| 146 |
+
context_len,
|
| 147 |
+
train_data,
|
| 148 |
+
objective_set,
|
| 149 |
+
max_steps,
|
| 150 |
+
device,
|
| 151 |
+
filename="dev.jbl",
|
| 152 |
+
recopy_model=recopy_gpt2,
|
| 153 |
+
):
|
| 154 |
+
"""
|
| 155 |
+
Collect individual IGF values from pre-trained transformer model
|
| 156 |
+
max_steps samples of training data to train secondary model
|
| 157 |
+
|
| 158 |
+
Args:
|
| 159 |
+
model: Pre-trained GPT2 model
|
| 160 |
+
orig_perp: Perplexity of original pretrained GPT-2 model
|
| 161 |
+
context_len: The maximum total input sequence length after tokenization. Sequences longer
|
| 162 |
+
than this will be truncated, sequences shorter will be padded
|
| 163 |
+
train_data: Data to train model
|
| 164 |
+
objective_set: Contexts used to create (X,IG(X)) pairs which is the training data for secondary learner
|
| 165 |
+
max_steps: To calculate training epochs of model
|
| 166 |
+
device: GPU/CPU
|
| 167 |
+
filename: To store intermediate perplexity differences
|
| 168 |
+
recopy_model: Reset the model to the original pretrained GPT-2 weights after each iteration
|
| 169 |
+
|
| 170 |
+
Returns:
|
| 171 |
+
file stored intermediate perplexity differences in intermediate stages
|
| 172 |
+
|
| 173 |
+
"""
|
| 174 |
+
|
| 175 |
+
# initialize variables to record relevant information
|
| 176 |
+
contexts = []
|
| 177 |
+
real_perps = []
|
| 178 |
+
past_perps = []
|
| 179 |
+
|
| 180 |
+
# Initialize the transformer model
|
| 181 |
+
orig_model = copy.deepcopy(model)
|
| 182 |
+
orig_model.to(device="cpu")
|
| 183 |
+
torch.cuda.empty_cache()
|
| 184 |
+
|
| 185 |
+
# Compute perplexity of initial transformer model for comparison
|
| 186 |
+
model.train()
|
| 187 |
+
model, lm_optimizer, lm_scheduler = recopy_model(orig_model, device, max_steps)
|
| 188 |
+
|
| 189 |
+
for step in tqdm(range(max_steps)):
|
| 190 |
+
context = torch.zeros((1, context_len), dtype=torch.long, device=device)
|
| 191 |
+
story = random.choice(train_data)
|
| 192 |
+
start = random.randint(0, len(story[0]) - context_len - 1)
|
| 193 |
+
context[0, :] = story[0][start : start + context_len]
|
| 194 |
+
lm_optimizer.zero_grad()
|
| 195 |
+
outputs = model(context, labels=context)
|
| 196 |
+
lm_loss = outputs[0]
|
| 197 |
+
past_perp = compute_perplexity(model, context, context_len)
|
| 198 |
+
model.train()
|
| 199 |
+
lm_loss.backward()
|
| 200 |
+
# Do LM backprop
|
| 201 |
+
torch.nn.utils.clip_grad_norm_(model.parameters(), 3.0)
|
| 202 |
+
lm_optimizer.step()
|
| 203 |
+
lm_scheduler.step() # Update learning rate schedule
|
| 204 |
+
|
| 205 |
+
# Compute perplexity after back-propagating on the selected context
|
| 206 |
+
real_perp = compute_perplexity(model, objective_set, context_len)
|
| 207 |
+
|
| 208 |
+
# Periodically save the stored (X, IG(X)) pairs
|
| 209 |
+
if step % 1000 == 0 and step > 1:
|
| 210 |
+
intermittent_save(contexts, real_perps, past_perps, filename)
|
| 211 |
+
|
| 212 |
+
# Reset the pretrained model to the original pretrained GPT-2 weights after each iteration
|
| 213 |
+
model, lm_optimizer, lm_scheduler = recopy_model(orig_model, device, max_steps)
|
| 214 |
+
|
| 215 |
+
past_perps.append(past_perp.item())
|
| 216 |
+
real_perps.append(orig_perp - real_perp.item())
|
| 217 |
+
contexts.append(np.array(context.cpu()))
|
| 218 |
+
|
| 219 |
+
intermittent_save(contexts, real_perps, past_perps, filename)
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
def generate_datasets(
|
| 223 |
+
context_len, file="data/tokenized_stories_train_wikitext103.jbl", number=100, min_len=1026, trim=True
|
| 224 |
+
):
|
| 225 |
+
"""
|
| 226 |
+
Generate objective set and training set
|
| 227 |
+
|
| 228 |
+
Args:
|
| 229 |
+
context_len: The maximum total input sequence length after tokenization. Sequences longer
|
| 230 |
+
than this will be truncated, sequences shorter will be padded
|
| 231 |
+
file: Tokenized data split into training set and objective set
|
| 232 |
+
number: size of objective dataset
|
| 233 |
+
min_len: minimum length of a context in objective set
|
| 234 |
+
trim: If True truncate the context if it exceeds context length
|
| 235 |
+
|
| 236 |
+
Returns:
|
| 237 |
+
Generated objective set and training data
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
"""
|
| 241 |
+
# Generate objective set and training set
|
| 242 |
+
# Designate the first number (100) articles that are long enough to be used
|
| 243 |
+
# as our objective set, rest (that are long enough) are training data for
|
| 244 |
+
# secondary learner
|
| 245 |
+
|
| 246 |
+
data = joblib.load(file)
|
| 247 |
+
print("data loaded")
|
| 248 |
+
objective_set = []
|
| 249 |
+
if trim:
|
| 250 |
+
for i, example in enumerate(data):
|
| 251 |
+
if len(example[0]) > min_len:
|
| 252 |
+
start = random.randint(0, len(example[0]) - context_len - 1)
|
| 253 |
+
objective_set.append(example[0, start : start + context_len])
|
| 254 |
+
if len(objective_set) >= number:
|
| 255 |
+
break
|
| 256 |
+
train_data = []
|
| 257 |
+
for j in range(i + 1, len(data)):
|
| 258 |
+
if len(data[j][0]) > min_len:
|
| 259 |
+
train_data.append(data[j])
|
| 260 |
+
else:
|
| 261 |
+
objective_set = data[0:number]
|
| 262 |
+
train_data = data[number:]
|
| 263 |
+
|
| 264 |
+
joblib.dump(objective_set, "objective_set.jbl")
|
| 265 |
+
print("objective set saved")
|
| 266 |
+
return train_data, objective_set
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
def train_secondary_learner(
|
| 270 |
+
secondary_learner, train_dataset, max_epochs, batch_size, eval_freq=50, igf_model_path="secondary_learner.pt"
|
| 271 |
+
):
|
| 272 |
+
"""
|
| 273 |
+
Train the secondary learner (igf_model)
|
| 274 |
+
|
| 275 |
+
Args:
|
| 276 |
+
secondary_learner: secondary learner
|
| 277 |
+
train_dataset: data to train secondary learner
|
| 278 |
+
max_epochs: number of epochs to train secondary learner
|
| 279 |
+
batch_size: batch size of training data of secondary learner
|
| 280 |
+
eval_freq: secondary model evaluation can be triggered at eval_freq
|
| 281 |
+
igf_model_path: path to store trained secondary learner
|
| 282 |
+
|
| 283 |
+
Returns:
|
| 284 |
+
Trained secondary learner
|
| 285 |
+
|
| 286 |
+
"""
|
| 287 |
+
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
|
| 288 |
+
# We will use the first 512 pairs from our dataset as a test set for
|
| 289 |
+
# our secondary learner and the rest to train
|
| 290 |
+
test_dataset = train_dataset[:512]
|
| 291 |
+
train_dataset = train_dataset[512:]
|
| 292 |
+
train_dataloader = DataLoader(train_dataset, shuffle=True, batch_size=batch_size)
|
| 293 |
+
test_dataloader = DataLoader(test_dataset, shuffle=False, batch_size=batch_size)
|
| 294 |
+
|
| 295 |
+
# secondary learner model set up
|
| 296 |
+
loss = nn.MSELoss()
|
| 297 |
+
test_loss = nn.MSELoss(reduction="sum")
|
| 298 |
+
secondary_learner.to(device)
|
| 299 |
+
q_optimizer = torch.optim.Adam(secondary_learner.parameters(), lr=0.00001)
|
| 300 |
+
secondary_learner.train()
|
| 301 |
+
|
| 302 |
+
# TODO in original code this is written as number of actual batches seen
|
| 303 |
+
# not number of items seen but other places it is number of items instead.
|
| 304 |
+
# improve consistency! changed this to epochs for clarity
|
| 305 |
+
best_test_loss = float("inf")
|
| 306 |
+
# Iterate through batches until we've used max_steps batches
|
| 307 |
+
for epoch in range(int(max_epochs)):
|
| 308 |
+
tr_q_loss = 0.0
|
| 309 |
+
secondary_learner.train()
|
| 310 |
+
for step, batch in enumerate(train_dataloader):
|
| 311 |
+
context = batch[0].to(device)
|
| 312 |
+
real_q = batch[1].to(device)
|
| 313 |
+
predicted_q = secondary_learner(context)
|
| 314 |
+
q_optimizer.zero_grad()
|
| 315 |
+
q_loss = loss(predicted_q, real_q.float())
|
| 316 |
+
q_loss.backward()
|
| 317 |
+
q_optimizer.step()
|
| 318 |
+
tr_q_loss += q_loss.item()
|
| 319 |
+
|
| 320 |
+
# model trains fairly quickly so we won't wait for a full epoch
|
| 321 |
+
# eval is triggered at eval_freq and end of epochs
|
| 322 |
+
if (step % eval_freq == 0 and step > 0) or ((step + 1) == len(train_dataloader)):
|
| 323 |
+
tr_loss = tr_q_loss / (step + 1)
|
| 324 |
+
|
| 325 |
+
secondary_learner.eval()
|
| 326 |
+
q_loss2 = 0.0
|
| 327 |
+
sum_q2 = 0.0
|
| 328 |
+
predicted = []
|
| 329 |
+
actual = []
|
| 330 |
+
# Compute performance of the secondary learner after this batch
|
| 331 |
+
for step2, batch2 in enumerate(test_dataloader):
|
| 332 |
+
features2 = batch2[0].to(device)
|
| 333 |
+
real_q2 = batch2[1].to(device)
|
| 334 |
+
predicted_q2 = secondary_learner(features2)
|
| 335 |
+
q_loss2 += test_loss(predicted_q2, real_q2).item()
|
| 336 |
+
sum_q2 += torch.sum(predicted_q2).item()
|
| 337 |
+
for ei, i in enumerate(predicted_q2.cpu().detach().numpy()):
|
| 338 |
+
predicted.append(i.item())
|
| 339 |
+
for ei, i in enumerate(real_q2.cpu().detach().numpy()):
|
| 340 |
+
actual.append(i.item())
|
| 341 |
+
|
| 342 |
+
q_loss2 /= len(test_dataset)
|
| 343 |
+
print(
|
| 344 |
+
"Epoch: ",
|
| 345 |
+
epoch,
|
| 346 |
+
"step: ",
|
| 347 |
+
step,
|
| 348 |
+
"Avg. q:",
|
| 349 |
+
sum_q2 / len(test_dataset),
|
| 350 |
+
"Train Loss: ",
|
| 351 |
+
tr_loss,
|
| 352 |
+
"Test Loss: ",
|
| 353 |
+
q_loss2,
|
| 354 |
+
)
|
| 355 |
+
if q_loss2 < best_test_loss:
|
| 356 |
+
joblib.dump((predicted, actual), "pred_vs_actual.jbl")
|
| 357 |
+
torch.save(secondary_learner.state_dict(), igf_model_path)
|
| 358 |
+
best_test_loss = q_loss2
|
| 359 |
+
|
| 360 |
+
secondary_learner.train()
|
| 361 |
+
return secondary_learner
|
| 362 |
+
|
| 363 |
+
|
| 364 |
+
class SecondaryLearner(nn.Module):
|
| 365 |
+
"""
|
| 366 |
+
Our secondary learner
|
| 367 |
+
"""
|
| 368 |
+
|
| 369 |
+
def __init__(self, model):
|
| 370 |
+
"""
|
| 371 |
+
We use a simple convolutional network as our secondary learner
|
| 372 |
+
|
| 373 |
+
Args:
|
| 374 |
+
model: Pre-trained GPT2 model
|
| 375 |
+
"""
|
| 376 |
+
# embeddings are from the pretrained model
|
| 377 |
+
super(SecondaryLearner, self).__init__()
|
| 378 |
+
self.embeddings = model.transformer.wte
|
| 379 |
+
self.embeddings.weight = copy.deepcopy(model.transformer.wte.weight)
|
| 380 |
+
self.conv = nn.Conv1d(self.embeddings.weight.size(1), 256, 3, padding=1)
|
| 381 |
+
self.fc = nn.Sequential(nn.Linear(256, 32), nn.Dropout(p=0.1), nn.Linear(32, 32), nn.Linear(32, 1))
|
| 382 |
+
|
| 383 |
+
def forward(self, context):
|
| 384 |
+
"""
|
| 385 |
+
Forward pass through the secondary learner
|
| 386 |
+
|
| 387 |
+
Args:
|
| 388 |
+
context: Context input to the secondary learner
|
| 389 |
+
|
| 390 |
+
Returns:
|
| 391 |
+
tensor after squeeze operation
|
| 392 |
+
|
| 393 |
+
"""
|
| 394 |
+
pooled = torch.max(self.conv(self.embeddings(context).squeeze(1).transpose(1, 2)), 2)[0]
|
| 395 |
+
qs = self.fc(pooled)
|
| 396 |
+
return qs.squeeze(1)
|
| 397 |
+
|
| 398 |
+
@classmethod
|
| 399 |
+
def from_pretrained(cls, state_path, model):
|
| 400 |
+
"""
|
| 401 |
+
Load the secondary learner
|
| 402 |
+
|
| 403 |
+
Args:
|
| 404 |
+
state_path: Path to save secondary learner
|
| 405 |
+
model: Pretrained GPT-2
|
| 406 |
+
|
| 407 |
+
Returns:
|
| 408 |
+
secondary learner
|
| 409 |
+
"""
|
| 410 |
+
|
| 411 |
+
secondary_learner = cls(model) # this calls __init__
|
| 412 |
+
state_dict = torch.load(state_path)
|
| 413 |
+
secondary_learner.load_state_dict(state_dict)
|
| 414 |
+
secondary_learner.embeddings = model.transformer.wte
|
| 415 |
+
secondary_learner.embeddings.weight = copy.deepcopy(model.transformer.wte.weight)
|
| 416 |
+
return secondary_learner
|
tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/information-gain-filtration/requirements.txt
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
matplotlib
|
| 2 |
+
numpy>=1.17.2
|
| 3 |
+
joblib>=0.13.2
|
| 4 |
+
scipy
|
| 5 |
+
torch>=1.10.1
|
| 6 |
+
transformers>=3.5
|
tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/information-gain-filtration/result_igf.png
ADDED
|
Git LFS Details
|
tasks/tasksmith-e0f68dd4420c/tests/source/examples/research_projects/information-gain-filtration/run_clm_igf.py
ADDED
|
@@ -0,0 +1,450 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2022 - Intel Corp. All rights reserved.
|
| 2 |
+
# Authors: Mayank Kumar Raunak, Javier Turek, Nicole Beckage
|
| 3 |
+
|
| 4 |
+
"""
|
| 5 |
+
Implementation of a new method for fine-tuning transformer models that we call
|
| 6 |
+
Information Gain Filtration 'IGF' on WikiText data set and compared the results
|
| 7 |
+
with the standard fine-tuning method
|
| 8 |
+
|
| 9 |
+
Steps followed in the code:
|
| 10 |
+
|
| 11 |
+
1) Generate a objective dataset of pairs (X, IG(X)). IG(X)--Informativeness of context 'X'.
|
| 12 |
+
Our IG (information gain) model is learning to predict the ‘informativeness’ of a particular
|
| 13 |
+
context. Informativeness is the change in metric between the model’s accuracy on an
|
| 14 |
+
objective set before and after seeing that context. For casual language modeling, the
|
| 15 |
+
metric is perplexity.
|
| 16 |
+
|
| 17 |
+
2) A secondary learner is trained to infer a function approximation for IG using the dataset
|
| 18 |
+
created in (1).
|
| 19 |
+
|
| 20 |
+
3) The learner created in (2) is used to inform the fine-tuning process and filter out low informative samples.
|
| 21 |
+
|
| 22 |
+
Last, a plot is generated to compare the performance of IGF to standard fine-tuning without any filtering
|
| 23 |
+
|
| 24 |
+
"""
|
| 25 |
+
|
| 26 |
+
# Prerequisite libraries:
|
| 27 |
+
|
| 28 |
+
import argparse
|
| 29 |
+
import random
|
| 30 |
+
|
| 31 |
+
import joblib
|
| 32 |
+
import numpy as np
|
| 33 |
+
import torch
|
| 34 |
+
from igf.igf import (
|
| 35 |
+
SecondaryLearner,
|
| 36 |
+
collect_objective_set,
|
| 37 |
+
compute_perplexity,
|
| 38 |
+
generate_datasets,
|
| 39 |
+
load_gpt2,
|
| 40 |
+
recopy_gpt2,
|
| 41 |
+
set_seed,
|
| 42 |
+
train_secondary_learner,
|
| 43 |
+
)
|
| 44 |
+
from torch.utils.data import DataLoader, RandomSampler
|
| 45 |
+
|
| 46 |
+
from transformers import GPT2LMHeadModel
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def generate_n_pairs(
|
| 50 |
+
context_len=32,
|
| 51 |
+
max_steps=10,
|
| 52 |
+
size_objective_set=100,
|
| 53 |
+
min_len=1026,
|
| 54 |
+
trim=True,
|
| 55 |
+
data_file="data/tokenized_stories_train_wikitext103.jbl",
|
| 56 |
+
igf_data_file="igf_context_pairs.jbl",
|
| 57 |
+
):
|
| 58 |
+
"""
|
| 59 |
+
Collecting *n* pairs for training the secondary learner
|
| 60 |
+
Args:
|
| 61 |
+
context_len: The maximum total input sequence length after tokenization. Sequences longer
|
| 62 |
+
than this will be truncated, sequences shorter will be padded
|
| 63 |
+
max_steps: To calculate training epochs of secondary learner
|
| 64 |
+
size_objective_set: size of objective data set used to create (X,IG(X)) pairs which is the training data for secondary learner
|
| 65 |
+
min_len: The minimum length of the article to be used as objective set
|
| 66 |
+
trim: If True truncate the context if it exceeds context length
|
| 67 |
+
data_file: Tokenized data set split for training and evaluation of model
|
| 68 |
+
igf_data_file: file to store (I,IG(X)) paired data set to train secondary learner
|
| 69 |
+
|
| 70 |
+
Returns:
|
| 71 |
+
Data stored in igf_data_file
|
| 72 |
+
|
| 73 |
+
"""
|
| 74 |
+
# generates same data everytime
|
| 75 |
+
set_seed(3)
|
| 76 |
+
# generate train_data and objective_set
|
| 77 |
+
train_data, objective_set = generate_datasets(
|
| 78 |
+
context_len, data_file, number=size_objective_set, min_len=1026, trim=True
|
| 79 |
+
)
|
| 80 |
+
# keeps model same across runs
|
| 81 |
+
set_seed(4)
|
| 82 |
+
# model, lm_optimizer, lm_scheduler = recopy_gpt2(model, device, max_steps) # store original model weights
|
| 83 |
+
# can we train on GPU?
|
| 84 |
+
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
|
| 85 |
+
|
| 86 |
+
# load pretrained model
|
| 87 |
+
model = load_gpt2("openai-community/gpt2").to(device)
|
| 88 |
+
print("computing perplexity on objective set")
|
| 89 |
+
orig_perp = compute_perplexity(model, objective_set, context_len).item()
|
| 90 |
+
print("perplexity on objective set:", orig_perp)
|
| 91 |
+
|
| 92 |
+
# collect igf pairs and save to file demo.jbl
|
| 93 |
+
collect_objective_set(model, orig_perp, context_len, train_data, objective_set, max_steps, device, igf_data_file)
|
| 94 |
+
|
| 95 |
+
# clean up, delete model and data we don't need anymore
|
| 96 |
+
del model, train_data, objective_set
|
| 97 |
+
torch.cuda.empty_cache()
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def training_secondary_learner(
|
| 101 |
+
secondary_learner_train_data,
|
| 102 |
+
secondary_learner_max_epochs=15,
|
| 103 |
+
secondary_learner_batch_size=128,
|
| 104 |
+
eval_freq=100,
|
| 105 |
+
igf_model_path="igf_model.pt",
|
| 106 |
+
):
|
| 107 |
+
"""
|
| 108 |
+
Train the secondary learner
|
| 109 |
+
|
| 110 |
+
Args:
|
| 111 |
+
secondary_learner_train_data: Data set with (X,IG(X)) pairs to train secondary learner where IG(X) - measure of informativeness and X- context
|
| 112 |
+
secondary_learner_max_epochs: Number of epochs to train secondary learner
|
| 113 |
+
secondary_learner_batch_size: Batch size to train secondary learner
|
| 114 |
+
eval_freq (object): secondary model evaluation can be triggered at eval_freq
|
| 115 |
+
igf_model_path: path to store trained secondary learner
|
| 116 |
+
|
| 117 |
+
Returns:
|
| 118 |
+
Trained secondary learner
|
| 119 |
+
"""
|
| 120 |
+
|
| 121 |
+
set_seed(42)
|
| 122 |
+
|
| 123 |
+
# Load pre-trained model
|
| 124 |
+
model = GPT2LMHeadModel.from_pretrained("openai-community/gpt2")
|
| 125 |
+
|
| 126 |
+
# Initialize secondary learner to use embedding weights of model
|
| 127 |
+
secondary_learner = SecondaryLearner(model)
|
| 128 |
+
|
| 129 |
+
# Train secondary learner
|
| 130 |
+
secondary_learner = train_secondary_learner(
|
| 131 |
+
secondary_learner,
|
| 132 |
+
secondary_learner_train_data,
|
| 133 |
+
max_epochs=secondary_learner_max_epochs,
|
| 134 |
+
batch_size=secondary_learner_batch_size,
|
| 135 |
+
eval_freq=100,
|
| 136 |
+
igf_model_path=igf_model_path,
|
| 137 |
+
)
|
| 138 |
+
|
| 139 |
+
del model, secondary_learner_train_data
|
| 140 |
+
torch.cuda.empty_cache()
|
| 141 |
+
|
| 142 |
+
return secondary_learner
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def finetune(
|
| 146 |
+
model,
|
| 147 |
+
train_dataset,
|
| 148 |
+
test_dataset,
|
| 149 |
+
context_len=32,
|
| 150 |
+
max_steps=1000,
|
| 151 |
+
batch_size=16,
|
| 152 |
+
threshold=1.0,
|
| 153 |
+
recopy_model=recopy_gpt2,
|
| 154 |
+
secondary_learner=None,
|
| 155 |
+
eval_interval=10,
|
| 156 |
+
finetuned_model_name="openai-community/gpt2_finetuned.pt",
|
| 157 |
+
):
|
| 158 |
+
"""
|
| 159 |
+
fine-tune with IGF if secondary_learner is not None, else standard fine-tuning
|
| 160 |
+
|
| 161 |
+
Args:
|
| 162 |
+
model: pre-trained GPT-2 model
|
| 163 |
+
train_dataset: Data set to train GPT-2 model
|
| 164 |
+
test_dataset: Evaluate GPT-2 model
|
| 165 |
+
context_len: The maximum total input sequence length after tokenization. Sequences longer
|
| 166 |
+
than this will be truncated, sequences shorter will be padded
|
| 167 |
+
max_steps: To calculate training epochs
|
| 168 |
+
batch_size: Batch size to train GPT-2 model
|
| 169 |
+
threshold: The threshold value used by secondary learner to filter the train_data and allow only"
|
| 170 |
+
informative data as input to the model
|
| 171 |
+
recopy_model: Reset the model to the original pretrained GPT-2 weights after each iteration
|
| 172 |
+
secondary_learner: Selection of IGF as fine-tuning method if not None
|
| 173 |
+
eval_interval: number of batches after which decay the selectivity of our secondary learner filter from
|
| 174 |
+
1 standard deviation above average to 1 below average
|
| 175 |
+
fine-tuned_model_name: name of the final final-tuned GPT-2 model
|
| 176 |
+
|
| 177 |
+
Returns:
|
| 178 |
+
Fine-tuned GPT-2 model
|
| 179 |
+
|
| 180 |
+
"""
|
| 181 |
+
|
| 182 |
+
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
|
| 183 |
+
train_sampler = RandomSampler(train_dataset)
|
| 184 |
+
train_dataloader = DataLoader(train_dataset, sampler=train_sampler)
|
| 185 |
+
|
| 186 |
+
num_train_epochs = max_steps // (len(train_dataset)) + 1
|
| 187 |
+
global_step = 0
|
| 188 |
+
context = torch.zeros((1, context_len), dtype=torch.long, device=device)
|
| 189 |
+
model, lm_optimizer, lm_scheduler = recopy_model(model, device, max_steps)
|
| 190 |
+
|
| 191 |
+
model.train()
|
| 192 |
+
if secondary_learner is not None:
|
| 193 |
+
secondary_learner.to(device)
|
| 194 |
+
secondary_learner.eval()
|
| 195 |
+
contexts = []
|
| 196 |
+
examples = 0
|
| 197 |
+
|
| 198 |
+
observed_qs = []
|
| 199 |
+
test_perps = []
|
| 200 |
+
|
| 201 |
+
# Compute the performance of the transformer model at the beginning
|
| 202 |
+
real_perp = compute_perplexity(model, test_dataset, context_len)
|
| 203 |
+
test_perps.append(real_perp)
|
| 204 |
+
print("Test perplexity, step", global_step, ":", real_perp)
|
| 205 |
+
for epoch in range(int(num_train_epochs)):
|
| 206 |
+
for step, example in enumerate(train_dataloader):
|
| 207 |
+
torch.cuda.empty_cache()
|
| 208 |
+
start = random.randint(0, example.size(2) - context_len - 1)
|
| 209 |
+
context[0, :] = example[0, 0, start : start + context_len]
|
| 210 |
+
lm_optimizer.zero_grad()
|
| 211 |
+
outputs = model(context, labels=context)
|
| 212 |
+
do_backprop = True
|
| 213 |
+
|
| 214 |
+
if secondary_learner is not None:
|
| 215 |
+
predicted_q = secondary_learner.forward(
|
| 216 |
+
torch.tensor(context, dtype=torch.long, device=device).unsqueeze(0)
|
| 217 |
+
)[0].item()
|
| 218 |
+
observed_qs.append(float(predicted_q))
|
| 219 |
+
|
| 220 |
+
# Here we implement the simple non-constant threshold for the predicted IG(X) value
|
| 221 |
+
# We will decay the selectivity of our secondary learner filter from
|
| 222 |
+
# 1 standard deviation above average to 1 below average after 10 batches.
|
| 223 |
+
|
| 224 |
+
if global_step == 10:
|
| 225 |
+
threshold = -1
|
| 226 |
+
if predicted_q < threshold:
|
| 227 |
+
do_backprop = False
|
| 228 |
+
|
| 229 |
+
# If we passed the filter, add the context to the batch!
|
| 230 |
+
if do_backprop:
|
| 231 |
+
contexts.append(np.array(context.cpu()))
|
| 232 |
+
lm_loss = outputs[0]
|
| 233 |
+
lm_loss.backward()
|
| 234 |
+
examples += 1
|
| 235 |
+
|
| 236 |
+
del outputs
|
| 237 |
+
|
| 238 |
+
# Once the batch is filled with enough contexts, backprop on the batch.
|
| 239 |
+
if examples == batch_size:
|
| 240 |
+
torch.cuda.empty_cache()
|
| 241 |
+
examples = 0
|
| 242 |
+
# Do LM backprop
|
| 243 |
+
torch.nn.utils.clip_grad_norm_(model.parameters(), 3.0)
|
| 244 |
+
lm_optimizer.step()
|
| 245 |
+
lm_scheduler.step() # Update learning rate schedule
|
| 246 |
+
global_step += 1
|
| 247 |
+
# Compute the performance of the transformer model at this batch
|
| 248 |
+
if global_step % eval_interval == 0:
|
| 249 |
+
real_perp = compute_perplexity(model, test_dataset, context_len)
|
| 250 |
+
test_perps.append(real_perp)
|
| 251 |
+
|
| 252 |
+
print("Test perplexity, step", global_step, ":", real_perp)
|
| 253 |
+
# Break out of the loop after 60 batches
|
| 254 |
+
if max_steps > 0 and global_step > 60:
|
| 255 |
+
break
|
| 256 |
+
if max_steps > 0 and global_step > 60:
|
| 257 |
+
break
|
| 258 |
+
|
| 259 |
+
# save finetuned transformer model
|
| 260 |
+
torch.save(model.state_dict(), finetuned_model_name)
|
| 261 |
+
torch.cuda.empty_cache()
|
| 262 |
+
# Do some cleaning up so we can reinitialize for the next run of this function
|
| 263 |
+
del lm_optimizer
|
| 264 |
+
del lm_scheduler
|
| 265 |
+
return model
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
def main():
|
| 269 |
+
parser = argparse.ArgumentParser(description="Fine-tune a transformer model with IGF on a language modeling task")
|
| 270 |
+
|
| 271 |
+
# Required parameters
|
| 272 |
+
parser.add_argument(
|
| 273 |
+
"--data_dir",
|
| 274 |
+
default=None,
|
| 275 |
+
type=str,
|
| 276 |
+
required=True,
|
| 277 |
+
help="The input data dir. Should contain data files for WikiText.",
|
| 278 |
+
)
|
| 279 |
+
parser.add_argument(
|
| 280 |
+
"--model_name_or_path",
|
| 281 |
+
default=None,
|
| 282 |
+
type=str,
|
| 283 |
+
required=True,
|
| 284 |
+
help="Path to pretrained model or model identifier from huggingface.co/models",
|
| 285 |
+
)
|
| 286 |
+
parser.add_argument(
|
| 287 |
+
"--data_file",
|
| 288 |
+
type=str,
|
| 289 |
+
default=None,
|
| 290 |
+
help=(
|
| 291 |
+
"A jbl file containing tokenized data which can be split as objective dataset, "
|
| 292 |
+
"train_dataset and test_dataset."
|
| 293 |
+
),
|
| 294 |
+
)
|
| 295 |
+
|
| 296 |
+
parser.add_argument(
|
| 297 |
+
"--igf_data_file",
|
| 298 |
+
type=str,
|
| 299 |
+
default=None,
|
| 300 |
+
help="A jbl file containing the context and information gain pairs to train secondary learner.",
|
| 301 |
+
)
|
| 302 |
+
|
| 303 |
+
parser.add_argument(
|
| 304 |
+
"--output_dir",
|
| 305 |
+
default=None,
|
| 306 |
+
type=str,
|
| 307 |
+
required=True,
|
| 308 |
+
help="The output directory where the final fine-tuned model is stored.",
|
| 309 |
+
)
|
| 310 |
+
|
| 311 |
+
parser.add_argument(
|
| 312 |
+
"--tokenizer_name",
|
| 313 |
+
default=None,
|
| 314 |
+
type=str,
|
| 315 |
+
help="Pretrained tokenizer name or path if not the same as model_name",
|
| 316 |
+
)
|
| 317 |
+
parser.add_argument("--seed", type=int, default=None, help="A seed for reproducible training.")
|
| 318 |
+
|
| 319 |
+
parser.add_argument(
|
| 320 |
+
"--context_len",
|
| 321 |
+
default=32,
|
| 322 |
+
type=int,
|
| 323 |
+
help=(
|
| 324 |
+
"The maximum total input sequence length after tokenization. Sequences longer "
|
| 325 |
+
"than this will be truncated, sequences shorter will be padded."
|
| 326 |
+
),
|
| 327 |
+
)
|
| 328 |
+
|
| 329 |
+
parser.add_argument(
|
| 330 |
+
"--size_objective_set",
|
| 331 |
+
default=100,
|
| 332 |
+
type=int,
|
| 333 |
+
help="number of articles that are long enough to be used as our objective set",
|
| 334 |
+
)
|
| 335 |
+
parser.add_argument(
|
| 336 |
+
"--eval_freq", default=100, type=int, help="secondary model evaluation is triggered at eval_freq"
|
| 337 |
+
)
|
| 338 |
+
|
| 339 |
+
parser.add_argument("--max_steps", default=1000, type=int, help="To calculate training epochs")
|
| 340 |
+
|
| 341 |
+
parser.add_argument(
|
| 342 |
+
"--secondary_learner_batch_size",
|
| 343 |
+
default=128,
|
| 344 |
+
type=int,
|
| 345 |
+
help="batch size of training data for secondary learner",
|
| 346 |
+
)
|
| 347 |
+
|
| 348 |
+
parser.add_argument(
|
| 349 |
+
"--batch_size",
|
| 350 |
+
default=16,
|
| 351 |
+
type=int,
|
| 352 |
+
help="batch size of training data of language model(openai-community/gpt2) ",
|
| 353 |
+
)
|
| 354 |
+
|
| 355 |
+
parser.add_argument(
|
| 356 |
+
"--eval_interval",
|
| 357 |
+
default=10,
|
| 358 |
+
type=int,
|
| 359 |
+
help=(
|
| 360 |
+
"decay the selectivity of our secondary learner filter from "
|
| 361 |
+
"1 standard deviation above average to 1 below average after 10 batches"
|
| 362 |
+
),
|
| 363 |
+
)
|
| 364 |
+
|
| 365 |
+
parser.add_argument(
|
| 366 |
+
"--number", default=100, type=int, help="The number of examples split to be used as objective_set/test_data"
|
| 367 |
+
)
|
| 368 |
+
|
| 369 |
+
parser.add_argument(
|
| 370 |
+
"--min_len", default=1026, type=int, help="The minimum length of the article to be used as objective set"
|
| 371 |
+
)
|
| 372 |
+
|
| 373 |
+
parser.add_argument(
|
| 374 |
+
"--secondary_learner_max_epochs", default=15, type=int, help="number of epochs to train secondary learner"
|
| 375 |
+
)
|
| 376 |
+
|
| 377 |
+
parser.add_argument("--trim", default=True, type=bool, help="truncate the example if it exceeds context length")
|
| 378 |
+
|
| 379 |
+
parser.add_argument(
|
| 380 |
+
"--threshold",
|
| 381 |
+
default=1.0,
|
| 382 |
+
type=float,
|
| 383 |
+
help=(
|
| 384 |
+
"The threshold value used by secondary learner to filter the train_data and allow only"
|
| 385 |
+
" informative data as input to the model"
|
| 386 |
+
),
|
| 387 |
+
)
|
| 388 |
+
|
| 389 |
+
parser.add_argument(
|
| 390 |
+
"--finetuned_model_name", default="openai-community/gpt2_finetuned.pt", type=str, help="finetuned_model_name"
|
| 391 |
+
)
|
| 392 |
+
|
| 393 |
+
parser.add_argument(
|
| 394 |
+
"--recopy_model",
|
| 395 |
+
default=recopy_gpt2,
|
| 396 |
+
type=str,
|
| 397 |
+
help="Reset the model to the original pretrained GPT-2 weights after each iteration",
|
| 398 |
+
)
|
| 399 |
+
|
| 400 |
+
# function calls
|
| 401 |
+
# Collecting *n* pairs of context and information gain(X, IG(X)) for training the secondary learner
|
| 402 |
+
generate_n_pairs(
|
| 403 |
+
context_len=32,
|
| 404 |
+
max_steps=10,
|
| 405 |
+
size_objective_set=100,
|
| 406 |
+
min_len=1026,
|
| 407 |
+
trim=True,
|
| 408 |
+
data_file="data/tokenized_stories_train_wikitext103.jbl",
|
| 409 |
+
igf_data_file="igf_context_pairs.jbl",
|
| 410 |
+
)
|
| 411 |
+
|
| 412 |
+
# Load train data for secondary learner
|
| 413 |
+
secondary_learner_train_data = joblib.load("data/IGF_values.jbl")
|
| 414 |
+
|
| 415 |
+
# Train secondary learner
|
| 416 |
+
secondary_learner = training_secondary_learner(
|
| 417 |
+
secondary_learner_train_data,
|
| 418 |
+
secondary_learner_max_epochs=15,
|
| 419 |
+
secondary_learner_batch_size=128,
|
| 420 |
+
eval_freq=100,
|
| 421 |
+
igf_model_path="igf_model.pt",
|
| 422 |
+
)
|
| 423 |
+
|
| 424 |
+
# load pretrained openai-community/gpt2 model
|
| 425 |
+
model = GPT2LMHeadModel.from_pretrained("openai-community/gpt2")
|
| 426 |
+
set_seed(42)
|
| 427 |
+
|
| 428 |
+
# Generate train and test data to train and evaluate openai-community/gpt2 model
|
| 429 |
+
train_dataset, test_dataset = generate_datasets(
|
| 430 |
+
context_len=32, file="data/tokenized_stories_train_wikitext103.jbl", number=100, min_len=1026, trim=True
|
| 431 |
+
)
|
| 432 |
+
|
| 433 |
+
# fine-tuning of the openai-community/gpt2 model using igf (Information Gain Filtration)
|
| 434 |
+
finetune(
|
| 435 |
+
model,
|
| 436 |
+
train_dataset,
|
| 437 |
+
test_dataset,
|
| 438 |
+
context_len=32,
|
| 439 |
+
max_steps=1000,
|
| 440 |
+
batch_size=16,
|
| 441 |
+
threshold=1.0,
|
| 442 |
+
recopy_model=recopy_gpt2,
|
| 443 |
+
secondary_learner=secondary_learner,
|
| 444 |
+
eval_interval=10,
|
| 445 |
+
finetuned_model_name="openai-community/gpt2_finetuned.pt",
|
| 446 |
+
)
|
| 447 |
+
|
| 448 |
+
|
| 449 |
+
if __name__ == "__main__":
|
| 450 |
+
main()
|