-
Notifications
You must be signed in to change notification settings - Fork 342
/
LSP_train.py
386 lines (325 loc) · 14.9 KB
/
LSP_train.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
'''
* @Desc: train GPT2 from scratch/ fine tuning.
Modified based on Huggingface GPT-2 implementation
'''
import json
import os
import sys
import argparse
import logging
import time
import tqdm
import datetime
import torch
import numpy as np
from os.path import join
from torch.distributed import get_rank, get_world_size
from lsp_model import GPT2LMHeadModel, GPT2Tokenizer, GPT2Config, Adam
from gpt2_training.train_utils import load_model, boolean_string, set_lr, get_eval_list_same_length
from gpt2_training.eval_utils import eval_model_loss
from data_loader import BucketingDataLoader, DynamicBatchingLoader, DistributedBucketingDataLoader
from gpt2_training.distributed import all_reduce_and_rescale_tensors, all_gather_list
logging.basicConfig(
format='%(asctime)s - %(levelname)s - %(name)s - %(message)s',
datefmt='%m/%d/%Y %H:%M:%S', level=logging.INFO)
logger = logging.getLogger(__name__)
INF = 100000000
CACHE_EMPTY_STEP = 10000
EVAL_STEP = 100000
#########################################################################
# Prepare Parser
##########################################################################
parser = argparse.ArgumentParser()
parser.add_argument('--model_name_or_path', type=str,
help='pretrained model name or path to local checkpoint')
parser.add_argument("--seed", type=int, default=42)
parser.add_argument("--max_seq_length", type=int, default=128)
parser.add_argument("--skip_eval", action='store_true',
help='If true, skip evaluation.')
parser.add_argument("--init_checkpoint", type=str)
parser.add_argument("--train_input_file", type=str)
parser.add_argument("--eval_input_file", type=str)
parser.add_argument("--continue_from", type=int, default=0)
parser.add_argument("--train_batch_size", type=int, default=4,
help="batch size now means per GPU per step")
parser.add_argument("--gradient_accumulation_steps", type=int, default=2,
help="to increase effective batch size "
"and reduce synchronization")
parser.add_argument("--eval_batch_size", type=int, default=4)
parser.add_argument("--learning_rate", type=float, default=1e-5)
parser.add_argument("--num_optim_steps", type=int, default=1000000,
help="new API specifies num update steps")
parser.add_argument("--valid_step", type=int, default=10000,
help="how many optim steps between validations")
parser.add_argument("--warmup_proportion", type=float, default=0.1)
parser.add_argument("--warmup_steps", type=int, default=16000)
parser.add_argument("--normalize_data", type=boolean_string, default=True)
parser.add_argument("--fp16", type=boolean_string, default=True)
parser.add_argument("--lr_schedule", type=str,
choices=['noam', 'noamwd', 'BERT', 'None'], default='noam')
parser.add_argument("--loss_scale", type=float, default=0)
parser.add_argument("--no_token_id", type=boolean_string, default=True)
parser.add_argument("--output_dir", type=str)
parser.add_argument("--log_dir", type=str)
parser.add_argument('--pbar', type=boolean_string, default=True, help='turn on progress bar')
# distributed
parser.add_argument('--local_rank', type=int, default=-1,
help='for torch.distributed')
parser.add_argument('--config', help='JSON config file')
# do normal parsing
args = parser.parse_args()
if args.config is not None:
# override argparse defaults by config JSON
opts = json.load(open(args.config))
for k, v in opts.items():
if isinstance(v, str):
# PHILLY ENV special cases
if 'PHILLY_JOB_DIRECTORY' in v:
v = v.replace('PHILLY_JOB_DIRECTORY',
os.environ['PHILLY_JOB_DIRECTORY'])
elif 'PHILLY_LOG_DIRECTORY' in v:
v = v.replace('PHILLY_LOG_DIRECTORY',
os.environ['PHILLY_LOG_DIRECTORY'])
setattr(args, k, v)
# command line should override config JSON
argv = sys.argv[1:]
overrides, _ = parser.parse_known_args(argv)
for k, v in vars(overrides).items():
if f'--{k}' in argv:
setattr(args, k, v)
setattr(args, 'local_rank', overrides.local_rank)
assert args.train_batch_size % args.gradient_accumulation_steps == 0, \
'batch size % gradient accumulation steps != 0!'
args.train_batch_size = (args.train_batch_size
// args.gradient_accumulation_steps)
logger.info('train batch size = {}, '
'new train batch size (after gradient accumulation) = {}'.format(
args.train_batch_size*args.gradient_accumulation_steps,
args.train_batch_size))
if args.local_rank == -1:
logger.info('CUDA available? {}'.format(str(torch.cuda.is_available())))
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
n_gpu = torch.cuda.device_count()
args.device, args.n_gpu = device, n_gpu
else:
# distributed training
torch.cuda.set_device(args.local_rank)
device = torch.device("cuda", args.local_rank)
# Initializes the distributed backend which will take care of
# sychronizing nodes/GPUs
torch.distributed.init_process_group(backend='nccl')
n_gpu = torch.distributed.get_world_size()
args.device, args.n_gpu = device, 1
logger.info("device: {} n_gpu: {}, distributed training: {}, "
"16-bits training: {}".format(
device, n_gpu, bool(args.local_rank != -1), args.fp16))
np.random.seed(args.seed)
torch.random.manual_seed(args.seed)
torch.cuda.manual_seed(args.seed)
if n_gpu > 0:
torch.cuda.manual_seed_all(args.seed)
timestamp = datetime.datetime.now().strftime('%Y-%m-%d%H%M%S')
output_dir = join(args.output_dir,
'GPT2.{}.{}.{}gpu.{}'.format(args.learning_rate,
args.train_batch_size, n_gpu,
timestamp))
log_dir = args.log_dir if args.log_dir is not None and len(args.log_dir) > 0 else output_dir
if args.local_rank == -1 or get_rank() == 0:
os.makedirs(output_dir, exist_ok=True)
logger.info('Input Argument Information')
args_dict = vars(args)
for a in args_dict:
logger.info('%-28s %s' % (a, args_dict[a]))
#########################################################################
# Prepare Data Set
##########################################################################
enc = GPT2Tokenizer.from_pretrained(args.model_name_or_path)
config = GPT2Config.from_json_file(
join(args.model_name_or_path, 'config.json'))
if args.local_rank == -1:
train_dataloader = BucketingDataLoader(args.train_input_file,
args.train_batch_size,
args.max_seq_length)
else:
train_dataloader = DistributedBucketingDataLoader(
get_rank(), get_world_size(),
args.train_input_file, args.train_batch_size,
args.max_seq_length)
eval_dataloader_loss = DynamicBatchingLoader(
args.eval_input_file, enc, args.normalize_data,
args.eval_batch_size, args.max_seq_length)
eval_dataloader_gen = get_eval_list_same_length(
args.eval_input_file, enc, args.eval_batch_size, True)
#########################################################################
# Prepare Model and Optimizer
##########################################################################
model = load_model(GPT2LMHeadModel(config), args.init_checkpoint,
args, verbose=True)
if args.local_rank != -1:
# when from scratch make sure initial models are the same
params = [p.data for p in model.parameters()]
all_reduce_and_rescale_tensors(
params, float(torch.distributed.get_world_size()))
model_parameters = filter(lambda p: p.requires_grad, model.parameters())
total_params = sum([np.prod(p.size()) for p in model_parameters])
logger.info('Number of parameter = {}'.format(total_params))
param_optimizer = list(model.named_parameters())
no_decay = ['bias', 'ln'] # no decay for bias and LayerNorm (ln)
optimizer_grouped_parameters = [
{'params': [p for n, p in param_optimizer
if not any(nd in n for nd in no_decay)],
'weight_decay': 0.01},
{'params': [p for n, p in param_optimizer
if any(nd in n for nd in no_decay)], 'weight_decay': 0.0}
]
if args.fp16:
logger.info('in fp16, using FusedAdam')
try:
from apex.optimizers import FP16_Optimizer
from apex.optimizers import FusedAdam
except ImportError:
raise ImportError(
"Please install apex from https://www.github.com/nvidia/apex "
"to use distributed and fp16 training.")
optimizer = FusedAdam(optimizer_grouped_parameters,
lr=args.learning_rate,
bias_correction=False,
max_grad_norm=1.0)
if args.loss_scale == 0:
optimizer = FP16_Optimizer(optimizer, dynamic_loss_scale=True,
verbose=False)
else:
optimizer = FP16_Optimizer(optimizer,
static_loss_scale=args.loss_scale,
verbose=False)
else:
optimizer = Adam(optimizer_grouped_parameters, args.learning_rate,
max_grad_norm=1.0)
#########################################################################
# Training !
##########################################################################
if args.local_rank == -1 or get_rank() == 0:
train_logger = open(join(log_dir, 'train_log.txt'), 'a+', buffering=1)
eval_logger = open(join(log_dir, 'eval_log.txt'), 'a+', buffering=1)
print('epoch,global_step,step,mean_loss,mean_ppl,n_token_real,'
'n_token_total,epoch_time', file=train_logger)
print('epoch,global_step,step,eval_loss,eval_ppl', file=eval_logger)
global_step = 0
step = 0
epoch = 0
if args.continue_from:
global_step = args.continue_from
step = global_step*2 - 1
if args.local_rank != -1:
n_gpu = 1
if args.local_rank == -1 or get_rank() == 0:
if args.pbar:
pbar = tqdm.tqdm(total=args.num_optim_steps, desc=f"training")
else:
pbar = None
while True:
model.train()
(tr_loss, tr_ppl, mean_ppl, nb_tr_examples, nb_tr_steps) = 0.0, 0.0, 0.0, 0, 0
n_token_real, n_token_total = 0, 0
train_start_time_epoch = time.time()
for batch in train_dataloader:
# activate new training mode
seq_len = batch[0].shape[1]
batch = tuple(t.to(device) for t in batch)
input_ids, position_ids, token_ids, label_ids, *_ = batch
if args.no_token_id:
token_ids = None
loss, ppl = model(input_ids, position_ids, token_ids, label_ids)
if n_gpu > 1:
loss = loss.mean()
ppl = ppl.mean()
loss = loss / (args.train_batch_size / input_ids.shape[0])
if args.fp16:
optimizer.backward(loss)
else:
loss.backward()
tr_loss += float(loss.item()) * (args.train_batch_size / input_ids.shape[0])
nb_tr_examples += input_ids.size(0)
nb_tr_steps += 1
mean_loss = tr_loss / nb_tr_steps
if ppl.item() < INF:
tr_ppl += ppl.item()
else:
tr_ppl += mean_ppl
mean_ppl = tr_ppl / nb_tr_steps
n_token_total += input_ids.shape[0] * input_ids.shape[1]
n_token_real += (input_ids != 0).sum().item()
# gradient update
step += 1
if step % args.gradient_accumulation_steps == 0:
set_lr(optimizer, global_step,
args.lr_schedule, args.learning_rate,
args.warmup_steps, args.warmup_proportion,
config.n_embd, args.num_optim_steps)
if args.local_rank != -1:
grads = [p.grad.data for p in model.parameters()
if p.requires_grad and p.grad is not None]
all_reduce_and_rescale_tensors(grads, float(1))
optimizer.step()
optimizer.zero_grad()
global_step += 1
# Print log info to file
if args.local_rank != -1:
mean_loss = sum(all_gather_list(mean_loss)) / get_world_size()
mean_ppl = sum(all_gather_list(mean_ppl)) / get_world_size()
n_token_real_all_proc = sum(all_gather_list(n_token_real))
n_token_total_all_proc = sum(all_gather_list(n_token_total))
else:
n_token_real_all_proc = n_token_real
n_token_total_all_proc = n_token_total
if args.local_rank == -1 or get_rank() == 0:
epoch_time = time.time() - train_start_time_epoch
if pbar is not None:
pbar.set_postfix_str(
f"tok/s: {n_token_real_all_proc//epoch_time//1000}k "
f"ppl: {mean_ppl:.2f} epoch: {epoch}")
pbar.update(1)
print('{},{},{},{},{},{},{},{}'.format(
epoch+1, global_step+1, step+1, mean_loss, mean_ppl,
n_token_real_all_proc, n_token_total_all_proc, epoch_time),
file=train_logger)
if global_step % args.valid_step == 0:
if args.local_rank == -1 or get_rank() == 0:
# only rank 0 process evaluate
torch.save(
{k: (v.cpu() if v is not None else None) # save to cpu tensors
for k, v in model.state_dict().items()},
join(output_dir,
f'GP2-pretrain-step-{global_step}.pkl'))
eval_loss, eval_ppl = eval_model_loss(
model, enc, eval_dataloader_loss, epoch, args)
# enable generation step evaluation for now
# gen_response = eval_model_generation(
# model, enc, eval_dataloader_gen, epoch, args)
'''
# probably use beam search only for test set
if False:
gen_response_beam = eval_model_generation(
model, enc, eval_dataloader_gen, epoch, args,
use_beam_search=True, beam_width=3)
'''
print('{},{},{},{},{}'.format(
epoch+1, global_step+1, step+1, eval_loss, eval_ppl),
file=eval_logger)
logger.info('current learning rate: '
+ str(optimizer.param_groups[0]['lr']))
model.train()
if global_step >= args.num_optim_steps:
break
if (step+1) % CACHE_EMPTY_STEP == 0:
torch.cuda.empty_cache()
if global_step >= args.num_optim_steps:
break
epoch += 1
if args.local_rank == -1 or get_rank() == 0:
if pbar is not None:
pbar.close()
train_logger.close()
eval_logger.close()