-
Notifications
You must be signed in to change notification settings - Fork 0
/
train_focus.py
465 lines (416 loc) · 25.4 KB
/
train_focus.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
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
#(c) 2021 NCSOFT Corporation & Korea University. All rights reserved.
import os
import math
import logging
from pprint import pformat
from argparse import ArgumentParser
import torch
from torch.nn import Sigmoid, Softmax
from torch.nn.parallel import DistributedDataParallel
from ignite.engine import Engine, Events
from ignite.handlers import ModelCheckpoint
from ignite.metrics import Loss, MetricsLambda, RunningAverage, Precision, CharFbeta, Recall, Accuracy
from ignite.metrics import Bleu, RougeL, RougeN
from ignite.contrib.handlers import ProgressBar, PiecewiseLinear
from ignite.contrib.handlers.tensorboard_logger import TensorboardLogger, OutputHandler, OptimizerParamsHandler
from transformers import (AdamW, WEIGHTS_NAME, CONFIG_NAME)
from utils_focus import make_focus_logdir
from data_utils import get_data_loaders, add_special_tokens_
logger = logging.getLogger(__file__)
def average_distributed_scalar(scalar, args):
""" Average a scalar over the nodes if we are in distributed training. We use this for distributed evaluation. """
if args.local_rank == -1:
return scalar
scalar_t = torch.tensor(scalar, dtype=torch.float, device=args.device) / torch.distributed.get_world_size()
torch.distributed.all_reduce(scalar_t, op=torch.distributed.ReduceOp.SUM)
return scalar_t.item()
def train():
parser = ArgumentParser()
parser.add_argument("--kp_method", type=str, default="cross_attention",
help="{focus, cross_attention, concat_cross_attention, colbert}")
parser.add_argument("--model_name", type=str, default="",
help="{GPT2, BART, transformer-decoder, transformer-encdec}")
parser.add_argument("--gpt2_model_path", type=str, default="gpt2",
help="pre-trained model path for decoder only models") # gpt2-medium
parser.add_argument("--bart_model_path", type=str, default="facebook/bart-base",
help="pre-trained model path for encoder-decoder models") # facebook/bart-large
parser.add_argument("--train_dataset_path", type=str, default="data/train_focus.json",
help="Path or url of the dataset.")
parser.add_argument("--train_dataset_cache", type=str, default='data/focus_cache.tar.gz',
help="Path or url of the dataset cache")
parser.add_argument("--dev_dataset_path", type=str, default="data/valid_focus.json",
help="Path or url of the dataset.")
parser.add_argument("--dev_dataset_cache", type=str, default='data/focus_cache.tar.gz',
help="Path or url of the dataset cache")
parser.add_argument("--ps_coef", type=float, default=1.0, help="Coefficient for persona loss")
parser.add_argument("--kn_coef", type=float, default=1.0, help="Coefficient for knowledge loss")
parser.add_argument("--lm_coef", type=float, default=10.0, help="Coefficient for LM loss")
parser.add_argument("--max_history", type=int, default=1, help="Number of previous exchanges to keep in history")
parser.add_argument("--train_batch_size", type=int, default=4, help="Batch size for training")
parser.add_argument("--valid_batch_size", type=int, default=1, help="Batch size for validation")
parser.add_argument("--gradient_accumulation_steps", type=int, default=16,
help="Accumulate gradients on several steps")
parser.add_argument("--lr", type=float, default=6.25e-5, help="Learning rate")
parser.add_argument("--max_norm", type=float, default=1.0, help="Clipping gradient norm")
parser.add_argument("--n_epochs", type=int, default=1, help="Number of training epochs")
parser.add_argument("--eval_before_start", action='store_true',
help="If true start with a first evaluation before training")
parser.add_argument("--inference", action='store_true', help="If true, inference with gold knowledge")
parser.add_argument("--test_infer", action='store_true', help="If true, test inference")
parser.add_argument("--device", type=str, default="cuda" if torch.cuda.is_available() else "cpu",
help="Device (cuda or cpu)")
parser.add_argument("--fp16", type=str, default="",
help="Set to O0, O1, O2 or O3 for fp16 training (see apex documentation)")
parser.add_argument("--local_rank", type=int, default=-1,
help="Local rank for distributed training (-1: not distributed)")
parser.add_argument("--gpu_start_num", type=int, default=1, help="Start number of GPU")
parser.add_argument("--flag", type=str, default="", help="Assign the name of the folder")
parser.add_argument("--seed", type=int, default=19950604)
parser.add_argument("--random_knowledge", action='store_true',
help="If true, the model choose the knowledge randomly")
parser.add_argument("--incontext", action='store_true', help="If true, it will use incontext structure")
args = parser.parse_args()
torch.manual_seed(args.seed)
logging.basicConfig(level=logging.INFO if args.local_rank in [-1, 0] else logging.WARN)
logger.info("Arguments: %s", pformat(args))
args.distributed = (args.local_rank != -1)
if args.distributed:
local_rank = args.local_rank + args.gpu_start_num
print("args local rank: ", args.local_rank, " local rank: ", local_rank)
torch.cuda.set_device(local_rank)
args.device = torch.device("cuda", local_rank)
torch.distributed.init_process_group(backend='nccl', init_method='env://')
logger.info("Prepare tokenizer, pretrained model and optimizer.")
if args.model_name == 'GPT2':
from transformers import GPT2Tokenizer
if args.kp_method == 'focus':
from classification_modules import GPT2PK_ctxt as gpt2model
elif args.kp_method == 'cross_attention':
from classification_modules import GPT2PK_cratn as gpt2model
elif args.kp_method == 'concat_cross_attention':
from classification_modules import GPT2PK_catatn as gpt2model
elif args.kp_method == 'colbert':
from classification_modules import GPT2PK_colbert as gpt2model
else:
raise ValueError(f'Unknown kp_method: {args.kp_method}')
tokenizer = GPT2Tokenizer.from_pretrained(args.gpt2_model_path)
model = gpt2model.from_pretrained(args.gpt2_model_path)
model.to(args.device)
model.eval()
if args.gpt2_model_path == 'gpt2' or 'gpt2-medium':
add_special_tokens_(model, tokenizer)
elif args.model_name == 'BART':
from transformers import BartTokenizer
if args.kp_method == 'focus':
from classification_modules import BARTPK_ctxt as bartmodel
elif args.kp_method == 'cross_attention':
from classification_modules import BARTPK_cratn as bartmodel
elif args.kp_method == 'concat_cross_attention':
from classification_modules import BARTPK_catatn as bartmodel
elif args.kp_method == 'colbert':
from classification_modules import BARTPK_colbert as bartmodel
else:
raise ValueError(f'Unknown kp_method: {args.kp_method}')
tokenizer = BartTokenizer.from_pretrained(args.bart_model_path)
model = bartmodel.from_pretrained(args.bart_model_path)
model.to(args.device)
model.eval()
if args.bart_model_path == "facebook/bart-base" or "facebook/bart-large":
add_special_tokens_(model, tokenizer)
elif args.model_name == 'transformer-decoder':
from transformers import GPT2Tokenizer, GPT2Config
if args.kp_method == 'focus':
from classification_modules import GPT2PK_ctxt as gpt2model
elif args.kp_method == 'cross_attention':
from classification_modules import GPT2PK_cratn as gpt2model
elif args.kp_method == 'concat_cross_attention':
from classification_modules import GPT2PK_catatn as gpt2model
elif args.kp_method == 'colbert':
from classification_modules import GPT2PK_colbert as gpt2model
else:
raise ValueError(f'Unknown kp_method: {args.kp_method}')
tokenizer = GPT2Tokenizer.from_pretrained(args.gpt2_model_path)
model_config = GPT2Config.from_pretrained(args.gpt2_model_path)
model = gpt2model(model_config)
model.to(args.device)
if args.gpt2_model_path == 'gpt2' or 'gpt2-medium':
add_special_tokens_(model, tokenizer)
elif args.model_name == 'transformer-encdec':
from transformers import BartTokenizer, BartConfig
if args.kp_method == 'focus':
from classification_modules import BARTPK_ctxt as bartmodel
elif args.kp_method == 'cross_attention':
from classification_modules import BARTPK_cratn as bartmodel
elif args.kp_method == 'concat_cross_attention':
from classification_modules import BARTPK_catatn as bartmodel
elif args.kp_method == 'colbert':
from classification_modules import BARTPK_colbert as bartmodel
else:
raise ValueError(f'Unknown kp_method: {args.kp_method}')
tokenizer = BartTokenizer.from_pretrained(args.bart_model_path)
model_config = BartConfig.from_pretrained(args.bart_model_path)
model = bartmodel(model_config)
model.to(args.device)
if args.bart_model_path == "facebook/bart-base" or "facebook/bart-large":
add_special_tokens_(model, tokenizer)
else:
raise NotImplementedError
# elif args.kp_method == 'cross_attention':
# if args.model_name == 'GPT2':
# from transformers import GPT2Tokenizer
# from classification_modules import GPT2PK_cratn as gpt2model
# tokenizer = GPT2Tokenizer.from_pretrained(args.gpt2_model_path)
# model = gpt2model.from_pretrained(args.gpt2_model_path)
# model.to(args.device)
# model.eval()
# if args.gpt2_model_path == 'gpt2' or 'gpt2-medium':
# add_special_tokens_(model, tokenizer)
#
# elif args.model_name == 'BART':
# from transformers import BartTokenizer
# from classification_modules import BARTPK_cratn as bartmodel
# tokenizer = BartTokenizer.from_pretrained(args.bart_model_path)
# model = bartmodel.from_pretrained(args.bart_model_path)
# model.to(args.device)
# model.eval()
# if args.bart_model_path == "facebook/bart-base" or "facebook/bart-large":
# add_special_tokens_(model, tokenizer)
#
# elif args.model_name == 'transformer-decoder':
# from transformers import GPT2Tokenizer, GPT2Config
# from classification_modules import GPT2PK_cratn as gpt2model
# tokenizer = GPT2Tokenizer.from_pretrained(args.gpt2_model_path)
# model_config = GPT2Config.from_pretrained(args.gpt2_model_path)
# model = gpt2model(model_config)
# model.to(args.device)
# if args.gpt2_model_path == 'gpt2' or 'gpt2-medium':
# add_special_tokens_(model, tokenizer)
#
# elif args.model_name == 'transformer-encdec':
# from transformers import BartTokenizer, BartConfig
# from classification_modules import BARTPK_cratn as bartmodel
# tokenizer = BartTokenizer.from_pretrained(args.bart_model_path)
# model_config = BartConfig.from_pretrained(args.bart_model_path)
# model = bartmodel(model_config)
# model.to(args.device)
# if args.bart_model_path == "facebook/bart-base" or "facebook/bart-large":
# add_special_tokens_(model, tokenizer)
#
# else:
# raise NotImplementedError
# else:
# raise NotImplementedError
optimizer = AdamW(model.parameters(), lr=args.lr, correct_bias=True)
if args.fp16:
from apex import amp # Apex is only required if we use fp16 training
model, optimizer = amp.initialize(model, optimizer, opt_level=args.fp16)
if args.distributed:
model = DistributedDataParallel(model, device_ids=[local_rank], output_device=local_rank)
logger.info("Prepare datasets")
train_loader, val_loader, train_sampler, valid_sampler = get_data_loaders(args, tokenizer)
# Training function and trainer
def update(engine, batch):
model.train()
batch = tuple(input_tensor.to(args.device) for input_tensor in batch)
if model.config.model_type == 'gpt2':
input_ids, input_eos, lm_labels, token_type_ids, mc_token_ids, persona_candidates, persona_can_idx, persona_grounding, knowledge_candidates, \
knowledge_can_idx, knowledge_grounding, tot_knowledge, tot_knowledge_token_ids, tot_knowledge_eos, reply, dialog, dialog_tti = batch
output = model(
input_ids=input_ids,
input_eos=input_eos,
token_type_ids=token_type_ids,
only_dial_input_ids=dialog,
only_dial_token_type_ids=dialog_tti,
persona_input_ids=persona_candidates,
knowledge_input_ids=knowledge_candidates,
persona_can_idx=persona_can_idx,
persona_grounding=persona_grounding,
knowledge_can_idx=knowledge_can_idx,
knowledge_grounding=knowledge_grounding,
tot_knowledge=tot_knowledge,
tot_knowledge_token_ids=tot_knowledge_token_ids,
tot_knowledge_eos=tot_knowledge_eos,
training=True,
mc_token_ids=mc_token_ids
)
elif model.config.model_type == 'bart':
input_ids, input_eos, decoder_input_ids, lm_labels, token_type_ids, mc_token_ids, persona_candidates, persona_can_idx, persona_grounding, knowledge_candidates, \
knowledge_can_idx, knowledge_grounding, tot_knowledge, tot_knowledge_eos, reply, dialog = batch
output = model(
input_ids=input_ids,
input_eos=input_eos,
only_dial_input_ids=dialog,
decoder_input_ids=decoder_input_ids,
persona_input_ids=persona_candidates,
knowledge_input_ids=knowledge_candidates,
persona_can_idx=persona_can_idx,
persona_grounding=persona_grounding,
knowledge_can_idx=knowledge_can_idx,
knowledge_grounding=knowledge_grounding,
tot_knowledge=tot_knowledge,
tot_knowledge_eos=tot_knowledge_eos,
lm_labels=lm_labels,
training=True,
mc_token_ids=mc_token_ids
)
else:
raise NotImplementedError
# train: lm_loss, knowledge_loss, persona_loss, dynamic_lm_logits, knowledge_logits, persona_logits
# valid: lm_label, dynamic_lm_logits, knowledge_logits, persona_logits
lm_loss, knowledge_loss, persona_loss = output[0], output[1], output[2]
loss = (lm_loss * args.lm_coef + knowledge_loss * args.kn_coef + persona_loss * args.ps_coef) / args.gradient_accumulation_steps
if args.fp16:
with amp.scale_loss(loss, optimizer) as scaled_loss:
scaled_loss.backward()
torch.nn.utils.clip_grad_norm_(amp.master_params(optimizer), args.max_norm)
else:
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), args.max_norm)
if engine.state.iteration % args.gradient_accumulation_steps == 0:
optimizer.step()
optimizer.zero_grad()
return (lm_loss.item(), knowledge_loss.item(), persona_loss.item())
trainer = Engine(update)
# Evaluation function and evaluator (evaluator output is the input of the metrics)
def inference(engine, batch):
model.eval()
with torch.no_grad():
batch = tuple(input_tensor.to(args.device) for input_tensor in batch)
if model.config.model_type == 'gpt2':
input_ids, input_eos, lm_labels, token_type_ids, mc_token_ids, persona_candidates, persona_can_idx, persona_grounding, knowledge_candidates, \
knowledge_can_idx, knowledge_grounding, tot_knowledge, tot_knowledge_token_ids, tot_knowledge_eos, reply, dialog, dialog_tti = batch
output = model(
input_ids=input_ids,
input_eos=input_eos,
token_type_ids=token_type_ids,
only_dial_input_ids=dialog,
only_dial_token_type_ids=dialog_tti,
persona_input_ids=persona_candidates,
knowledge_input_ids=knowledge_candidates,
persona_can_idx=persona_can_idx,
knowledge_can_idx=knowledge_can_idx,
tot_knowledge=tot_knowledge,
tot_knowledge_token_ids=tot_knowledge_token_ids,
tot_knowledge_eos=tot_knowledge_eos,
training=False,
mc_token_ids=mc_token_ids
)
# train: lm_loss, knowledge_loss, persona_loss, dynamic_lm_logits, knowledge_logits, persona_logits
# valid: lm_label, dynamic_lm_logits, knowledge_logits, persona_logits
lm_labels, lm_logits, knowledge_logits, persona_logits = output[0], output[1], output[2], output[3]
elif model.config.model_type == 'bart':
input_ids, input_eos, decoder_input_ids, lm_labels, token_type_ids, mc_token_ids, persona_candidates, persona_can_idx, persona_grounding, knowledge_candidates, \
knowledge_can_idx, knowledge_grounding, tot_knowledge, tot_knowledge_eos, reply, dialog = batch
output = model(
input_ids=input_ids,
input_eos=input_eos,
only_dial_input_ids=dialog,
decoder_input_ids=decoder_input_ids,
persona_input_ids=persona_candidates,
knowledge_input_ids=knowledge_candidates,
persona_can_idx=persona_can_idx,
knowledge_can_idx=knowledge_can_idx,
tot_knowledge=tot_knowledge,
tot_knowledge_eos=tot_knowledge_eos,
training=False,
mc_token_ids=mc_token_ids
)
lm_logits, knowledge_logits, persona_logits = output[0], output[1], output[2]
else:
raise NotImplementedError
lm_logits_flat_shifted = lm_logits[:, :-1, :].contiguous().view(-1, lm_logits.size(-1))
lm_labels_flat_shifted = lm_labels[:, 1:].contiguous().view(-1)
persona_logits = persona_logits.squeeze()
persona_grounding = persona_grounding.type_as(persona_logits).squeeze()
sigmoid = Sigmoid()
persona_pred_sigmoid = sigmoid(persona_logits)
persona_pred_sigmoid = (persona_pred_sigmoid > 0.5).float()
softmax = Softmax(dim=-1)
knowledge_pred = softmax(knowledge_logits)
_, k_index_1 = torch.topk(knowledge_pred, k=1, dim=-1)
_, k_index_5 = torch.topk(knowledge_pred, k=5, dim=-1)
k_index_1, k_index_5 = k_index_1.squeeze(0), k_index_5.squeeze(0)
k_index_1_cvtd = torch.tensor([1 if num in k_index_1 else 0 for num in range(10)], device=args.device)
k_label_cvtd = torch.tensor([1 if num in knowledge_grounding else 0 for num in range(10)],
device=args.device)
lm_pred = softmax(lm_logits_flat_shifted)
lm_val, lm_idx = torch.topk(lm_pred, k=1, dim=-1)
lm_idx = lm_idx.squeeze(-1)
mask = (lm_labels_flat_shifted != -100)
lm_labels_only = [lm_labels_flat_shifted[mask].tolist()]
lm_idx_only = lm_idx[mask].tolist()
return (lm_logits_flat_shifted, knowledge_logits, persona_logits, persona_pred_sigmoid, k_index_1_cvtd, knowledge_pred, lm_idx_only), \
(lm_labels_flat_shifted, knowledge_grounding, persona_grounding.type_as(persona_logits), lm_labels_only)
evaluator = Engine(inference)
# Attach evaluation to trainer: we evaluate when we start the training and at the end of each epoch
trainer.add_event_handler(Events.EPOCH_COMPLETED, lambda _: evaluator.run(val_loader))
if args.n_epochs < 1:
trainer.add_event_handler(Events.COMPLETED, lambda _: evaluator.run(val_loader))
if args.eval_before_start:
trainer.add_event_handler(Events.STARTED, lambda _: evaluator.run(val_loader))
# Make sure distributed data samplers split the dataset nicely between the distributed processes
if args.distributed:
trainer.add_event_handler(Events.EPOCH_STARTED, lambda engine: train_sampler.set_epoch(engine.state.epoch))
evaluator.add_event_handler(Events.EPOCH_STARTED, lambda engine: valid_sampler.set_epoch(engine.state.epoch))
# Linearly decrease the learning rate from lr to zero
scheduler = PiecewiseLinear(optimizer, "lr", [(0, args.lr), (args.n_epochs * len(train_loader), 0.0)])
trainer.add_event_handler(Events.ITERATION_STARTED, scheduler)
# Prepare metrics - note how we compute distributed metrics
RunningAverage(output_transform=lambda x: x[0]).attach(trainer, "lm_loss")
RunningAverage(output_transform=lambda x: x[1]).attach(trainer, "knowledge_loss")
RunningAverage(output_transform=lambda x: x[2]).attach(trainer, "persona_loss")
metrics = {
"lm_loss": Loss(torch.nn.CrossEntropyLoss(ignore_index=-100), output_transform=lambda x: (x[0][0], x[1][0])),
"knowledge_loss": Loss(torch.nn.CrossEntropyLoss(), output_transform=lambda x: (x[0][1], x[1][1])),
"persona_loss": Loss(torch.nn.BCEWithLogitsLoss(), output_transform=lambda x: (x[0][2], x[1][2])),
"Knowledge_acc": Accuracy(output_transform=lambda x: (x[0][5], x[1][1])),
"Persona_acc": Accuracy(output_transform=lambda x: (x[0][3], x[1][2])),
"Persona_acc_mtl": Accuracy(output_transform=lambda x: (x[0][3].unsqueeze(0), x[1][2].unsqueeze(0)), is_multilabel=True)
}
metrics.update({"average_lm_loss": MetricsLambda(average_distributed_scalar, metrics["lm_loss"], args),
"average_knowledge_loss": MetricsLambda(average_distributed_scalar, metrics["knowledge_loss"],args),
"average_persona_loss": MetricsLambda(average_distributed_scalar, metrics["persona_loss"], args),
"average_Knowledge_acc": MetricsLambda(average_distributed_scalar, metrics["Knowledge_acc"], args),
"average_Persona_acc": MetricsLambda(average_distributed_scalar, metrics["Persona_acc"], args),
"average_Persona_acc_mtl": MetricsLambda(average_distributed_scalar, metrics["Persona_acc_mtl"], args)
})
metrics["average_ppl"] = MetricsLambda(math.exp, metrics["average_lm_loss"])
for name, metric in metrics.items():
metric.attach(evaluator, name)
# On the main process: add progress bar, tensorboard, checkpoints and save model, configuration and tokenizer before we start to train
if args.local_rank in [-1, 0]:
pbar = ProgressBar(persist=True)
pbar.attach(trainer, metric_names=["lm_loss"])
evaluator.add_event_handler(Events.COMPLETED,
lambda _: pbar.log_message("Validation: %s" % pformat(evaluator.state.metrics)))
dir_name = str(os.path.basename(__file__))[:-3] + "_" + args.model_name + "_" + args.flag
log_dir = make_focus_logdir(dir_name)
tb_logger = TensorboardLogger(log_dir)
tb_logger.attach(trainer, log_handler=OutputHandler(tag="training", metric_names=["lm_loss", "knowledge_loss", "persona_loss",
"knowledge_accuracy", "persona_accuracy", "f1_score"]),
event_name=Events.ITERATION_COMPLETED)
tb_logger.attach(trainer, log_handler=OptimizerParamsHandler(optimizer), event_name=Events.ITERATION_STARTED)
tb_logger.attach(evaluator, log_handler=OutputHandler(tag="validation", metric_names=list(metrics.keys())),
event_name=Events.ITERATION_STARTED)
tb_logger.attach(evaluator, log_handler=OutputHandler(tag="validation", metric_names=list(metrics.keys())),
event_name=Events.EPOCH_STARTED)
tb_logger.attach(evaluator, log_handler=OutputHandler(tag="validation", metric_names=list(metrics.keys())),
event_name=Events.ITERATION_COMPLETED(every=5000))
checkpoint_handler = ModelCheckpoint(log_dir, 'checkpoint', n_saved=3)
trainer.add_event_handler(Events.EPOCH_COMPLETED, checkpoint_handler, {
'mymodel': getattr(model, 'module', model)}) # "getattr" takes care of distributed encapsulation
torch.save(args, log_dir + '/model_training_args.bin')
getattr(model, 'module', model).config.to_json_file(os.path.join(log_dir, CONFIG_NAME))
tokenizer.save_pretrained(log_dir)
# Run the training
trainer.run(train_loader, max_epochs=args.n_epochs)
# On the main process: close tensorboard logger and rename the last checkpoint (for easy re-loading with OpenAIGPTModel.from_pretrained method)
if args.local_rank in [-1, 0] and args.n_epochs > 0:
os.rename(os.path.join(log_dir, checkpoint_handler._saved[-1][1]), os.path.join(log_dir, WEIGHTS_NAME))
tb_logger.close()
if __name__ == "__main__":
import time
start = time.time()
train()
end = time.time()
print("Total time needed:", end-start)