-
Notifications
You must be signed in to change notification settings - Fork 1
/
run_squad.py
1731 lines (1567 loc) · 71.4 KB
/
run_squad.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
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
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# coding=utf-8
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
""" Finetuning the library models for question-answering on SQuAD (DistilBERT, Bert, XLM, XLNet)."""
import sys
import argparse
import glob
import logging
import os
import random
import timeit
import json
import copy
import math
import pickle
from collections import Counter
import numpy as np
import torch
import torch.nn.functional as F
from torch.nn import CrossEntropyLoss
from torch.nn.utils.rnn import pad_sequence
from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, WeightedRandomSampler
from torch.utils.data import Subset, ConcatDataset, Dataset
from torch.utils.data.distributed import DistributedSampler
from tqdm import tqdm, trange
from pathlib import Path
import spacy
from pytorch_memlab import profile
from transformers import (
BertConfig,
BertForQuestionAnswering,
BertTokenizer,
RobertaConfig,
RobertaForQuestionAnswering,
RobertaTokenizer,
WEIGHTS_NAME,
AdamW,
AutoConfig,
AutoModelForQuestionAnswering,
AutoTokenizer,
get_linear_schedule_with_warmup,
squad_convert_examples_to_features,
)
from transformers.data.metrics.squad_metrics import (
compute_predictions_log_probs,
compute_predictions_logits,
squad_evaluate,
)
from transformers.data.processors.squad import SquadExample, SquadFeatures
from squad import SquadResult, SquadV1Processor, SquadV2Processor
from utils import Statistics, load_json, save_json
from utils_qa import get_bool_of_biased_dataset
import warnings
warnings.simplefilter('ignore')
import wandb
logger = logging.getLogger(__name__)
MODEL_CLASSES = {
'bert': (BertConfig, BertForQuestionAnswering, BertTokenizer),
'roberta': (RobertaConfig, RobertaForQuestionAnswering, RobertaTokenizer),
}
from transformers import __version__
MODEL_TYPES = list(MODEL_CLASSES.keys())
def set_seed(args):
random.seed(args.seed)
np.random.seed(args.seed)
torch.manual_seed(args.seed)
if args.n_gpu > 0:
torch.cuda.manual_seed_all(args.seed)
def to_list(tensor):
return tensor.detach().cpu().tolist()
def train(args, train_dataset, train_dataloader, model, tokenizer, wandb, optimizer, scheduler, t_total, max_steps=0, num_epochs=0, global_step=0, logging_steps=-1):
""" Train the model """
# Check if saved optimizer or scheduler states exist
if os.path.isfile(os.path.join(args.model_name_or_path, "optimizer.pt")) and os.path.isfile(
os.path.join(args.model_name_or_path, "scheduler.pt")
):
# Load in optimizer and scheduler states
optimizer.load_state_dict(torch.load(os.path.join(args.model_name_or_path, "optimizer.pt")))
scheduler.load_state_dict(torch.load(os.path.join(args.model_name_or_path, "scheduler.pt")))
if args.fp16:
try:
from apex import amp
except ImportError:
raise ImportError("Please install apex from https://www.github.com/nvidia/apex to use fp16 training.")
model, optimizer = amp.initialize(model, optimizer, opt_level=args.fp16_opt_level)
# multi-gpu training (should be after apex fp16 initialization)
if args.n_gpu > 1:
model = torch.nn.DataParallel(model)
# Distributed training (should be after apex fp16 initialization)
if args.local_rank != -1:
model = torch.nn.parallel.DistributedDataParallel(
model, device_ids=[args.local_rank], output_device=args.local_rank, find_unused_parameters=True
)
# Train!
logger.info("***** Running training *****")
logger.info(" Num examples = %d", len(train_dataset))
logger.info(" Num Epochs = %d", num_epochs)
logger.info(" Instantaneous batch size per GPU = %d", args.per_gpu_train_batch_size)
logger.info(
" Total train batch size (w. parallel, distributed & accumulation) = %d",
args.train_batch_size
* args.gradient_accumulation_steps
* (torch.distributed.get_world_size() if args.local_rank != -1 else 1),
)
logger.info(" Gradient Accumulation steps = %d", args.gradient_accumulation_steps)
logger.info(" Total optimization steps = %d", t_total)
epochs_trained = 0
steps_trained_in_current_epoch = 0
# Check if continuing training from a checkpoint
if os.path.exists(args.model_name_or_path):
try:
# set global_step to gobal_step of last saved checkpoint from model path
checkpoint_suffix = args.model_name_or_path.split("-")[-1].split("/")[0]
global_step = int(checkpoint_suffix)
epochs_trained = global_step // (len(train_dataloader) // args.gradient_accumulation_steps)
steps_trained_in_current_epoch = global_step % (len(train_dataloader) // args.gradient_accumulation_steps)
logger.info(" Continuing training from checkpoint, will skip to saved global_step")
logger.info(" Continuing training from epoch %d", epochs_trained)
logger.info(" Continuing training from global step %d", global_step)
logger.info(" Will skip the first %d steps in the first epoch", steps_trained_in_current_epoch)
except ValueError:
logger.info(" Starting fine-tuning.")
model.zero_grad()
train_iterator = trange(
epochs_trained, int(num_epochs), desc="Epoch", disable=args.local_rank not in [-1, 0]
)
# Added here for reproductibility
set_seed(args)
if args.local_rank == -1 and args.evaluate_during_training and args.log_before_train:
results = evaluate(args, model, tokenizer, prefix=global_step)
metrics = {}
for key, value in results.items():
metrics[f"eval/{key}"] = value
wandb.log(metrics, step=global_step)
for _ in train_iterator:
epoch_iterator = tqdm(train_dataloader, desc="Iteration", disable=args.local_rank not in [-1, 0])
for step, batch in enumerate(epoch_iterator):
# Skip past any already trained steps if resuming training
if steps_trained_in_current_epoch > 0:
steps_trained_in_current_epoch -= 1
continue
model.train()
batch = tuple(t.to(args.device) for t in batch)
inputs = {
"input_ids": batch[0],
"attention_mask": batch[1],
"token_type_ids": batch[2],
"start_positions": batch[3],
"end_positions": batch[4],
}
if args.model_type.split('_')[0] in ["xlm", "roberta", "distilbert", "camembert"]:
del inputs["token_type_ids"]
if args.model_type.split('_')[0] in ["xlnet", "xlm"]:
inputs.update({"cls_index": batch[5], "p_mask": batch[6]})
if args.version_2_with_negative:
inputs.update({"is_impossible": batch[7]})
if hasattr(model, "config") and hasattr(model.config, "lang2id"):
inputs.update(
{"langs": (torch.ones(batch[0].shape, dtype=torch.int64) * args.lang_id).to(args.device)}
)
outputs = model(**inputs, return_dict=True)
# model outputs are always tuple in transformers (see doc)
loss = outputs.loss
if args.n_gpu > 1:
loss = loss.mean() # mean() to average on multi-gpu parallel (not distributed) training
if args.gradient_accumulation_steps > 1:
loss = loss / args.gradient_accumulation_steps
if args.fp16:
with amp.scale_loss(loss, optimizer) as scaled_loss:
scaled_loss.backward()
else:
loss.backward()
if (step + 1) % args.gradient_accumulation_steps == 0:
if args.fp16:
torch.nn.utils.clip_grad_norm_(amp.master_params(optimizer), args.max_grad_norm)
else:
torch.nn.utils.clip_grad_norm_(model.parameters(), args.max_grad_norm)
optimizer.step()
scheduler.step() # Update learning rate schedule
model.zero_grad()
global_step += 1
# Log metrics
if args.local_rank in [-1, 0]:
metrics = {}
metrics["train/lr"] = scheduler.get_lr()[0]
metrics["train/loss"] = loss
if logging_steps > 0 and args.evaluate_during_training and global_step % logging_steps == 0:
results = evaluate(args, model, tokenizer, prefix=global_step)
for key, value in results.items():
metrics[f"eval/{key}"] = value
wandb.log(metrics, step=global_step)
# Save model checkpoint
if args.local_rank in [-1, 0] and args.save_steps > 0 and global_step % args.save_steps == 0:
output_dir = os.path.join(args.output_dir, "checkpoint-{}".format(global_step))
if not os.path.exists(output_dir):
os.makedirs(output_dir)
# Take care of distributed/parallel training
model_to_save = model.module if hasattr(model, "module") else model
model_to_save.save_pretrained(output_dir)
tokenizer.save_pretrained(output_dir)
torch.save(args, os.path.join(output_dir, "training_args.bin"))
logger.info("Saving model checkpoint to %s", output_dir)
torch.save(optimizer.state_dict(), os.path.join(output_dir, "optimizer.pt"))
torch.save(scheduler.state_dict(), os.path.join(output_dir, "scheduler.pt"))
logger.info("Saving optimizer and scheduler states to %s", output_dir)
if max_steps > 0 and global_step > max_steps:
epoch_iterator.close()
break
if max_steps > 0 and global_step > max_steps:
train_iterator.close()
break
return global_step, loss
def evaluate(args, model, tokenizer, prefix=""):
dataset, examples, features = load_and_cache_examples(args, tokenizer, 'dev', args.predict_file, output_examples=True)
if not os.path.exists(args.output_dir) and args.local_rank in [-1, 0]:
os.makedirs(args.output_dir)
args.eval_batch_size = args.per_gpu_eval_batch_size * max(1, args.n_gpu)
# Note that DistributedSampler samples randomly
eval_sampler = SequentialSampler(dataset)
eval_dataloader = DataLoader(dataset, sampler=eval_sampler, batch_size=args.eval_batch_size)
# multi-gpu evaluate
if args.n_gpu > 1 and not isinstance(model, torch.nn.DataParallel):
model = torch.nn.DataParallel(model)
# Eval!
logger.info("***** Running evaluation {} *****".format(prefix))
logger.info(" Num examples = %d", len(dataset))
logger.info(" Batch size = %d", args.eval_batch_size)
all_results = []
start_time = timeit.default_timer()
for batch in tqdm(eval_dataloader, desc="Evaluating"):
model.eval()
with torch.no_grad():
batch = tuple(t.to(args.device) for t in batch)
if args.model_type == 'bert_bias_rel_pos':
inputs = convert_batch_to_relative_position_inputs(args, tokenizer, batch)
else:
inputs = {
"input_ids": batch[0],
"attention_mask": batch[1],
"token_type_ids": batch[2],
}
if args.model_type.split('_')[0] in ["xlm", "roberta", "distilbert", "camembert"]:
del inputs["token_type_ids"]
feature_indices = batch[3]
# XLNet and XLM use more arguments for their predictions
if args.model_type.split('_')[0] in ["xlnet", "xlm"]:
inputs.update({"cls_index": batch[4], "p_mask": batch[5]})
# for lang_id-sensitive xlm models
if hasattr(model, "config") and hasattr(model.config, "lang2id"):
inputs.update(
{"langs": (torch.ones(batch[0].shape, dtype=torch.int64) * args.lang_id).to(args.device)}
)
outputs = model(**inputs, return_dict=True)
for i, feature_index in enumerate(feature_indices):
# TODO: i and feature_index are the same number! Simplify by removing enumerate?
eval_feature = features[feature_index.item()]
unique_id = int(eval_feature.unique_id)
# Some models (XLNet, XLM) use 5 arguments for their predictions, while the other "simpler"
# models only use two.
if args.model_type.split('_')[0] in ["xlnet", "xlm"] and args.model_type is not 'xlnet_simple':
start_logits = outputs.start_top_log_probs[i]
start_top_index = outputs.start_top_index[i]
end_logits = outputs.end_top_log_probs[i]
end_top_index = outputs.end_top_index[i]
cls_logits = outputs.cls_logits[i]
result = SquadResult(
unique_id,
start_logits,
end_logits,
start_top_index=start_top_index,
end_top_index=end_top_index,
cls_logits=cls_logits,
)
else:
start_logits = to_list(outputs.start_logits[i])
end_logits = to_list(outputs.end_logits[i])
result = SquadResult(unique_id, start_logits, end_logits)
all_results.append(result)
evalTime = timeit.default_timer() - start_time
logger.info(" Evaluation done in total %f secs (%f sec per example)", evalTime, evalTime / len(dataset))
# Compute predictions
pred_file_id = Path(args.predict_file).stem
output_prediction_file = os.path.join(args.output_dir, f"predictions_{pred_file_id}_{prefix}.json")
output_nbest_file = os.path.join(args.output_dir, f"nbest_predictions_{pred_file_id}_{prefix}.json")
if args.version_2_with_negative:
output_null_log_odds_file = os.path.join(args.output_dir, f"null_odds_{pred_file_id}_{prefix}.json")
else:
output_null_log_odds_file = None
# XLNet and XLM use a more complex post-processing procedure
if args.model_type.split('_')[0] in ["xlnet", "xlm"] and args.model_type is not 'xlnet_simple':
start_n_top = model.config.start_n_top if hasattr(model, "config") else model.module.config.start_n_top
end_n_top = model.config.end_n_top if hasattr(model, "config") else model.module.config.end_n_top
predictions = compute_predictions_log_probs(
examples,
features,
all_results,
args.n_best_size,
args.max_answer_length,
output_prediction_file,
output_nbest_file,
output_null_log_odds_file,
start_n_top,
end_n_top,
args.version_2_with_negative,
tokenizer,
args.verbose_logging,
)
else:
predictions = compute_predictions_logits(
examples,
features,
all_results,
args.n_best_size,
args.max_answer_length,
args.do_lower_case,
output_prediction_file,
output_nbest_file,
output_null_log_odds_file,
args.verbose_logging,
args.version_2_with_negative,
args.null_score_diff_threshold,
tokenizer,
)
# Compute the F1 and exact scores.
results = squad_evaluate(examples, predictions)
return results
def load_and_cache_examples(args, tokenizer, mode, file, output_examples=False):
if args.local_rank not in [-1, 0] and not mode in ['dev', 'test']:
# Make sure only the first process in distributed training process the dataset, and the others will use the cache
torch.distributed.barrier()
# Load data features from cache or dataset file
input_dir = args.data_dir if args.data_dir else os.path.dirname(file)
cached_features_file = os.path.join(
input_dir,
"cached_{}_{}_{}".format(
os.path.splitext(os.path.basename(file))[0],
list(filter(None, args.model_name_or_path.split("/"))).pop(),
str(args.max_seq_length),
),
)
# Init features and dataset from cache if it exists
if os.path.exists(cached_features_file) and not args.overwrite_cache:
logger.info("Loading features from cached file %s", cached_features_file)
features_and_dataset = torch.load(cached_features_file)
features, dataset, examples = (
features_and_dataset["features"],
features_and_dataset["dataset"],
features_and_dataset["examples"],
)
else:
logger.info("Creating features from dataset file at %s", input_dir)
#if (not args.data_dir and\
# ((mode in ['dev', 'test'] and not args.predict_file) or\
# (mode in ['train'] and not args.train_file) or\
# (mode in ['pretrain'] and not args.pretrain_file))):
if False:
# We do not want to use the original split of squad.
assert False
try:
import tensorflow_datasets as tfds
except ImportError:
raise ImportError("If not data_dir is specified, tensorflow_datasets needs to be installed.")
if args.version_2_with_negative:
logger.warn("tensorflow_datasets does not handle version 2 of SQuAD.")
tfds_examples = tfds.load("squad")
examples = SquadV1Processor().get_examples_from_dataset(tfds_examples, evaluate=mode in ['dev', 'test'])
else:
processor = SquadV2Processor() if args.version_2_with_negative else SquadV1Processor()
if mode in ['dev', 'test']:
examples = processor.get_dev_examples(args.data_dir, filename=file, do_lower_case='triviaqa' in input_dir)
elif mode == 'train':
examples = processor.get_train_examples(args.data_dir, filename=file, do_lower_case='triviaqa' in input_dir)
elif mode == 'pretrain':
examples = processor.get_train_examples(args.data_dir, filename=file, do_lower_case='triviaqa' in input_dir)
# do_lower_case here for processing triviaqa
features, dataset = squad_convert_examples_to_features(
examples=examples,
tokenizer=tokenizer,
max_seq_length=args.max_seq_length,
doc_stride=args.doc_stride,
max_query_length=args.max_query_length,
is_training=mode in ['train', 'pretrain'],
return_dataset="pt",
threads=args.threads,
)
if args.local_rank in [-1, 0]:
logger.info("Saving features into cached file %s", cached_features_file)
torch.save({"features": features, "dataset": dataset, "examples": examples}, cached_features_file)
if args.local_rank == 0 and mode in ['train', 'pretrain']:
# Make sure only the first process in distributed training process the dataset, and the others will use the cache
torch.distributed.barrier()
if output_examples:
return dataset, examples, features
return dataset
def prepare_optimizer_and_schedule(args, model, t_total):
# Prepare optimizer and schedule (linear warmup and decay)
no_decay = ["bias", "LayerNorm.weight"]
optimizer_grouped_parameters = [
{
"params": [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay)],
"weight_decay": args.weight_decay,
},
{"params": [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay)], "weight_decay": 0.0},
]
optimizer = AdamW(optimizer_grouped_parameters, lr=args.learning_rate, eps=args.adam_epsilon)
if args.warmup_ratio > 0:
args.warmup_steps = int(t_total * args.warmup_ratio)
scheduler = get_linear_schedule_with_warmup(
optimizer, num_warmup_steps=args.warmup_steps, num_training_steps=t_total
)
return optimizer, scheduler
def mdl_probe(args, model, tokenizer, prefix=""):
"""
model: transformer (bert, roberta, ...)
"""
for task_name in args.probe_tasks:
reporting_root = os.path.join(args.output_dir, 'probing_'+task_name+'_L' + str(args.probe_layer) + '_'+str(prefix))
if not os.path.exists(reporting_root):
os.makedirs(reporting_root)
args.reporting_root = reporting_root
dataset_class = choose_dataset_class(args.model_type.split('_')[0])
task_class, reporter_class, loss_class = choose_task_classes(task_name)
probe_class = choose_probe_class(args, task_name)
regimen_class = regimen.ProbeRegimen
task = task_class(args)
expt_dataset = dataset_class(args, task, model, tokenizer)
expt_reporter = reporter_class(args, expt_dataset, task_name)
expt_probe = probe_class(args)
expt_regimen = regimen_class(args, reporter=expt_reporter, task_name=task_name)
expt_loss = loss_class(args)
online_coding_list = []
dev_report_list = []
test_report_list = []
dev_dataloader = expt_dataset.get_dev_dataloader()
test_dataloader = expt_dataset.get_test_dataloader()
shuffled_dataset = torch.utils.data.Subset(
expt_dataset.train_dataset, indices=np.random.permutation(len(expt_dataset.train_dataset)))
train_portions, eval_portions = split_data_into_portions(shuffled_dataset)
for i in range(len(train_portions) - 1):
expt_probe = probe_class(args)
current_train = DataLoader(train_portions[i],
batch_size=expt_dataset.batch_size,
collate_fn=expt_dataset.custom_pad, shuffle=False)
current_dev = DataLoader(eval_portions[i],
batch_size=expt_dataset.batch_size,
collate_fn=expt_dataset.custom_pad, shuffle=False)
# run-train-probe
reports, evals = expt_regimen.train_until_convergence(expt_probe, expt_loss,
current_train,
dev_dataloader,
eval_datasets = {'dev': dev_dataloader,
'test': test_dataloader,
'online_portion': current_dev})
online_coding_list.append(evals)
expt_probe.load_state_dict(torch.load(expt_regimen.params_path))
expt_probe.eval()
# eval on portion, dev/test
dev_predictions = expt_regimen.predict(expt_probe, dev_dataloader)
dev_report = expt_reporter(dev_predictions, dev_dataloader, 'dev', probe=expt_probe)
dev_report_list.append(dev_report)
test_predictions = expt_regimen.predict(expt_probe, test_dataloader)
test_report = expt_reporter(test_predictions, test_dataloader, 'test', probe=expt_probe)
print('\n\nTest Report: ', test_report, len(test_dataloader), '\n\n')
test_report_list.append(test_report)
expt_probe = probe_class(args)
# train on the last portion
current_train = DataLoader(train_portions[-1],
batch_size=expt_dataset.batch_size,
collate_fn=expt_dataset.custom_pad, shuffle=False)
# run-train-probe
reports, evals = expt_regimen.train_until_convergence(expt_probe, expt_loss,
current_train,
dev_dataloader,
eval_datasets = {'dev': dev_dataloader,
'test': test_dataloader,
'train': current_train,})
online_coding_list.append(evals)
# load best model from current iteration
expt_probe.load_state_dict(torch.load(expt_regimen.params_path))
expt_probe.eval()
# eval on portion
dev_predictions = expt_regimen.predict(expt_probe, dev_dataloader)
dev_report = expt_reporter(dev_predictions, dev_dataloader, 'dev', probe=expt_probe)
dev_report_list.append(dev_report)
test_predictions = expt_regimen.predict(expt_probe, test_dataloader)
test_report = expt_reporter(test_predictions, test_dataloader, 'test', probe=expt_probe)
print('\n\nTest Report: ', test_report, len(test_dataloader), '\n\n')
test_report_list.append(test_report)
with open(os.path.join(args.reporting_root, 'online_coding.pkl'), 'wb') as f:
pickle.dump(online_coding_list, f)
with open(os.path.join(args.reporting_root, 'online_dev_report.json'), 'w') as f:
json.dump(dev_report_list, f, indent=4)
with open(os.path.join(args.reporting_root, 'online_test_report.json'), 'w') as f:
json.dump(test_report_list, f, indent=4)
return test_report_list[-1]
def evaluate_loss(args, dataloader, model):
all_loss = 0
num_examples = 0
for batch in tqdm(dataloader, desc="Evaluating"):
model.eval()
with torch.no_grad():
batch = tuple(t.to(args.device) for t in batch)
inputs = {
"input_ids": batch[0],
"attention_mask": batch[1],
"token_type_ids": batch[2],
"start_positions": batch[3],
"end_positions": batch[4],
}
if args.model_type.split('_')[0] in ["xlm", "roberta", "distilbert", "camembert"]:
del inputs["token_type_ids"]
outputs = model(**inputs)
loss = outputs.loss
batch_size = batch[0].size(0)
all_loss += loss.item() * batch_size
num_examples += batch_size
return all_loss / num_examples
def main():
parser = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"--model_type",
default=None,
type=str,
required=True,
help="Model type selected in the list: " + ", ".join(MODEL_TYPES),
)
parser.add_argument(
"--model_name_or_path",
default=None,
type=str,
required=True,
help="Path to pretrained model or model identifier from huggingface.co/models",
)
parser.add_argument(
"--output_dir",
default=None,
type=str,
required=True,
help="The output directory where the model checkpoints and predictions will be written.",
)
parser.add_argument(
"--output_dir_base",
default="/data/shinoda/git/QuestionGeneration/output/",
type=str,
help="The output directory base where the model checkpoints and predictions will be written.",
)
# Other parameters
parser.add_argument(
"--data_dir",
default=None,
type=str,
help="The input data dir. Should contain the .json files for the task."
+ "If no data dir or train/predict files are specified, will run with tensorflow_datasets.",
)
parser.add_argument(
"--train_file",
default="/data/shinoda/dataset/qa/squad/train-v1.1.json",
type=str,
help="The input training file. If a data dir is specified, will look for the file there"
+ "If no data dir or train/predict files are specified, will run with tensorflow_datasets.",
)
parser.add_argument(
"--train_file_synonym",
default="input/squad-du-split/train.tokenized-v1.0.synonym.json",
type=str,
help="The input training file.",
)
parser.add_argument(
"--train_file_backed",
default="input/squad-du-split/train.tokenized-v1.0.backed.json",
type=str,
help="The input training file.",
)
parser.add_argument(
"--mix_train_file",
default="",
type=str,
help="Mix train file used when do_mix_train",
)
parser.add_argument(
"--pretrain_files",
default=[],
nargs='*',
type=str
)
parser.add_argument(
"--predict_file",
default="/data/shinoda/dataset/qa/squad/dev-v1.1.json",
type=str,
help="The input evaluation file. If a data dir is specified, will look for the file there"
+ "If no data dir or train/predict files are specified, will run with tensorflow_datasets.",
)
parser.add_argument(
"--preprocess_file",
default=None,
type=str,
help="The input file you want to preprocess.",
)
parser.add_argument(
"--config_name", default="", type=str, help="Pretrained config name or path if not the same as model_name"
)
parser.add_argument(
"--tokenizer_name",
default="",
type=str,
help="Pretrained tokenizer name or path if not the same as model_name",
)
parser.add_argument(
"--cache_dir",
default="",
type=str,
help="Where do you want to store the pre-trained models downloaded from s3",
)
parser.add_argument(
"--version_2_with_negative",
action="store_true",
help="If true, the SQuAD examples contain some that do not have an answer.",
)
parser.add_argument(
"--null_score_diff_threshold",
type=float,
default=0.0,
help="If null_score - best_non_null is greater than the threshold predict null.",
)
parser.add_argument(
"--max_seq_length",
default=384,
type=int,
help="The maximum total input sequence length after WordPiece tokenization. Sequences "
"longer than this will be truncated, and sequences shorter than this will be padded.",
)
parser.add_argument(
"--doc_stride",
default=128,
type=int,
help="When splitting up a long document into chunks, how much stride to take between chunks.",
)
parser.add_argument(
"--max_query_length",
default=64,
type=int,
help="The maximum number of tokens for the question. Questions longer than this will "
"be truncated to this length.",
)
parser.add_argument("--do_train", action="store_true", help="Whether to run training.")
parser.add_argument("--do_eval", action="store_true", help="Whether to run eval on the dev set.")
parser.add_argument("--do_only_preprocess", action="store_true", help="Only preprocessing")
parser.add_argument(
"--evaluate_during_training", action="store_true", help="Run evaluation during training at each logging step."
)
parser.add_argument(
"--do_lower_case", action="store_true", help="Set this flag if you are using an uncased model."
)
parser.add_argument(
"--do_online_code", action="store_true", help="Do online code analysis"
)
parser.add_argument(
"--do_biased_train", action="store_true", help="Do biased train"
)
parser.add_argument(
"--bias_1",
default=None,
type=str,
help="Specify bias type for biased training"
)
parser.add_argument(
"--bias_1_larger_than",
type=float,
default=None,
help="examples where biases are greater than or equal to the threshold are used to train a model",
)
parser.add_argument(
"--bias_1_smaller_than",
type=float,
default=None,
help="examples where biases are smaller than or equal to the threshold are used to train a model",
)
parser.add_argument(
"--bias_1_included_in",
default=None,
nargs='*',
type=str,
help="examples where biases are included in this list are used to train a model"
)
parser.add_argument(
"--bias_1_custom_func",
default=None,
type=str,
help="examples where the output of this func given a bias is true are used to train a model"
)
parser.add_argument(
"--bias_1_same_as",
default=None,
type=str,
help="examples where biases are same as other biases"
)
parser.add_argument(
"--bias_1_not_equal",
default=None,
type=str,
help="examples where biases are not equal to other biases"
)
parser.add_argument(
"--bias_1_top_k",
type=int,
default=None,
help="examples where biases are top k",
)
parser.add_argument(
"--bias_2",
default=None,
type=str,
help="Specify bias type for biased training"
)
parser.add_argument(
"--bias_2_larger_than",
type=float,
default=None,
help="examples where biases are greater than the threshold are used to train a model",
)
parser.add_argument(
"--bias_2_smaller_than",
type=float,
default=None,
help="examples where biases are smaller than the threshold are used to train a model",
)
parser.add_argument(
"--bias_2_included_in",
default=None,
nargs='*',
type=str,
help="examples where biases are included in this list are used to train a model"
)
parser.add_argument(
"--bias_2_custom_func",
default=None,
type=str,
help="examples where the output of this func given a bias is true are used to train a model"
)
parser.add_argument(
"--bias_2_same_as",
default=None,
type=str,
help="examples where biases are same as other biases"
)
parser.add_argument(
"--bias_2_not_equal",
default=None,
type=str,
help="examples where biases are not equal to other biases"
)
parser.add_argument(
"--bias_2_top_k",
type=int,
default=None,
help="examples where biases are top k",
)
parser.add_argument(
"--bias_3",
default=None,
type=str,
help="Specify bias type for biased training"
)
parser.add_argument(
"--bias_3_larger_than",
type=float,
default=None,
help="examples where biases are greater than the threshold are used to train a model",
)
parser.add_argument(
"--bias_3_smaller_than",
type=float,
default=None,
help="examples where biases are smaller than the threshold are used to train a model",
)
parser.add_argument(
"--bias_3_included_in",
default=None,
nargs='*',
type=str,
help="examples where biases are included in this list are used to train a model"
)
parser.add_argument(
"--bias_3_custom_func",
default=None,
type=str,
help="examples where the output of this func given a bias is true are used to train a model"
)
parser.add_argument(
"--bias_3_same_as",
default=None,
type=str,
help="examples where biases are same as other biases"
)
parser.add_argument(
"--bias_3_not_equal",
default=None,
type=str,
help="examples where biases are not equal to other biases"
)
parser.add_argument(
"--bias_3_top_k",
type=int,
default=None,
help="examples where biases are top k",
)
parser.add_argument(
"--do_fewshot_train", action="store_true", help=""
)
parser.add_argument(
"--do_fewshot_unique_features", action="store_true", help=""
)
parser.add_argument(
"--num_fewshot_examples",
type=int,
default=1024,
help="",
)
parser.add_argument(
"--num_total_examples",
type=int,
default=5000,
help="",
)
parser.add_argument(
"--do_blend_anti_biased", action="store_true", help=""
)
parser.add_argument(
"--anti_biased_ratio",
type=float,
default=0.0,
help="",
)
parser.add_argument(
"--anti_bias_1",
default=None,
type=str,
help="Specify bias type for anti_biased training"
)
parser.add_argument(
"--anti_bias_1_larger_than",
type=float,
default=None,
help="examples where anti_biases are greater than or equal to the threshold are used to train a model",
)
parser.add_argument(
"--anti_bias_1_smaller_than",
type=float,
default=None,
help="examples where anti_biases are smaller than or equal to the threshold are used to train a model",
)
parser.add_argument(
"--anti_bias_1_included_in",
default=None,
nargs='*',
type=str,
help="examples where anti_biases are included in this list are used to train a model"
)
parser.add_argument(
"--anti_bias_1_custom_func",
default=None,
type=str,
help="examples where the output of this func given a anti_bias is true are used to train a model"
)
parser.add_argument(
"--anti_bias_1_same_as",
default=None,
type=str,
help="examples where anti_biases are same as other anti_biases"
)
parser.add_argument(
"--anti_bias_1_not_equal",
default=None,
type=str,
help="examples where anti_biases are not equal to other anti_biases"
)
parser.add_argument(
"--anti_bias_1_top_k",
type=int,
default=None,
help="examples where biases are top k",
)
parser.add_argument(
"--anti_bias_2",