Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

run_factoid.py 33 KB

You have to be logged in to leave a comment. Sign In
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
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
  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. """ Finetuning the library models for question-answering on SQuAD (DistilBERT, Bert, XLM, XLNet)."""
  17. import argparse
  18. import glob
  19. import logging
  20. import os
  21. import random
  22. import timeit
  23. import numpy as np
  24. import torch
  25. from torch.utils.data import DataLoader, RandomSampler, SequentialSampler
  26. from torch.utils.data.distributed import DistributedSampler
  27. from tqdm import tqdm, trange
  28. from transformers import (
  29. MODEL_FOR_QUESTION_ANSWERING_MAPPING,
  30. WEIGHTS_NAME,
  31. AdamW,
  32. AutoConfig,
  33. AutoModelForQuestionAnswering,
  34. AutoTokenizer,
  35. get_linear_schedule_with_warmup,
  36. squad_convert_examples_to_features,
  37. )
  38. from transformers.data.metrics.squad_metrics import (
  39. compute_predictions_log_probs,
  40. compute_predictions_logits,
  41. squad_evaluate,
  42. )
  43. from transformers.data.processors.squad import SquadResult, SquadV1Processor, SquadV2Processor
  44. try:
  45. from torch.utils.tensorboard import SummaryWriter
  46. except ImportError:
  47. from tensorboardX import SummaryWriter
  48. from utils_qa import transform_n2b_factoid, eval_bioasq_standard
  49. logger = logging.getLogger(__name__)
  50. MODEL_CONFIG_CLASSES = list(MODEL_FOR_QUESTION_ANSWERING_MAPPING.keys())
  51. MODEL_TYPES = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)
  52. os.environ["TOKENIZERS_PARALLELISM"] = "false"
  53. def set_seed(args):
  54. random.seed(args.seed)
  55. np.random.seed(args.seed)
  56. torch.manual_seed(args.seed)
  57. if args.n_gpu > 0:
  58. torch.cuda.manual_seed_all(args.seed)
  59. def to_list(tensor):
  60. return tensor.detach().cpu().tolist()
  61. def train(args, train_dataset, model, tokenizer):
  62. """ Train the model """
  63. if args.local_rank in [-1, 0]:
  64. tb_writer = SummaryWriter()
  65. args.train_batch_size = args.per_gpu_train_batch_size * max(1, args.n_gpu)
  66. train_sampler = RandomSampler(train_dataset) if args.local_rank == -1 else DistributedSampler(train_dataset)
  67. train_dataloader = DataLoader(train_dataset, sampler=train_sampler, batch_size=args.train_batch_size)
  68. if args.max_steps > 0:
  69. t_total = args.max_steps
  70. args.num_train_epochs = args.max_steps // (len(train_dataloader) // args.gradient_accumulation_steps) + 1
  71. else:
  72. t_total = len(train_dataloader) // args.gradient_accumulation_steps * args.num_train_epochs
  73. # Prepare optimizer and schedule (linear warmup and decay)
  74. no_decay = ["bias", "LayerNorm.weight"]
  75. optimizer_grouped_parameters = [
  76. {
  77. "params": [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay)],
  78. "weight_decay": args.weight_decay,
  79. },
  80. {"params": [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay)], "weight_decay": 0.0},
  81. ]
  82. optimizer = AdamW(optimizer_grouped_parameters, lr=args.learning_rate, eps=args.adam_epsilon)
  83. scheduler = get_linear_schedule_with_warmup(
  84. optimizer, num_warmup_steps=args.warmup_steps, num_training_steps=t_total
  85. )
  86. # Check if saved optimizer or scheduler states exist
  87. if os.path.isfile(os.path.join(args.model_name_or_path, "optimizer.pt")) and os.path.isfile(
  88. os.path.join(args.model_name_or_path, "scheduler.pt")
  89. ):
  90. # Load in optimizer and scheduler states
  91. optimizer.load_state_dict(torch.load(os.path.join(args.model_name_or_path, "optimizer.pt")))
  92. scheduler.load_state_dict(torch.load(os.path.join(args.model_name_or_path, "scheduler.pt")))
  93. if args.fp16:
  94. try:
  95. from apex import amp
  96. except ImportError:
  97. raise ImportError("Please install apex from https://www.github.com/nvidia/apex to use fp16 training.")
  98. model, optimizer = amp.initialize(model, optimizer, opt_level=args.fp16_opt_level)
  99. # multi-gpu training (should be after apex fp16 initialization)
  100. if args.n_gpu > 1:
  101. model = torch.nn.DataParallel(model)
  102. # Distributed training (should be after apex fp16 initialization)
  103. if args.local_rank != -1:
  104. model = torch.nn.parallel.DistributedDataParallel(
  105. model, device_ids=[args.local_rank], output_device=args.local_rank, find_unused_parameters=True
  106. )
  107. # Train!
  108. logger.info("***** Running training *****")
  109. logger.info(" Num examples = %d", len(train_dataset))
  110. logger.info(" Num Epochs = %d", args.num_train_epochs)
  111. logger.info(" Instantaneous batch size per GPU = %d", args.per_gpu_train_batch_size)
  112. logger.info(
  113. " Total train batch size (w. parallel, distributed & accumulation) = %d",
  114. args.train_batch_size
  115. * args.gradient_accumulation_steps
  116. * (torch.distributed.get_world_size() if args.local_rank != -1 else 1),
  117. )
  118. logger.info(" Gradient Accumulation steps = %d", args.gradient_accumulation_steps)
  119. logger.info(" Total optimization steps = %d", t_total)
  120. global_step = 1
  121. epochs_trained = 0
  122. steps_trained_in_current_epoch = 0
  123. # Check if continuing training from a checkpoint
  124. if os.path.exists(args.model_name_or_path):
  125. try:
  126. # set global_step to gobal_step of last saved checkpoint from model path
  127. checkpoint_suffix = args.model_name_or_path.split("-")[-1].split("/")[0]
  128. global_step = int(checkpoint_suffix)
  129. epochs_trained = global_step // (len(train_dataloader) // args.gradient_accumulation_steps)
  130. steps_trained_in_current_epoch = global_step % (len(train_dataloader) // args.gradient_accumulation_steps)
  131. logger.info(" Continuing training from checkpoint, will skip to saved global_step")
  132. logger.info(" Continuing training from epoch %d", epochs_trained)
  133. logger.info(" Continuing training from global step %d", global_step)
  134. logger.info(" Will skip the first %d steps in the first epoch", steps_trained_in_current_epoch)
  135. except ValueError:
  136. logger.info(" Starting fine-tuning.")
  137. tr_loss, logging_loss = 0.0, 0.0
  138. model.zero_grad()
  139. train_iterator = trange(
  140. epochs_trained, int(args.num_train_epochs), desc="Epoch", disable=args.local_rank not in [-1, 0]
  141. )
  142. # Added here for reproductibility
  143. set_seed(args)
  144. for _ in train_iterator:
  145. epoch_iterator = tqdm(train_dataloader, desc="Iteration", disable=args.local_rank not in [-1, 0])
  146. for step, batch in enumerate(epoch_iterator):
  147. # Skip past any already trained steps if resuming training
  148. if steps_trained_in_current_epoch > 0:
  149. steps_trained_in_current_epoch -= 1
  150. continue
  151. model.train()
  152. batch = tuple(t.to(args.device) for t in batch)
  153. inputs = {
  154. "input_ids": batch[0],
  155. "attention_mask": batch[1],
  156. "token_type_ids": batch[2],
  157. "start_positions": batch[3],
  158. "end_positions": batch[4],
  159. }
  160. if args.model_type in ["xlm", "roberta", "distilbert", "camembert"]:
  161. del inputs["token_type_ids"]
  162. if args.model_type in ["xlnet", "xlm"]:
  163. inputs.update({"cls_index": batch[5], "p_mask": batch[6]})
  164. if args.version_2_with_negative:
  165. inputs.update({"is_impossible": batch[7]})
  166. if hasattr(model, "config") and hasattr(model.config, "lang2id"):
  167. inputs.update(
  168. {"langs": (torch.ones(batch[0].shape, dtype=torch.int64) * args.lang_id).to(args.device)}
  169. )
  170. outputs = model(**inputs)
  171. # model outputs are always tuple in transformers (see doc)
  172. loss = outputs[0]
  173. if args.n_gpu > 1:
  174. loss = loss.mean() # mean() to average on multi-gpu parallel (not distributed) training
  175. if args.gradient_accumulation_steps > 1:
  176. loss = loss / args.gradient_accumulation_steps
  177. if args.fp16:
  178. with amp.scale_loss(loss, optimizer) as scaled_loss:
  179. scaled_loss.backward()
  180. else:
  181. loss.backward()
  182. tr_loss += loss.item()
  183. if (step + 1) % args.gradient_accumulation_steps == 0:
  184. if args.fp16:
  185. torch.nn.utils.clip_grad_norm_(amp.master_params(optimizer), args.max_grad_norm)
  186. else:
  187. torch.nn.utils.clip_grad_norm_(model.parameters(), args.max_grad_norm)
  188. optimizer.step()
  189. scheduler.step() # Update learning rate schedule
  190. model.zero_grad()
  191. global_step += 1
  192. # Log metrics
  193. if args.local_rank in [-1, 0] and args.logging_steps > 0 and global_step % args.logging_steps == 0:
  194. # Only evaluate when single GPU otherwise metrics may not average well
  195. if args.local_rank == -1 and args.evaluate_during_training:
  196. results = evaluate(args, model, tokenizer)
  197. for key, value in results.items():
  198. tb_writer.add_scalar("eval_{}".format(key), value, global_step)
  199. tb_writer.add_scalar("lr", scheduler.get_lr()[0], global_step)
  200. tb_writer.add_scalar("loss", (tr_loss - logging_loss) / args.logging_steps, global_step)
  201. logging_loss = tr_loss
  202. # Save model checkpoint
  203. if args.local_rank in [-1, 0] and args.save_steps > 0 and global_step % args.save_steps == 0:
  204. output_dir = os.path.join(args.output_dir, "checkpoint-{}".format(global_step))
  205. # Take care of distributed/parallel training
  206. model_to_save = model.module if hasattr(model, "module") else model
  207. model_to_save.save_pretrained(output_dir)
  208. tokenizer.save_pretrained(output_dir)
  209. torch.save(args, os.path.join(output_dir, "training_args.bin"))
  210. logger.info("Saving model checkpoint to %s", output_dir)
  211. torch.save(optimizer.state_dict(), os.path.join(output_dir, "optimizer.pt"))
  212. torch.save(scheduler.state_dict(), os.path.join(output_dir, "scheduler.pt"))
  213. logger.info("Saving optimizer and scheduler states to %s", output_dir)
  214. if args.max_steps > 0 and global_step > args.max_steps:
  215. epoch_iterator.close()
  216. break
  217. if args.max_steps > 0 and global_step > args.max_steps:
  218. train_iterator.close()
  219. break
  220. if args.local_rank in [-1, 0]:
  221. tb_writer.close()
  222. return global_step, tr_loss / global_step
  223. def evaluate(args, model, tokenizer, prefix=""):
  224. dataset, examples, features = load_and_cache_examples(args, tokenizer, evaluate=True, output_examples=True)
  225. if not os.path.exists(args.output_dir) and args.local_rank in [-1, 0]:
  226. os.makedirs(args.output_dir)
  227. args.eval_batch_size = args.per_gpu_eval_batch_size * max(1, args.n_gpu)
  228. # Note that DistributedSampler samples randomly
  229. eval_sampler = SequentialSampler(dataset)
  230. eval_dataloader = DataLoader(dataset, sampler=eval_sampler, batch_size=args.eval_batch_size)
  231. # multi-gpu evaluate
  232. if args.n_gpu > 1 and not isinstance(model, torch.nn.DataParallel):
  233. model = torch.nn.DataParallel(model)
  234. # Eval!
  235. logger.info("***** Running evaluation {} *****".format(prefix))
  236. logger.info(" Num examples = %d", len(dataset))
  237. logger.info(" Batch size = %d", args.eval_batch_size)
  238. all_results = []
  239. start_time = timeit.default_timer()
  240. for batch in tqdm(eval_dataloader, desc="Evaluating"):
  241. model.eval()
  242. batch = tuple(t.to(args.device) for t in batch)
  243. with torch.no_grad():
  244. inputs = {
  245. "input_ids": batch[0],
  246. "attention_mask": batch[1],
  247. "token_type_ids": batch[2],
  248. }
  249. if args.model_type in ["xlm", "roberta", "distilbert", "camembert"]:
  250. del inputs["token_type_ids"]
  251. feature_indices = batch[3]
  252. # XLNet and XLM use more arguments for their predictions
  253. if args.model_type in ["xlnet", "xlm"]:
  254. inputs.update({"cls_index": batch[4], "p_mask": batch[5]})
  255. # for lang_id-sensitive xlm models
  256. if hasattr(model, "config") and hasattr(model.config, "lang2id"):
  257. inputs.update(
  258. {"langs": (torch.ones(batch[0].shape, dtype=torch.int64) * args.lang_id).to(args.device)}
  259. )
  260. outputs = model(**inputs)
  261. for i, feature_index in enumerate(feature_indices):
  262. eval_feature = features[feature_index.item()]
  263. unique_id = int(eval_feature.unique_id)
  264. output = [to_list(output[i]) for output in outputs]
  265. # Some models (XLNet, XLM) use 5 arguments for their predictions, while the other "simpler"
  266. # models only use two.
  267. if len(output) >= 5:
  268. start_logits = output[0]
  269. start_top_index = output[1]
  270. end_logits = output[2]
  271. end_top_index = output[3]
  272. cls_logits = output[4]
  273. result = SquadResult(
  274. unique_id,
  275. start_logits,
  276. end_logits,
  277. start_top_index=start_top_index,
  278. end_top_index=end_top_index,
  279. cls_logits=cls_logits,
  280. )
  281. else:
  282. start_logits, end_logits = output
  283. result = SquadResult(unique_id, start_logits, end_logits)
  284. all_results.append(result)
  285. evalTime = timeit.default_timer() - start_time
  286. logger.info(" Evaluation done in total %f secs (%f sec per example)", evalTime, evalTime / len(dataset))
  287. # Compute predictions
  288. output_prediction_file = os.path.join(args.output_dir, "predictions_{}.json".format(prefix))
  289. output_nbest_file = os.path.join(args.output_dir, "nbest_predictions_{}.json".format(prefix))
  290. if args.version_2_with_negative:
  291. output_null_log_odds_file = os.path.join(args.output_dir, "null_odds_{}.json".format(prefix))
  292. else:
  293. output_null_log_odds_file = None
  294. predictions = compute_predictions_logits(
  295. examples,
  296. features,
  297. all_results,
  298. args.n_best_size,
  299. args.max_answer_length,
  300. args.do_lower_case,
  301. output_prediction_file,
  302. output_nbest_file,
  303. output_null_log_odds_file,
  304. args.verbose_logging,
  305. args.version_2_with_negative,
  306. args.null_score_diff_threshold,
  307. tokenizer,
  308. )
  309. ## Transform the prediction into the BioASQ format
  310. logger.info("***** Transform the prediction file into the BioASQ format {} *****".format(prefix))
  311. transform_n2b_factoid(output_nbest_file, args.output_dir)
  312. ## Evaluate with the BioASQ official evaluation code
  313. pred_file = os.path.join(args.output_dir, "BioASQform_BioASQ-answer.json")
  314. eval_score = eval_bioasq_standard(str(5), pred_file, args.golden_file, args.official_eval_dir)
  315. print("** BioASQ-factoid Evaluation Results ************************************")
  316. print(f" S. Accuracy = {float(eval_score[1])*100:.2f}")
  317. print(f" L. Accuracy = {float(eval_score[2])*100:.2f}")
  318. print(f" MRR = {float(eval_score[3])*100:.2f}")
  319. def load_and_cache_examples(args, tokenizer, evaluate=False, output_examples=False):
  320. if args.local_rank not in [-1, 0] and not evaluate:
  321. # Make sure only the first process in distributed training process the dataset, and the others will use the cache
  322. torch.distributed.barrier()
  323. # Load data features from cache or dataset file
  324. input_dir = args.data_dir if args.data_dir else "."
  325. cached_features_file = os.path.join(
  326. input_dir,
  327. "cached_{}_{}_{}".format(
  328. "dev" if evaluate else "train",
  329. list(filter(None, args.model_name_or_path.split("/"))).pop(),
  330. str(args.max_seq_length),
  331. ),
  332. )
  333. # Init features and dataset from cache if it exists
  334. if os.path.exists(cached_features_file) and not args.overwrite_cache:
  335. logger.info("Loading features from cached file %s", cached_features_file)
  336. features_and_dataset = torch.load(cached_features_file)
  337. features, dataset, examples = (
  338. features_and_dataset["features"],
  339. features_and_dataset["dataset"],
  340. features_and_dataset["examples"],
  341. )
  342. else:
  343. logger.info("Creating features from dataset file at %s", input_dir)
  344. if not args.data_dir and ((evaluate and not args.predict_file) or (not evaluate and not args.train_file)):
  345. try:
  346. import tensorflow_datasets as tfds
  347. except ImportError:
  348. raise ImportError("If not data_dir is specified, tensorflow_datasets needs to be installed.")
  349. if args.version_2_with_negative:
  350. logger.warn("tensorflow_datasets does not handle version 2 of SQuAD.")
  351. tfds_examples = tfds.load("squad")
  352. examples = SquadV1Processor().get_examples_from_dataset(tfds_examples, evaluate=evaluate)
  353. else:
  354. processor = SquadV2Processor() if args.version_2_with_negative else SquadV1Processor()
  355. if evaluate:
  356. examples = processor.get_dev_examples(args.data_dir, filename=args.predict_file)
  357. else:
  358. examples = processor.get_train_examples(args.data_dir, filename=args.train_file)
  359. features, dataset = squad_convert_examples_to_features(
  360. examples=examples,
  361. tokenizer=tokenizer,
  362. max_seq_length=args.max_seq_length,
  363. doc_stride=args.doc_stride,
  364. max_query_length=args.max_query_length,
  365. is_training=not evaluate,
  366. return_dataset="pt",
  367. threads=args.threads,
  368. )
  369. if args.local_rank in [-1, 0]:
  370. logger.info("Saving features into cached file %s", cached_features_file)
  371. torch.save({"features": features, "dataset": dataset, "examples": examples}, cached_features_file)
  372. if args.local_rank == 0 and not evaluate:
  373. # Make sure only the first process in distributed training process the dataset, and the others will use the cache
  374. torch.distributed.barrier()
  375. if output_examples:
  376. return dataset, examples, features
  377. return dataset
  378. def main():
  379. parser = argparse.ArgumentParser()
  380. # Required parameters
  381. parser.add_argument(
  382. "--model_type",
  383. default=None,
  384. type=str,
  385. required=True,
  386. help="Model type selected in the list: " + ", ".join(MODEL_TYPES),
  387. )
  388. parser.add_argument(
  389. "--model_name_or_path",
  390. default=None,
  391. type=str,
  392. required=True,
  393. help="Path to pretrained model or model identifier from huggingface.co/models",
  394. )
  395. parser.add_argument(
  396. "--output_dir",
  397. default=None,
  398. type=str,
  399. required=True,
  400. help="The output directory where the model checkpoints and predictions will be written.",
  401. )
  402. parser.add_argument(
  403. "--golden_file",
  404. default=None,
  405. type=str,
  406. help="BioASQ official golden answer file"
  407. )
  408. parser.add_argument(
  409. "--official_eval_dir",
  410. default='./scripts/bioasq_eval',
  411. type=str,
  412. help="BioASQ official golden answer file"
  413. )
  414. # Other parameters
  415. parser.add_argument(
  416. "--data_dir",
  417. default=None,
  418. type=str,
  419. help="The input data dir. Should contain the .json files for the task."
  420. + "If no data dir or train/predict files are specified, will run with tensorflow_datasets.",
  421. )
  422. parser.add_argument(
  423. "--train_file",
  424. default=None,
  425. type=str,
  426. help="The input training file. If a data dir is specified, will look for the file there"
  427. + "If no data dir or train/predict files are specified, will run with tensorflow_datasets.",
  428. )
  429. parser.add_argument(
  430. "--predict_file",
  431. default=None,
  432. type=str,
  433. help="The input evaluation file. If a data dir is specified, will look for the file there"
  434. + "If no data dir or train/predict files are specified, will run with tensorflow_datasets.",
  435. )
  436. parser.add_argument(
  437. "--config_name", default="", type=str, help="Pretrained config name or path if not the same as model_name"
  438. )
  439. parser.add_argument(
  440. "--tokenizer_name",
  441. default="",
  442. type=str,
  443. help="Pretrained tokenizer name or path if not the same as model_name",
  444. )
  445. parser.add_argument(
  446. "--cache_dir",
  447. default="",
  448. type=str,
  449. help="Where do you want to store the pre-trained models downloaded from s3",
  450. )
  451. parser.add_argument(
  452. "--version_2_with_negative",
  453. action="store_true",
  454. help="If true, the SQuAD examples contain some that do not have an answer.",
  455. )
  456. parser.add_argument(
  457. "--null_score_diff_threshold",
  458. type=float,
  459. default=0.0,
  460. help="If null_score - best_non_null is greater than the threshold predict null.",
  461. )
  462. parser.add_argument(
  463. "--max_seq_length",
  464. default=384,
  465. type=int,
  466. help="The maximum total input sequence length after WordPiece tokenization. Sequences "
  467. "longer than this will be truncated, and sequences shorter than this will be padded.",
  468. )
  469. parser.add_argument(
  470. "--doc_stride",
  471. default=128,
  472. type=int,
  473. help="When splitting up a long document into chunks, how much stride to take between chunks.",
  474. )
  475. parser.add_argument(
  476. "--max_query_length",
  477. default=64,
  478. type=int,
  479. help="The maximum number of tokens for the question. Questions longer than this will "
  480. "be truncated to this length.",
  481. )
  482. parser.add_argument("--do_train", action="store_true", help="Whether to run training.")
  483. parser.add_argument("--do_eval", action="store_true", help="Whether to run eval on the dev set.")
  484. parser.add_argument(
  485. "--evaluate_during_training", action="store_true", help="Run evaluation during training at each logging step."
  486. )
  487. parser.add_argument(
  488. "--do_lower_case", action="store_true", help="Set this flag if you are using an uncased model."
  489. )
  490. parser.add_argument("--per_gpu_train_batch_size", default=8, type=int, help="Batch size per GPU/CPU for training.")
  491. parser.add_argument(
  492. "--per_gpu_eval_batch_size", default=8, type=int, help="Batch size per GPU/CPU for evaluation."
  493. )
  494. parser.add_argument("--learning_rate", default=5e-5, type=float, help="The initial learning rate for Adam.")
  495. parser.add_argument(
  496. "--gradient_accumulation_steps",
  497. type=int,
  498. default=1,
  499. help="Number of updates steps to accumulate before performing a backward/update pass.",
  500. )
  501. parser.add_argument("--weight_decay", default=0.0, type=float, help="Weight decay if we apply some.")
  502. parser.add_argument("--adam_epsilon", default=1e-8, type=float, help="Epsilon for Adam optimizer.")
  503. parser.add_argument("--max_grad_norm", default=1.0, type=float, help="Max gradient norm.")
  504. parser.add_argument(
  505. "--num_train_epochs", default=3.0, type=float, help="Total number of training epochs to perform."
  506. )
  507. parser.add_argument(
  508. "--max_steps",
  509. default=-1,
  510. type=int,
  511. help="If > 0: set total number of training steps to perform. Override num_train_epochs.",
  512. )
  513. parser.add_argument("--warmup_steps", default=0, type=int, help="Linear warmup over warmup_steps.")
  514. parser.add_argument(
  515. "--n_best_size",
  516. default=20,
  517. type=int,
  518. help="The total number of n-best predictions to generate in the nbest_predictions.json output file.",
  519. )
  520. parser.add_argument(
  521. "--max_answer_length",
  522. default=30,
  523. type=int,
  524. help="The maximum length of an answer that can be generated. This is needed because the start "
  525. "and end predictions are not conditioned on one another.",
  526. )
  527. parser.add_argument(
  528. "--verbose_logging",
  529. action="store_true",
  530. help="If true, all of the warnings related to data processing will be printed. "
  531. "A number of warnings are expected for a normal SQuAD evaluation.",
  532. )
  533. parser.add_argument(
  534. "--lang_id",
  535. default=0,
  536. type=int,
  537. help="language id of input for language-specific xlm models (see tokenization_xlm.PRETRAINED_INIT_CONFIGURATION)",
  538. )
  539. parser.add_argument("--logging_steps", type=int, default=500, help="Log every X updates steps.")
  540. parser.add_argument("--save_steps", type=int, default=500, help="Save checkpoint every X updates steps.")
  541. parser.add_argument(
  542. "--eval_all_checkpoints",
  543. action="store_true",
  544. help="Evaluate all checkpoints starting with the same prefix as model_name ending and ending with step number",
  545. )
  546. parser.add_argument("--no_cuda", action="store_true", help="Whether not to use CUDA when available")
  547. parser.add_argument(
  548. "--overwrite_output_dir", action="store_true", help="Overwrite the content of the output directory"
  549. )
  550. parser.add_argument(
  551. "--overwrite_cache", action="store_true", help="Overwrite the cached training and evaluation sets"
  552. )
  553. parser.add_argument("--seed", type=int, default=42, help="random seed for initialization")
  554. parser.add_argument("--local_rank", type=int, default=-1, help="local_rank for distributed training on gpus")
  555. parser.add_argument(
  556. "--fp16",
  557. action="store_true",
  558. help="Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit",
  559. )
  560. parser.add_argument(
  561. "--fp16_opt_level",
  562. type=str,
  563. default="O1",
  564. help="For fp16: Apex AMP optimization level selected in ['O0', 'O1', 'O2', and 'O3']."
  565. "See details at https://nvidia.github.io/apex/amp.html",
  566. )
  567. parser.add_argument("--server_ip", type=str, default="", help="Can be used for distant debugging.")
  568. parser.add_argument("--server_port", type=str, default="", help="Can be used for distant debugging.")
  569. parser.add_argument("--threads", type=int, default=1, help="multiple threads for converting example to features")
  570. args = parser.parse_args()
  571. if args.doc_stride >= args.max_seq_length - args.max_query_length:
  572. logger.warning(
  573. "WARNING - You've set a doc stride which may be superior to the document length in some "
  574. "examples. This could result in errors when building features from the examples. Please reduce the doc "
  575. "stride or increase the maximum length to ensure the features are correctly built."
  576. )
  577. if (
  578. os.path.exists(args.output_dir)
  579. and os.listdir(args.output_dir)
  580. and args.do_train
  581. and not args.overwrite_output_dir
  582. ):
  583. raise ValueError(
  584. "Output directory ({}) already exists and is not empty. Use --overwrite_output_dir to overcome.".format(
  585. args.output_dir
  586. )
  587. )
  588. # Setup distant debugging if needed
  589. if args.server_ip and args.server_port:
  590. # Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script
  591. import ptvsd
  592. print("Waiting for debugger attach")
  593. ptvsd.enable_attach(address=(args.server_ip, args.server_port), redirect_output=True)
  594. ptvsd.wait_for_attach()
  595. # Setup CUDA, GPU & distributed training
  596. if args.local_rank == -1 or args.no_cuda:
  597. device = torch.device("cuda" if torch.cuda.is_available() and not args.no_cuda else "cpu")
  598. args.n_gpu = 0 if args.no_cuda else torch.cuda.device_count()
  599. else: # Initializes the distributed backend which will take care of sychronizing nodes/GPUs
  600. torch.cuda.set_device(args.local_rank)
  601. device = torch.device("cuda", args.local_rank)
  602. torch.distributed.init_process_group(backend="nccl")
  603. args.n_gpu = 1
  604. args.device = device
  605. # Setup logging
  606. logging.basicConfig(
  607. format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
  608. datefmt="%m/%d/%Y %H:%M:%S",
  609. level=logging.INFO if args.local_rank in [-1, 0] else logging.WARN,
  610. )
  611. logger.warning(
  612. "Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s",
  613. args.local_rank,
  614. device,
  615. args.n_gpu,
  616. bool(args.local_rank != -1),
  617. args.fp16,
  618. )
  619. # Set seed
  620. set_seed(args)
  621. # Load pretrained model and tokenizer
  622. if args.local_rank not in [-1, 0]:
  623. # Make sure only the first process in distributed training will download model & vocab
  624. torch.distributed.barrier()
  625. args.model_type = args.model_type.lower()
  626. config = AutoConfig.from_pretrained(
  627. args.config_name if args.config_name else args.model_name_or_path,
  628. cache_dir=args.cache_dir if args.cache_dir else None,
  629. )
  630. tokenizer = AutoTokenizer.from_pretrained(
  631. args.tokenizer_name if args.tokenizer_name else args.model_name_or_path,
  632. do_lower_case=args.do_lower_case,
  633. cache_dir=args.cache_dir if args.cache_dir else None,
  634. )
  635. model = AutoModelForQuestionAnswering.from_pretrained(
  636. args.model_name_or_path,
  637. from_tf=bool(".ckpt" in args.model_name_or_path),
  638. config=config,
  639. cache_dir=args.cache_dir if args.cache_dir else None,
  640. )
  641. if args.local_rank == 0:
  642. # Make sure only the first process in distributed training will download model & vocab
  643. torch.distributed.barrier()
  644. model.to(args.device)
  645. logger.info("Training/evaluation parameters %s", args)
  646. # Before we do anything with models, we want to ensure that we get fp16 execution of torch.einsum if args.fp16 is set.
  647. # Otherwise it'll default to "promote" mode, and we'll get fp32 operations. Note that running `--fp16_opt_level="O2"` will
  648. # remove the need for this code, but it is still valid.
  649. if args.fp16:
  650. try:
  651. import apex
  652. apex.amp.register_half_function(torch, "einsum")
  653. except ImportError:
  654. raise ImportError("Please install apex from https://www.github.com/nvidia/apex to use fp16 training.")
  655. # Training
  656. if args.do_train:
  657. train_dataset = load_and_cache_examples(args, tokenizer, evaluate=False, output_examples=False)
  658. global_step, tr_loss = train(args, train_dataset, model, tokenizer)
  659. logger.info(" global_step = %s, average loss = %s", global_step, tr_loss)
  660. # Save the trained model and the tokenizer
  661. if args.do_train and (args.local_rank == -1 or torch.distributed.get_rank() == 0):
  662. logger.info("Saving model checkpoint to %s", args.output_dir)
  663. # Save a trained model, configuration and tokenizer using `save_pretrained()`.
  664. # They can then be reloaded using `from_pretrained()`
  665. # Take care of distributed/parallel training
  666. model_to_save = model.module if hasattr(model, "module") else model
  667. model_to_save.save_pretrained(args.output_dir)
  668. tokenizer.save_pretrained(args.output_dir)
  669. # Good practice: save your training arguments together with the trained model
  670. torch.save(args, os.path.join(args.output_dir, "training_args.bin"))
  671. # Load a trained model and vocabulary that you have fine-tuned
  672. model = AutoModelForQuestionAnswering.from_pretrained(args.output_dir) # , force_download=True)
  673. tokenizer = AutoTokenizer.from_pretrained(args.output_dir, do_lower_case=args.do_lower_case)
  674. model.to(args.device)
  675. # Evaluation - we can ask to evaluate all the checkpoints (sub-directories) in a directory
  676. results = {}
  677. if args.do_eval and args.local_rank in [-1, 0]:
  678. if args.do_train:
  679. logger.info("Loading checkpoints saved during training for evaluation")
  680. checkpoints = [args.output_dir]
  681. if args.eval_all_checkpoints:
  682. checkpoints = list(
  683. os.path.dirname(c)
  684. for c in sorted(glob.glob(args.output_dir + "/**/" + WEIGHTS_NAME, recursive=True))
  685. )
  686. logging.getLogger("transformers.modeling_utils").setLevel(logging.WARN) # Reduce model loading logs
  687. else:
  688. logger.info("Loading checkpoint %s for evaluation", args.model_name_or_path)
  689. checkpoints = [args.model_name_or_path]
  690. logger.info("Evaluate the following checkpoints: %s", checkpoints)
  691. for checkpoint in checkpoints:
  692. # Reload the model
  693. global_step = checkpoint.split("-")[-1] if len(checkpoints) > 1 else ""
  694. model = AutoModelForQuestionAnswering.from_pretrained(checkpoint) # , force_download=True)
  695. model.to(args.device)
  696. # Evaluate
  697. evaluate(args, model, tokenizer, prefix=global_step)
  698. if __name__ == "__main__":
  699. main()
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...