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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Tune LM on Code
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import io
|
| 6 |
+
import logging
|
| 7 |
+
import math
|
| 8 |
+
import os
|
| 9 |
+
import pprint
|
| 10 |
+
import sys
|
| 11 |
+
import time
|
| 12 |
+
import json
|
| 13 |
+
import argparse
|
| 14 |
+
|
| 15 |
+
import transformers
|
| 16 |
+
|
| 17 |
+
from tqdm import tqdm
|
| 18 |
+
from datetime import datetime
|
| 19 |
+
|
| 20 |
+
import torch
|
| 21 |
+
import torch.distributed as dist
|
| 22 |
+
import torch.nn as nn
|
| 23 |
+
import torch.nn.functional as F
|
| 24 |
+
import torch.optim as optim
|
| 25 |
+
import torch.multiprocessing as mp
|
| 26 |
+
|
| 27 |
+
from dataset.MATH import MATHDataset
|
| 28 |
+
from dataset.khan_academy import KhanAcademyMathDataset
|
| 29 |
+
from dataset.mathematica import MathematicaMathDataset
|
| 30 |
+
from dataset.mathematica_with_steps import MathematicaWithStepsMathDataset
|
| 31 |
+
|
| 32 |
+
def run_training(args, train_data):
|
| 33 |
+
|
| 34 |
+
if not args.save_steps:
|
| 35 |
+
# Save every epoch
|
| 36 |
+
if not args.tpu_num_cores:
|
| 37 |
+
save_steps = len(train_data)
|
| 38 |
+
save_steps = int(save_steps / torch.cuda.device_count())
|
| 39 |
+
save_steps = int(save_steps / args.grad_acc_steps)
|
| 40 |
+
save_steps = int(save_steps / args.batch_size_per_replica)
|
| 41 |
+
else:
|
| 42 |
+
save_steps = len(train_data)
|
| 43 |
+
save_steps = int(save_steps / 8) # 8 TPU cores is constant for now.
|
| 44 |
+
save_steps = int(save_steps / args.grad_acc_steps)
|
| 45 |
+
save_steps = int(save_steps / args.batch_size_per_replica)
|
| 46 |
+
else:
|
| 47 |
+
save_steps = args.save_steps
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
print("Save Steps = ", save_steps)
|
| 52 |
+
|
| 53 |
+
## Checkpoint Loading ########################################################
|
| 54 |
+
if args.load:
|
| 55 |
+
model = transformers.GPT2LMHeadModel.from_pretrained(args.load)
|
| 56 |
+
print(f"Loaded model from {args.load}")
|
| 57 |
+
else:
|
| 58 |
+
model = transformers.GPT2LMHeadModel.from_pretrained(args.arch)
|
| 59 |
+
|
| 60 |
+
start_epoch = 0
|
| 61 |
+
start_iteration = 0
|
| 62 |
+
|
| 63 |
+
## Dataloading ########################################################
|
| 64 |
+
train_data.start_iteration = start_iteration
|
| 65 |
+
|
| 66 |
+
## Start Loop ########################################################
|
| 67 |
+
print(f"Setting up Trainer")
|
| 68 |
+
|
| 69 |
+
training_args = transformers.TrainingArguments(
|
| 70 |
+
output_dir=args.save_dir,
|
| 71 |
+
overwrite_output_dir=False,
|
| 72 |
+
|
| 73 |
+
do_train=True,
|
| 74 |
+
do_eval=False,
|
| 75 |
+
do_predict=True,
|
| 76 |
+
evaluation_strategy='no',
|
| 77 |
+
eval_steps=0,
|
| 78 |
+
|
| 79 |
+
num_train_epochs=args.epochs,
|
| 80 |
+
per_device_train_batch_size=args.batch_size_per_replica,
|
| 81 |
+
gradient_accumulation_steps=args.grad_acc_steps,
|
| 82 |
+
|
| 83 |
+
learning_rate=args.lr,
|
| 84 |
+
weight_decay=args.weight_decay,
|
| 85 |
+
warmup_steps=args.lr_warmup_steps,
|
| 86 |
+
max_grad_norm=100000.0, # Essentially disable gradient clipping
|
| 87 |
+
|
| 88 |
+
logging_dir=args.save_dir,
|
| 89 |
+
logging_first_step=True,
|
| 90 |
+
logging_steps=args.log_freq,
|
| 91 |
+
save_steps=save_steps,
|
| 92 |
+
save_total_limit=10, # Only save the last epoch
|
| 93 |
+
|
| 94 |
+
dataloader_drop_last=True,
|
| 95 |
+
dataloader_num_workers=args.dataloader_num_workers,
|
| 96 |
+
|
| 97 |
+
local_rank=args.local_rank,
|
| 98 |
+
tpu_num_cores=args.tpu_num_cores,
|
| 99 |
+
)
|
| 100 |
+
|
| 101 |
+
trainer = GPT2Trainer(
|
| 102 |
+
model=model,
|
| 103 |
+
args=training_args,
|
| 104 |
+
train_dataset=train_data,
|
| 105 |
+
)
|
| 106 |
+
trainer.remove_callback(transformers.integrations.TensorBoardCallback)
|
| 107 |
+
trainer.add_callback(CustomTensorBoardCallback())
|
| 108 |
+
|
| 109 |
+
print(f"STARTING TRAINING. save_steps={save_steps}")
|
| 110 |
+
trainer.train()
|
| 111 |
+
|
| 112 |
+
trainer.save_model(os.path.join(args.save_dir, "final_checkpoint"))
|
| 113 |
+
print("Finished")
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
class GPT2Trainer(transformers.Trainer):
|
| 117 |
+
def create_optimizer_and_scheduler(self, num_training_steps: int):
|
| 118 |
+
"""
|
| 119 |
+
Setup the optimizer and the learning rate scheduler.
|
| 120 |
+
We provide a reasonable default that works well. If you want to use something else, you can pass a tuple in the
|
| 121 |
+
Trainer's init through :obj:`optimizers`, or subclass and override this method in a subclass.
|
| 122 |
+
"""
|
| 123 |
+
if self.optimizer is None:
|
| 124 |
+
print("Making AdamW Optimizer")
|
| 125 |
+
no_decay = ["bias", "LayerNorm.weight"]
|
| 126 |
+
optimizer_grouped_parameters = [
|
| 127 |
+
{
|
| 128 |
+
"params": [p for n, p in self.model.named_parameters() if not any(nd in n for nd in no_decay)],
|
| 129 |
+
"weight_decay": self.args.weight_decay,
|
| 130 |
+
},
|
| 131 |
+
{
|
| 132 |
+
"params": [p for n, p in self.model.named_parameters() if any(nd in n for nd in no_decay)],
|
| 133 |
+
"weight_decay": 0.0,
|
| 134 |
+
},
|
| 135 |
+
]
|
| 136 |
+
self.optimizer = torch.optim.AdamW(
|
| 137 |
+
optimizer_grouped_parameters,
|
| 138 |
+
lr=self.args.learning_rate,
|
| 139 |
+
betas=(self.args.adam_beta1, self.args.adam_beta2),
|
| 140 |
+
eps=self.args.adam_epsilon,
|
| 141 |
+
)
|
| 142 |
+
|
| 143 |
+
if self.lr_scheduler is None:
|
| 144 |
+
|
| 145 |
+
if self.args.warmup_steps == -1:
|
| 146 |
+
print("Using constant LR")
|
| 147 |
+
self.lr_scheduler = torch.optim.lr_scheduler.LambdaLR(self.optimizer, lambda steps: 1.0)
|
| 148 |
+
else:
|
| 149 |
+
print("Using Linear warmup LR")
|
| 150 |
+
self.lr_scheduler = self.get_linear_schedule_with_warmup(
|
| 151 |
+
self.optimizer, num_warmup_steps=self.args.warmup_steps, num_training_steps=num_training_steps
|
| 152 |
+
)
|
| 153 |
+
|
| 154 |
+
@staticmethod
|
| 155 |
+
def get_linear_schedule_with_warmup(optimizer, num_warmup_steps, num_training_steps, last_epoch=-1):
|
| 156 |
+
"""
|
| 157 |
+
Linear warmup from 0 to max lr, then linear decay from max_lr to 0.1*max_lr
|
| 158 |
+
As done in https://arxiv.org/pdf/2010.14701.pdf
|
| 159 |
+
"""
|
| 160 |
+
def lr_lambda(current_step: int):
|
| 161 |
+
if current_step < num_warmup_steps:
|
| 162 |
+
return float(current_step) / float(max(1, num_warmup_steps))
|
| 163 |
+
min_lr_multiplier = 0.1
|
| 164 |
+
return max(
|
| 165 |
+
min_lr_multiplier,
|
| 166 |
+
((1 - min_lr_multiplier) * float(num_training_steps - current_step) / float(max(1, num_training_steps - num_warmup_steps))) + min_lr_multiplier
|
| 167 |
+
)
|
| 168 |
+
|
| 169 |
+
return torch.optim.lr_scheduler.LambdaLR(optimizer, lr_lambda, last_epoch)
|
| 170 |
+
|
| 171 |
+
def get_tokenizer_gpt(args):
|
| 172 |
+
"""
|
| 173 |
+
If args.tokenizer_merges_file is given, return a tokenizer that uses that merges_file.
|
| 174 |
+
In the paper, we use this to restrict models to ingest and outuput digits. For example:
|
| 175 |
+
|
| 176 |
+
>>> tokenizer = transformers.GPT2Tokenizer.from_pretrained("gpt2", merges_file="merges_gpt2_single_digit_numbers.txt")
|
| 177 |
+
>>> tokenizer_old = transformers.GPT2Tokenizer.from_pretrained("gpt2")
|
| 178 |
+
>>> tokenizer.encode("1")
|
| 179 |
+
[16]
|
| 180 |
+
>>> tokenizer_old.encode("1")
|
| 181 |
+
[16]
|
| 182 |
+
>>> tokenizer.encode("2")
|
| 183 |
+
[17]
|
| 184 |
+
>>> tokenizer_old.encode("12")
|
| 185 |
+
[1065]
|
| 186 |
+
>>> tokenizer.encode("12")
|
| 187 |
+
[16, 17]
|
| 188 |
+
>>> tokenizer.encode("HEllo world!")
|
| 189 |
+
[13909, 18798, 995, 0]
|
| 190 |
+
>>> tokenizer_old.encode("HEllo world!")
|
| 191 |
+
[13909, 18798, 995, 0]
|
| 192 |
+
"""
|
| 193 |
+
if args.tokenizer_merges_file is not None:
|
| 194 |
+
tokenizer = transformers.GPT2Tokenizer.from_pretrained(args.arch, merges_file=args.tokenizer_merges_file)
|
| 195 |
+
else:
|
| 196 |
+
tokenizer = transformers.GPT2Tokenizer.from_pretrained(args.arch)
|
| 197 |
+
return tokenizer
|
| 198 |
+
|
| 199 |
+
def get_dataset(args):
|
| 200 |
+
|
| 201 |
+
tokenizer = get_tokenizer_gpt(args)
|
| 202 |
+
# print(tokenizer.tokenize("1231231234441234 blah dklkjl12490!!@ 2*x + y^k + f(x)")) # sanity check
|
| 203 |
+
|
| 204 |
+
train_data = []
|
| 205 |
+
|
| 206 |
+
if args.mathematica_dataroot:
|
| 207 |
+
for mathematica_dr in args.mathematica_dataroot:
|
| 208 |
+
len_multiplier, dirname = mathematica_dr.split("@")
|
| 209 |
+
len_multiplier = float(len_multiplier)
|
| 210 |
+
|
| 211 |
+
no_steps_flist_fname = os.path.join(dirname, "no_steps_flist_relative.txt")
|
| 212 |
+
with_steps_flist_fname = os.path.join(dirname, "with_steps_flist_relative.txt")
|
| 213 |
+
|
| 214 |
+
with open(no_steps_flist_fname,"r") as f:
|
| 215 |
+
no_steps_num_files = len(f.readlines())
|
| 216 |
+
|
| 217 |
+
with open(with_steps_flist_fname,"r") as f:
|
| 218 |
+
with_steps_num_files = len(f.readlines())
|
| 219 |
+
|
| 220 |
+
if no_steps_num_files:
|
| 221 |
+
train_data.append(MathematicaMathDataset(
|
| 222 |
+
dataroot=no_steps_flist_fname,
|
| 223 |
+
tokenizer=tokenizer,
|
| 224 |
+
max_tokens=384 if args.arch == 'gpt2-xl' else 1024,
|
| 225 |
+
mode='gpt2',
|
| 226 |
+
len_multiplier=len_multiplier
|
| 227 |
+
))
|
| 228 |
+
|
| 229 |
+
if with_steps_num_files:
|
| 230 |
+
train_data.append(MathematicaWithStepsMathDataset(
|
| 231 |
+
dataroot=with_steps_flist_fname,
|
| 232 |
+
tokenizer=tokenizer,
|
| 233 |
+
max_tokens=384 if args.arch == 'gpt2-xl' else 1024,
|
| 234 |
+
mode='gpt2',
|
| 235 |
+
len_multiplier=len_multiplier
|
| 236 |
+
))
|
| 237 |
+
|
| 238 |
+
if args.khan_dataroot:
|
| 239 |
+
len_multiplier, dirname = args.khan_dataroot.split("@")
|
| 240 |
+
len_multiplier = float(len_multiplier)
|
| 241 |
+
train_data.append(KhanAcademyMathDataset(
|
| 242 |
+
dataroot=dirname,
|
| 243 |
+
tokenizer=tokenizer,
|
| 244 |
+
max_tokens=384 if args.arch == 'gpt2-xl' else 1024,
|
| 245 |
+
mode='gpt2',
|
| 246 |
+
mode_answer=args.khan_mode,
|
| 247 |
+
len_multiplier=len_multiplier,
|
| 248 |
+
latex_mask=args.khan_latex_mask
|
| 249 |
+
))
|
| 250 |
+
|
| 251 |
+
if args.MATH_dataroot:
|
| 252 |
+
train_data.append(MATHDataset(
|
| 253 |
+
dataroot=args.MATH_dataroot,
|
| 254 |
+
tokenizer=tokenizer,
|
| 255 |
+
max_tokens=384 if args.arch == 'gpt2-xl' else 1024,
|
| 256 |
+
mode='gpt2',
|
| 257 |
+
mode_answer=args.MATH_mode,
|
| 258 |
+
len_multiplier=1.0,
|
| 259 |
+
peek_fraction=(args.MATH_peek_min, args.MATH_peek_max),
|
| 260 |
+
packing=True, # Special for fine-tuning
|
| 261 |
+
randomize=True # Special for fine-tuning
|
| 262 |
+
))
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
# Print the sizes of each dataset, useful for weighting
|
| 266 |
+
for dset in train_data:
|
| 267 |
+
print(f"{dset.__class__.__name__}: __len__ = {len(dset)}")
|
| 268 |
+
|
| 269 |
+
return torch.utils.data.ConcatDataset(train_data)
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
def main():
|
| 273 |
+
|
| 274 |
+
######### Arg parsing ###############################################################
|
| 275 |
+
|
| 276 |
+
parser = argparse.ArgumentParser(description="Language Modelling on Code")
|
| 277 |
+
parser.add_argument('--arch', default='gpt2', choices=transformers.GPT2_PRETRAINED_MODEL_ARCHIVE_LIST)
|
| 278 |
+
parser.add_argument('--tokenizer-merges-file', default=None, type=str)
|
| 279 |
+
parser.add_argument('--load', default=None, type=str)
|
| 280 |
+
|
| 281 |
+
# Dataloading
|
| 282 |
+
parser.add_argument('--khan-mode', default='mixed_hints', type=str)
|
| 283 |
+
parser.add_argument('--khan-dataroot', default=None, type=str)
|
| 284 |
+
parser.add_argument('--khan-latex-mask', default=False, action='store_true')
|
| 285 |
+
parser.add_argument('--deepmind-dataroot', default=None, type=str, action='append')
|
| 286 |
+
parser.add_argument('--mathematica-dataroot', default=None, type=str, action='append')
|
| 287 |
+
parser.add_argument('--mathematica-with-steps-dataroot', default=None, type=str, action='append')
|
| 288 |
+
parser.add_argument('--MATH-mode', default='mixed_final_boxed_and_full', type=str, choices=['mixed_final_boxed_and_full', 'final_boxed', 'peeking', 'nopack_padding', 'mixed_full_and_peeking', 'mixed_full_and_nopack_padding'])
|
| 289 |
+
parser.add_argument('--MATH-peek-min', default=0.1, type=float)
|
| 290 |
+
parser.add_argument('--MATH-peek-max', default=1.0, type=float)
|
| 291 |
+
parser.add_argument('--MATH-dataroot', default=None, type=str)
|
| 292 |
+
parser.add_argument('--stackexchange-dataroot', default=None, type=str)
|
| 293 |
+
parser.add_argument('--dataloader-num-workers', default=1, type=int)
|
| 294 |
+
|
| 295 |
+
# Training
|
| 296 |
+
parser.add_argument('--epochs', default=1, type=int)
|
| 297 |
+
parser.add_argument('--lr', default=5e-5, type=float)
|
| 298 |
+
parser.add_argument('--weight-decay', default=0.05, type=float)
|
| 299 |
+
parser.add_argument('--lr-warmup-steps', default=-1, type=int)
|
| 300 |
+
parser.add_argument('--batch-size-per-replica', default=8, type=int)
|
| 301 |
+
parser.add_argument('--grad-acc-steps', default=4, type=int)
|
| 302 |
+
parser.add_argument('--local_rank', default=-1, type=int)
|
| 303 |
+
parser.add_argument('--tpu_num_cores', default=None, type=int)
|
| 304 |
+
|
| 305 |
+
# Logging and stuff
|
| 306 |
+
parser.add_argument('--save-dir', default="checkpoints/TEMP", type=str)
|
| 307 |
+
parser.add_argument('--save-steps', default=0, type=int)
|
| 308 |
+
parser.add_argument('--log-freq', default=5, type=int)
|
| 309 |
+
|
| 310 |
+
args = parser.parse_args()
|
| 311 |
+
args.save_dir = os.path.join(args.save_dir, datetime.now().strftime("%m-%d-%Y__%H:%M:%S"))
|
| 312 |
+
|
| 313 |
+
######### Start training ###############################################################
|
| 314 |
+
|
| 315 |
+
argsdict = vars(args)
|
| 316 |
+
print(pprint.pformat(argsdict))
|
| 317 |
+
|
| 318 |
+
train_data = get_dataset(args)
|
| 319 |
+
|
| 320 |
+
os.makedirs(args.save_dir, exist_ok=True)
|
| 321 |
+
with open(os.path.join(args.save_dir, "command.txt"), 'w') as f:
|
| 322 |
+
f.write(pprint.pformat(argsdict))
|
| 323 |
+
|
| 324 |
+
run_training(args, train_data)
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
def _mp_fn(index):
|
| 328 |
+
# For xla_spawn (TPUs)
|
| 329 |
+
main()
|
| 330 |
+
|
| 331 |
+
|
| 332 |
+
if __name__ == "__main__":
|
| 333 |
+
main()
|