-
Notifications
You must be signed in to change notification settings - Fork 20
/
generate_training_data.py
1519 lines (1291 loc) · 58.9 KB
/
generate_training_data.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
from logging import error
from datasets import load_dataset
import transformers
from random import sample
import random
import torch
import json
from tqdm import tqdm
from nltk.translate.bleu_score import sentence_bleu
import pandas as pd
import re
'''
data format
{text_a, text_b, label:None or 0_1, }
'''
DATASET_HUGGINGFACE = {
'cnndm': ['cnn_dailymail', '3.0.0', 'train'],
'mnli': ['multi_nli', 'default', 'train'],
'squad': ['squad', 'plain_text', 'train'],
'squad_v2': ['squad_v2', 'squad_v2', 'train'],
'paws': ['paws', 'labeled_final', 'train'],
'vitaminc': ['tals/vitaminc', 'v1.0', 'train'],
'xsum': ['xsum', 'default', 'train'],
'stsb': ['glue', 'stsb', 'train'],
'sick': ['sick', 'default', 'train'],
'race': ['race', 'all', 'train'],
'race_val': ['race', 'all', 'validation'],
'anli_r1': ['anli', 'plain_text', 'train_r1'],
'anli_r2': ['anli', 'plain_text', 'train_r2'],
'anli_r3': ['anli', 'plain_text', 'train_r3'],
'snli': ['snli', 'plain_text', 'train'],
'wikihow': ['wikihow', 'all', 'train'],
'mrpc': ['glue', 'mrpc', 'train'],
'msmarco': ['ms_marco', 'v2.1', 'train'],
'mrpc_val': ['glue', 'mrpc', 'validation'],
'paws_val': ['paws', 'labeled_final', 'validation'],
'paws_unlabeled': ['paws', 'unlabeled_final', 'train'],
'qqp': ['glue', 'qqp', 'train'],
'qqp_val': ['glue', 'qqp', 'validation'],
'squad_v2_new': ['squad_v2', 'squad_v2', 'train'],
'adversarial_qa': ['adversarial_qa', 'adversarialQA', 'train'],
'drop': ['drop', 'train'],
'duorc_self': ['duorc', 'SelfRC', 'train'],
'duorc_paraphrase': ['duorc', 'ParaphraseRC', 'train'],
'quoref': ['quoref', 'train'],
'hotpot_qa_distractor': ['hotpot_qa', 'distractor', 'train'],
'hotpot_qa_fullwiki': ['hotpot_qa', 'fullwiki', 'train'],
'ropes': ['ropes', 'train'],
'boolq': ['boolq', 'train'],
'eraser_multi_rc': ['eraser_multi_rc', 'train'],
'quail': ['quail', 'train'],
'sciq': ['sciq', 'train'],
'strategy_qa': ['metaeval/strategy-qa', 'train'],
'gap': ['gap', 'train'],
}
DATASET_CONFIG = {
'cnndm': {'task': 'summarization', 'text_a': 'article', 'text_b': 'highlights', 'label': None, 'huggingface': True},
'mnli': {'task': 'nli', 'text_a': 'premise', 'text_b': 'hypothesis', 'label': 'label', 'huggingface': True},
'nli_fever': {'task': 'fact_checking', 'text_a': 'context', 'text_b': 'query', 'label': 'label','huggingface': False, 'using_hf_api': False, 'using_pandas': False, 'using_json':True, 'data_path':'data/nli_fever/train_fitems.jsonl' },
'doc_nli': {'task': 'bin_nli', 'text_a': 'premise', 'text_b': 'hypothesis', 'label': 'label','huggingface': False, 'using_hf_api': False, 'using_pandas': False, 'using_json':True, 'data_path':'data/DocNLI_dataset/train.json' },
'squad': {'task': 'extractive_qa', 'text_a': 'context', 'text_b': ['question', 'answers'], 'label': None, 'huggingface': True},
'squad_v2': {'task': 'qa', 'text_a': 'context', 'text_b': ['question', 'answers'], 'label': None, 'huggingface': True},
'paws': {'task': 'paraphrase', 'text_a': 'sentence1', 'text_b': 'sentence2', 'label': 'label', 'huggingface': True},
'vitaminc': {'task': 'fact_checking', 'text_a': 'evidence', 'text_b': 'claim', 'label': 'label', 'huggingface': True},
'xsum': {'task': 'summarization', 'text_a': 'document', 'text_b': 'summary', 'label': None, 'huggingface': True, 'cliff_path': 'data/model_generated_data/cliff_summ/xsum_train.jsonl'},
'stsb': {'task': 'sts', 'text_a': 'sentence1', 'text_b': 'sentence2', 'label': 'label', 'huggingface': True},
'sick': {'task': 'sts', 'text_a': 'sentence_A', 'text_b': 'sentence_B', 'label': 'relatedness_score', 'huggingface': True},
'race': {'task': 'qa', 'text_a': 'article', 'text_b': ['question', 'options'], 'label': 'answer', 'huggingface': True},
'race_val': {'task': 'qa', 'text_a': 'article', 'text_b': ['question', 'options'], 'label': 'answer', 'huggingface': True},
'anli_r1': {'task': 'nli', 'text_a': 'premise', 'text_b': 'hypothesis', 'label': 'label', 'huggingface': True},
'anli_r2': {'task': 'nli', 'text_a': 'premise', 'text_b': 'hypothesis', 'label': 'label', 'huggingface': True},
'anli_r3': {'task': 'nli', 'text_a': 'premise', 'text_b': 'hypothesis', 'label': 'label', 'huggingface': True},
'snli': {'task': 'nli', 'text_a': 'premise', 'text_b': 'hypothesis', 'label': 'label', 'huggingface': True},
'wikihow': {'task': 'summarization', 'text_a': 'text', 'text_b': 'headline', 'label': None, 'huggingface': False, 'using_hf_api': True, 'data_dir': 'data/wikihow_raw'},
'mrpc': {'task': 'paraphrase', 'text_a': 'sentence1', 'text_b': 'sentence2', 'label': 'label','huggingface': True},
'mrpc_val': {'task': 'paraphrase', 'text_a': 'sentence1', 'text_b': 'sentence2', 'label': 'label','huggingface': True},
'paws_val': {'task': 'paraphrase', 'text_a': 'sentence1', 'text_b': 'sentence2', 'label': 'label', 'huggingface': True},
'paws_unlabeled': {'task': 'paraphrase', 'text_a': 'sentence1', 'text_b': 'sentence2', 'label': 'label', 'huggingface': True},
'msmarco': {'task': 'ir', 'text_a': 'passages', 'text_b': ['query', 'answers'], 'label': None,'huggingface': True},
'paws_qqp': {'task': 'paraphrase', 'text_a': 'sentence1', 'text_b': 'sentence2', 'label': None,'huggingface': False, 'using_hf_api': False, 'using_pandas': True, 'data_path':'paws_qqp/output/train.tsv' },
'wiki103': {'task': 'paraphrase', 'text_a': 'original_sent', 'text_b': 'paraphrase', 'label': None,'huggingface': False, 'using_hf_api': False, 'using_pandas': False, 'using_json': True, 'data_path':'data/model_generated_data/backtranslation/wiki103_single_sent_backtranslation.json'},
'qqp': {'task': 'paraphrase', 'text_a':'question1', 'text_b':'question2', 'label': 'label', 'huggingface': True},
'qqp_val': {'task': 'paraphrase', 'text_a':'question1', 'text_b':'question2', 'label': 'label', 'huggingface': True},
'wmt17xxx': {'task': 'wmt', 'text_a': 'ref', 'text_b': 'mt', 'label': 'score','huggingface': False, 'using_hf_api': False, 'using_pandas': True, 'data_path':'data/wmt/wmt17/2017-da.csv' },
'wmt15': {'task': 'wmt', 'text_a': 'ref', 'text_b': 'mt', 'label': 'score','huggingface': False, 'using_hf_api': False, 'using_pandas': False, 'using_json':True, 'data_path':'data/eval/wmt15_eval.jsonl' },
'wmt16': {'task': 'wmt', 'text_a': 'ref', 'text_b': 'mt', 'label': 'score','huggingface': False, 'using_hf_api': False, 'using_pandas': False, 'using_json':True, 'data_path':'data/eval/wmt16_eval.jsonl' },
'wmt17': {'task': 'wmt', 'text_a': 'ref', 'text_b': 'mt', 'label': 'score','huggingface': False, 'using_hf_api': False, 'using_pandas': False, 'using_json':True, 'data_path':'data/eval/wmt17_eval.jsonl' },
'wmt18': {'task': 'wmt', 'text_a': 'ref', 'text_b': 'mt', 'label': 'score','huggingface': False, 'using_hf_api': False, 'using_pandas': False, 'using_json':True, 'data_path':'data/eval/wmt18_eval.jsonl' },
'wmt19': {'task': 'wmt', 'text_a': 'ref', 'text_b': 'mt', 'label': 'score','huggingface': False, 'using_hf_api': False, 'using_pandas': False, 'using_json':True, 'data_path':'data/eval/wmt19_eval.jsonl' },
'squad_v2_new': {'task': 'qa', 'huggingface': True},
'adversarial_qa': {'task': 'qa', 'huggingface': True},
'drop': {'task': 'qa', 'huggingface': True},
'duorc_self': {'task': 'qa', 'huggingface': True},
'duorc_paraphrase': {'task': 'qa', 'huggingface': True},
'quoref': {'task': 'qa', 'huggingface': True},
'hotpot_qa_distractor': {'task': 'qa', 'huggingface': True},
'hotpot_qa_fullwiki': {'task': 'qa', 'huggingface': True},
'newsqa': {'task': 'qa', 'using_json': True, 'raw_json': True, 'data_path': 'data/newsqa_raw/combined-newsqa-data-v1.json'},
'ropes': {'task': 'qa', 'huggingface': True},
'boolq': {'task': 'qa', 'huggingface': True},
'eraser_multi_rc': {'task': 'qa', 'huggingface': True},
'quail': {'task': 'qa', 'huggingface': True},
'sciq': {'task': 'qa', 'huggingface': True},
'strategy_qa': {'task': 'qa', 'huggingface': True},
'gap': {'task': 'coreference', 'huggingface': True},
}
class QA2D():
def __init__(self, batch_size=32, device='cuda', verbose=True) -> None:
from transformers import BartTokenizer, BartForConditionalGeneration
self.tokenizer = BartTokenizer.from_pretrained("MarkS/bart-base-qa2d")
self.model = BartForConditionalGeneration.from_pretrained("MarkS/bart-base-qa2d").to(device)
self.batch_size = batch_size
self.device=device
self.verbose = verbose
def generate(self, questions: list, answers: list):
assert len(questions) == len(answers)
qa_list = []
for q, a in zip(questions, answers):
qa_list.append(f"question: {q} answer: {a}")
output = []
for qa_pairs in tqdm(
self.chunks(qa_list, self.batch_size),
desc="QA to Declarative",
total=int(len(qa_list)/self.batch_size),
disable=(not self.verbose)
):
input_text = qa_pairs
input_token = self.tokenizer(
input_text, return_tensors='pt', padding=True, truncation=True).to(self.device)
dec_sents = self.model.generate(
input_token.input_ids, max_length=512)
result = self.tokenizer.batch_decode(
dec_sents, skip_special_tokens=True)
output.extend(result)
return output
def chunks(self, lst, n):
"""Yield successive n-sized chunks from lst."""
for i in range(0, len(lst), n):
yield lst[i:i + n]
class QAnswering():
"""
To answer not-answerable questions
"""
def __init__(self, batch_size=32, device='cuda') -> None:
from transformers import T5Tokenizer, T5ForConditionalGeneration
self.tokenizer = T5Tokenizer.from_pretrained(
"valhalla/t5-base-qa-qg-hl")
self.model = T5ForConditionalGeneration.from_pretrained(
"valhalla/t5-base-qa-qg-hl").to(device)
self.batch_size = batch_size
self.device = device
def generate(self, questions: list, contexts: list):
assert len(questions) == len(contexts)
answers = []
for qs, cs in tqdm(zip(self.chunks(questions, self.batch_size), self.chunks(contexts, self.batch_size)), desc="Generating Answers for not answerable", total=int(len(questions)/self.batch_size)):
qc_pairs = []
assert len(qs) == len(cs)
for one_q, one_c in zip(qs, cs):
qc_pairs.append(f"""question: {one_q} context: {one_c}""")
input_ids = self.tokenizer(
qc_pairs, padding=True, truncation=True, return_tensors='pt').to(self.device).input_ids
outputs = self.model.generate(input_ids, max_length=512)
answers.extend(self.tokenizer.batch_decode(
outputs, skip_special_tokens=True))
return answers
def chunks(self, lst, n):
"""Yield successive n-sized chunks from lst."""
for i in range(0, len(lst), n):
yield lst[i:i + n]
class MLMGeneratorWithPairedData():
def __init__(self, corpra: list, device='cuda', batch_size=8, mask_percent=0.25) -> None:
self.device = device
self.tokenizer = transformers.DistilBertTokenizer.from_pretrained(
"distilbert-base-uncased")
self.model = transformers.DistilBertForMaskedLM.from_pretrained(
"distilbert-base-uncased").to(self.device)
self.mask_percent = mask_percent
self.batch_size = batch_size
self.dataset = corpra # text needs to be noised
def chunks(self, lst, n):
"""Yield successive n-sized chunks from lst."""
for i in range(0, len(lst), n):
yield lst[i:i + n]
def generate(self):
sents_output = []
for examples in tqdm(self.chunks(self.dataset, self.batch_size), total=int(len(self.dataset)/self.batch_size), desc="MLM Generating"):
sents_to_be_noised = [each for each in examples]
sents_noised = self.mlm_infiller(sents_to_be_noised)
sents_output.extend(sents_noised)
return sents_output
def mlm_infiller(self, batch):
"""
input a batch of sentences, list
"""
masked_batch = []
masked_batch_ids = []
for each_sent in batch:
sent_tokens = self.tokenizer.tokenize(each_sent)
sent_token_ids = self.tokenizer(each_sent)['input_ids']
mask_list = sample(list(range(len(sent_tokens))), int(
self.mask_percent * len(sent_tokens)))
sent_tokens = [
each if i not in mask_list else self.tokenizer.mask_token for i, each in enumerate(sent_tokens)]
masked_batch_ids.append(
[each if i-1 not in mask_list else self.tokenizer.mask_token_id for i, each in enumerate(sent_token_ids)])
masked_batch.append(' '.join(sent_tokens))
inputs = self.tokenizer(
masked_batch, padding=True, truncation=True, return_tensors="pt").to(self.device)
with torch.no_grad():
logits = self.model(**inputs).logits
infill_tokens = []
for i in range(len(masked_batch)):
mask_token_index = (inputs.input_ids == self.tokenizer.mask_token_id)[
i].nonzero(as_tuple=True)[0]
predicted_token_id = logits[i, mask_token_index].argmax(axis=-1)
infill_tokens.append(predicted_token_id)
infilled_sent = []
for masked_sent_ids, infill_token in zip(masked_batch_ids, infill_tokens):
for infill_one_token in infill_token:
for i, each_id in enumerate(masked_sent_ids):
if each_id == self.tokenizer.mask_token_id:
masked_sent_ids[i] = infill_one_token
break
infilled_sent.append(self.tokenizer.decode(
masked_sent_ids, skip_special_tokens=True))
return infilled_sent
class ExtractiveSummarizationGenerator():
def __init__(self) -> None:
pass
def generate(self, texts):
'''
texts: list of string
'''
from summa.summarizer import summarize
summaries = []
for text in tqdm(texts, desc="Extracting Summary"):
for prop in range(1, 20):
summ = summarize(text, ratio=prop/20.)
if len(summ) > 0:
break
summaries.append(summ)
return summaries
class DataGenerator():
def __init__(self, dataset_names) -> None:
self.dataset_names = dataset_names
self.datasets = dict()
self.t5_qa = None
self.t5_tokenizer = None
self.load_dataset_from_huggingface()
def load_dataset_from_huggingface(self):
for each_dataset in self.dataset_names:
if DATASET_CONFIG[each_dataset].get('huggingface'):
self.datasets[each_dataset] = load_dataset(
*DATASET_HUGGINGFACE[each_dataset][:-1])[DATASET_HUGGINGFACE[each_dataset][-1]]
elif DATASET_CONFIG[each_dataset].get('using_hf_api'):
self.datasets[each_dataset] = load_dataset(
*DATASET_HUGGINGFACE[each_dataset][:-1], data_dir=DATASET_CONFIG[each_dataset]['data_dir'])[DATASET_HUGGINGFACE[each_dataset][-1]]
elif DATASET_CONFIG[each_dataset].get('using_pandas'):
if DATASET_CONFIG[each_dataset]['data_path'].split('.')[-1] == 'tsv':
self.datasets[each_dataset] = pd.read_csv(
DATASET_CONFIG[each_dataset]['data_path'], sep='\t')
elif DATASET_CONFIG[each_dataset]['data_path'].split('.')[-1] == 'csv':
self.datasets[each_dataset] = pd.read_csv(
DATASET_CONFIG[each_dataset]['data_path'])
elif DATASET_CONFIG[each_dataset].get('using_json'):
self.datasets[each_dataset] = []
if DATASET_CONFIG[each_dataset].get('raw_json'):
with open(DATASET_CONFIG[each_dataset]['data_path'], 'r', encoding='utf8') as f:
self.datasets[each_dataset] = json.load(f)
else:
try:
json_file = json.load(
open(DATASET_CONFIG[each_dataset]['data_path'], 'r', encoding='utf8'))
for example in json_file:
self.datasets[each_dataset].append(example)
except:
with open(DATASET_CONFIG[each_dataset]['data_path'], 'r', encoding='utf8') as f:
for example in f:
self.datasets[each_dataset].append(
json.loads(example))
else:
error('unable to locate raw dataset...')
def process_squad(self):
from rake_nltk import Rake
r = Rake()
topk = 5
threshold = 0.6
output = []
label = -1
for example in tqdm(self.datasets['squad'], desc=f'Constructing squad'):
text_a = example[DATASET_CONFIG['squad']['text_a']]
question = example[DATASET_CONFIG['squad']['text_b'][0]]
answer = example[DATASET_CONFIG['squad']
['text_b'][1]]['text'] # a list
text_b = [question+' '+answer_ele for answer_ele in answer]
text_c = []
r.extract_keywords_from_text(text_a)
keywords_in_context = r.get_ranked_phrases()[:topk]
for each_keyword in keywords_in_context:
# then it is an incorrect answer
if sentence_bleu([answer_ele.lower().split() for answer_ele in answer], each_keyword.split(), weights=(0.33, 0.33, 0.33)) < threshold:
text_c.append(question+' '+each_keyword)
output.append({
'text_a': text_a,
'text_b': text_b,
'text_c': text_c,
'label': label
})
return output
def process_squad_v2(self):
# first collect answerable items
not_answerable_contexts = []
not_answerable_questions = []
not_answerable_answers = []
answerable_contexts = []
answerable_questions = []
answerable_answers = []
qa_generator = QAnswering(batch_size=32, device='cuda')
qa2d_generator = QA2D(batch_size=32, device='cuda')
for example in tqdm(self.datasets['squad_v2'], desc=f'Collecting (not)answerable examples'):
if len(example['answers']['text']) == 0:
not_answerable_contexts.append(example['context'])
not_answerable_questions.append(example['question'])
else:
answerable_contexts.append(example['context'])
answerable_questions.append(example['question'])
answerable_answers.append(example['answers']['text'][0])
not_answerable_answers = qa_generator.generate(
not_answerable_questions, not_answerable_contexts)
answerable_declarative_sents = qa2d_generator.generate(
answerable_questions, answerable_answers)
not_answerable_declarative_sents = qa2d_generator.generate(
not_answerable_questions, not_answerable_answers)
output = []
for i, dec_sent in enumerate(answerable_declarative_sents):
output.append({
'text_a': answerable_contexts[i],
'text_b': [dec_sent],
'text_c': [],
'label': 1
})
for i, dec_sent in enumerate(not_answerable_declarative_sents):
output.append({
'text_a': not_answerable_contexts[i],
'text_b': [dec_sent],
'text_c': [],
'label': 0
})
return output
def process_race(self):
qa2d_generator = QA2D(batch_size=32, device='cuda')
option_dict = {'A': 0, 'B': 1, 'C': 2, 'D': 3}
output = []
correct_context = []
correct_question = []
correct_answer = []
wrong_context = []
wrong_question = []
wrong_answer = []
for example in tqdm(self.datasets['race'], desc=f'Constructing race'):
text_a = example[DATASET_CONFIG['race']['text_a']]
label = -1
question = example[DATASET_CONFIG['race']['text_b'][0]]
if "_" in question:
answer_id = option_dict[example[DATASET_CONFIG['race']['label']]]
for i, options in enumerate(example[DATASET_CONFIG['race']['text_b'][1]]):
if i == answer_id:
output.append({
'text_a': text_a,
'text_b': [' '.join(question.replace("_", " "+options+" ").split())],
'text_c': [],
'label': 1
})
else:
output.append({
'text_a': text_a,
'text_b': [' '.join(question.replace("_", " "+options+" ").split())],
'text_c': [],
'label': 0
})
else:
answer_id = option_dict[example[DATASET_CONFIG['race']['label']]]
for i, options in enumerate(example[DATASET_CONFIG['race']['text_b'][1]]):
if i == answer_id:
output.append({
'text_a': text_a,
'text_b': [question],
'text_c': [options],
'label': 1
})
else:
output.append({
'text_a': text_a,
'text_b': [question],
'text_c': [options],
'label': 0
})
return output
def process_race_val(self):
qa2d_generator = QA2D(batch_size=32, device='cuda')
option_dict = {'A': 0, 'B': 1, 'C': 2, 'D': 3}
output = []
correct_context = []
correct_question = []
correct_answer = []
wrong_context = []
wrong_question = []
wrong_answer = []
for example in tqdm(self.datasets['race_val'], desc=f'Constructing race_val'):
text_a = example[DATASET_CONFIG['race_val']['text_a']]
label = -1
question = example[DATASET_CONFIG['race_val']['text_b'][0]]
if "_" in question:
answer_id = option_dict[example[DATASET_CONFIG['race_val']['label']]]
for i, options in enumerate(example[DATASET_CONFIG['race_val']['text_b'][1]]):
if i == answer_id:
output.append({
'text_a': text_a,
'text_b': [' '.join(question.replace("_", " "+options+" ").split())],
'text_c': [],
'label': 1
})
else:
output.append({
'text_a': text_a,
'text_b': [' '.join(question.replace("_", " "+options+" ").split())],
'text_c': [],
'label': 0
})
else:
answer_id = option_dict[example[DATASET_CONFIG['race_val']['label']]]
for i, options in enumerate(example[DATASET_CONFIG['race_val']['text_b'][1]]):
if i == answer_id:
correct_context.append(text_a)
correct_question.append(question)
correct_answer.append(options)
else:
wrong_context.append(text_a)
wrong_question.append(question)
wrong_answer.append(options)
correct_declarative = qa2d_generator.generate(
correct_question, correct_answer)
wrong_declarative = qa2d_generator.generate(
wrong_question, wrong_answer)
assert len(correct_context) == len(correct_declarative)
assert len(wrong_context) == len(wrong_declarative)
for context, dec in zip(correct_context, correct_declarative):
output.append({
'text_a': context,
'text_b': [dec],
'text_c': [],
'label': 1
})
for context, dec in zip(wrong_context, wrong_declarative):
output.append({
'text_a': context,
'text_b': [dec],
'text_c': [],
'label': 0
})
return output
def process_race_test(self):
option_dict = {'A': 0, 'B': 1, 'C': 2, 'D': 3}
output = []
for example in tqdm(self.datasets['race_test'], desc=f'Constructing race_test'):
text_a = example[DATASET_CONFIG['race_test']['text_a']]
text_b = [] # pos
text_c = [] # neg
label = -1
question = example[DATASET_CONFIG['race_test']['text_b'][0]]
if "_" in question:
answer_id = option_dict[example[DATASET_CONFIG['race_test']['label']]]
for i, options in enumerate(example[DATASET_CONFIG['race_test']['text_b'][1]]):
if i == answer_id:
text_b.append(' '.join(question.replace(
"_", " "+options+" ").split()))
else:
text_c.append(' '.join(question.replace(
"_", " "+options+" ").split()))
else:
answer_id = option_dict[example[DATASET_CONFIG['race_test']['label']]]
for i, options in enumerate(example[DATASET_CONFIG['race_test']['text_b'][1]]):
if i == answer_id:
text_b.append(question+" "+options+" ")
else:
text_c.append(question+" "+options+" ")
output.append({
'text_a': text_a,
'text_b': text_b,
'text_c': text_c,
'label': label
})
return output
def process_xsum(self):
'''
text_a: raw_text
text_b: raw_summary + ***extractive summ*** removed
text_c: cliff xsum + DistillBERT from raw_text_b + ***DistillBERT from extractive summ text_b***
'''
output = []
gold_summary = [example[DATASET_CONFIG['xsum']['text_b']]
for example in self.datasets['xsum']]
ext_summarizer = ExtractiveSummarizationGenerator()
extracted_summ = ext_summarizer.generate(
[example[DATASET_CONFIG['xsum']['text_a']] for example in self.datasets['xsum']])
mlm_hallucinator = MLMGeneratorWithPairedData(
corpra=gold_summary, device='cuda:0', batch_size=64, mask_percent=0.25)
gold_summary_hallucinated = mlm_hallucinator.generate()
mlm_hallucinator = MLMGeneratorWithPairedData(
corpra=extracted_summ, device='cuda:0', batch_size=64, mask_percent=0.25)
extracted_summ_hallucinated = mlm_hallucinator.generate()
assert len(self.datasets['xsum']) == len(gold_summary_hallucinated) and len(
self.datasets['xsum']) == len(extracted_summ_hallucinated)
for i, example in tqdm(enumerate(self.datasets['xsum']), desc="Constructing xsum", total=len(self.datasets['xsum'])):
text_a = example[DATASET_CONFIG['xsum']['text_a']]
text_b = [gold_summary[i], extracted_summ[i]]
text_c = [gold_summary_hallucinated[i],
extracted_summ_hallucinated[i]]
label = -1
output.append({
'text_a': text_a,
'text_b': text_b,
'text_c': text_c,
'label': label
})
return output
def process_cnndm(self):
'''
text_a: raw_text
text_b: raw_summary + ***extractive summ*** removed
text_c: DistillBERT from raw_text_b + ***DistillBERT from extractive summ text_b***
'''
# interpretation of fairseq-generate output: https://github.com/facebookresearch/fairseq/issues/3000
output = []
gold_summary = [example[DATASET_CONFIG['cnndm']['text_b']]
for example in self.datasets['cnndm']]
ext_summarizer = ExtractiveSummarizationGenerator()
extracted_summ = ext_summarizer.generate(
[example[DATASET_CONFIG['cnndm']['text_a']] for example in self.datasets['cnndm']])
mlm_hallucinator = MLMGeneratorWithPairedData(
corpra=gold_summary, device='cuda:0', batch_size=64, mask_percent=0.25)
gold_summary_hallucinated = mlm_hallucinator.generate()
mlm_hallucinator = MLMGeneratorWithPairedData(
corpra=extracted_summ, device='cuda:0', batch_size=64, mask_percent=0.25)
extracted_summ_hallucinated = mlm_hallucinator.generate()
assert len(self.datasets['cnndm']) == len(gold_summary_hallucinated) and len(
self.datasets['cnndm']) == len(extracted_summ_hallucinated)
for i, example in tqdm(enumerate(self.datasets['cnndm']), desc="Constructing cnndm", total=len(self.datasets['cnndm'])):
text_a = example[DATASET_CONFIG['cnndm']['text_a']]
text_b = [gold_summary[i], extracted_summ[i]]
text_c = [gold_summary_hallucinated[i],
extracted_summ_hallucinated[i]]
label = -1
output.append({
'text_a': text_a,
'text_b': text_b,
'text_c': text_c,
'label': label
})
return output
def process_wikihow(self):
'''
text_a: raw_text
text_b: raw_summary + ***extractive summ*** removed
text_c: DistillBERT from raw_text_b + ***DistillBERT from extractive summ text_b***
'''
# interpretation of fairseq-generate output: https://github.com/facebookresearch/fairseq/issues/3000
output = []
gold_summary = [example[DATASET_CONFIG['wikihow']['text_b']]
for example in self.datasets['wikihow']]
ext_summarizer = ExtractiveSummarizationGenerator()
extracted_summ = ext_summarizer.generate(
[example[DATASET_CONFIG['wikihow']['text_a']] for example in self.datasets['wikihow']])
mlm_hallucinator = MLMGeneratorWithPairedData(
corpra=gold_summary, device='cuda:0', batch_size=64, mask_percent=0.25)
gold_summary_hallucinated = mlm_hallucinator.generate()
mlm_hallucinator = MLMGeneratorWithPairedData(
corpra=extracted_summ, device='cuda:0', batch_size=64, mask_percent=0.25)
extracted_summ_hallucinated = mlm_hallucinator.generate()
assert len(self.datasets['wikihow']) == len(gold_summary_hallucinated) and len(
self.datasets['wikihow']) == len(extracted_summ_hallucinated)
for i, example in tqdm(enumerate(self.datasets['wikihow']), desc="Constructing wikihow", total=len(self.datasets['wikihow'])):
text_a = example[DATASET_CONFIG['wikihow']['text_a']]
text_b = [gold_summary[i], extracted_summ[i]]
text_c = [gold_summary_hallucinated[i],
extracted_summ_hallucinated[i]]
label = -1
output.append({
'text_a': text_a,
'text_b': text_b,
'text_c': text_c,
'label': label
})
return output
def process_wiki103(self):
output = []
paraphrases = [example[DATASET_CONFIG['wiki103']['text_b']]
for example in self.datasets['wiki103']]
mlm_hallucinator = MLMGeneratorWithPairedData(
corpra=paraphrases, device='cuda:3', batch_size=64, mask_percent=0.25)
paraphrase_hallucinated = mlm_hallucinator.generate()
assert len(self.datasets['wiki103']) == len(paraphrase_hallucinated)
for i, example in tqdm(enumerate(self.datasets['wiki103']), desc=f'Constructing wiki103'):
output.append({
'text_a': example[DATASET_CONFIG['wiki103']['text_a']],
'text_b': [example[DATASET_CONFIG['wiki103']['text_b']]],
'text_c': [],
'label': 1
})
output.append({
'text_a': example[DATASET_CONFIG['wiki103']['text_a']],
'text_b': [paraphrase_hallucinated[i]],
'text_c': [],
'label': 0
})
return output
def process_mnli(self):
output = []
for example in tqdm(self.datasets['mnli'], desc=f'Constructing mnli'):
text_a = example[DATASET_CONFIG['mnli']['text_a']]
text_b = [example[DATASET_CONFIG['mnli']['text_b']]]
text_c = []
label = example[DATASET_CONFIG['mnli']['label']]
output.append({
'text_a': text_a,
'text_b': text_b,
'text_c': text_c,
'label': label
})
return output
def process_nli_fever(self):
output = []
for example in tqdm(self.datasets['nli_fever'], desc=f'Constructing nli_fever'):
text_a = example[DATASET_CONFIG['nli_fever']['text_a']]
text_b = [example[DATASET_CONFIG['nli_fever']['text_b']]]
text_c = []
raw_label = example[DATASET_CONFIG['nli_fever']['label']]
if raw_label == 'SUPPORTS': # convert to nli style label
label = 0
elif raw_label == 'REFUTES':
label = 2
else:
label = 1
output.append({
'text_a': text_a,
'text_b': text_b,
'text_c': text_c,
'label': label
})
return output
def process_doc_nli(self):
output = []
for example in tqdm(self.datasets['doc_nli'], desc=f'Constructing doc_nli'):
text_a = example[DATASET_CONFIG['doc_nli']['text_a']]
text_b = [example[DATASET_CONFIG['doc_nli']['text_b']]]
text_c = []
raw_label = example[DATASET_CONFIG['doc_nli']['label']]
if raw_label == 'entailment': # convert to paraphrase style label
label = 1
else:
label = 0
output.append({
'text_a': text_a,
'text_b': text_b,
'text_c': text_c,
'label': label
})
return output
def process_anli_r1(self):
output = []
for example in tqdm(self.datasets['anli_r1'], desc=f'Constructing anli_r1'):
text_a = example[DATASET_CONFIG['anli_r1']['text_a']]
text_b = [example[DATASET_CONFIG['anli_r1']['text_b']]]
text_c = []
label = example[DATASET_CONFIG['anli_r1']['label']]
output.append({
'text_a': text_a,
'text_b': text_b,
'text_c': text_c,
'label': label
})
return output
def process_anli_r2(self):
output = []
for example in tqdm(self.datasets['anli_r2'], desc=f'Constructing anli_r2'):
text_a = example[DATASET_CONFIG['anli_r2']['text_a']]
text_b = [example[DATASET_CONFIG['anli_r2']['text_b']]]
text_c = []
label = example[DATASET_CONFIG['anli_r2']['label']]
output.append({
'text_a': text_a,
'text_b': text_b,
'text_c': text_c,
'label': label
})
return output
def process_anli_r3(self):
output = []
for example in tqdm(self.datasets['anli_r3'], desc=f'Constructing anli_r3'):
text_a = example[DATASET_CONFIG['anli_r3']['text_a']]
text_b = [example[DATASET_CONFIG['anli_r3']['text_b']]]
text_c = []
label = example[DATASET_CONFIG['anli_r3']['label']]
output.append({
'text_a': text_a,
'text_b': text_b,
'text_c': text_c,
'label': label
})
return output
def process_snli(self):
output = []
for example in tqdm(self.datasets['snli'], desc=f'Constructing snli'):
text_a = example[DATASET_CONFIG['snli']['text_a']]
text_b = [example[DATASET_CONFIG['snli']['text_b']]]
text_c = []
label = example[DATASET_CONFIG['snli']['label']]
output.append({
'text_a': text_a,
'text_b': text_b,
'text_c': text_c,
'label': label
})
return output
def process_paws(self):
output = []
for example in tqdm(self.datasets['paws'], desc=f'Constructing paws'):
text_a = example[DATASET_CONFIG['paws']['text_a']]
text_b = [example[DATASET_CONFIG['paws']['text_b']]]
text_c = []
label = example[DATASET_CONFIG['paws']['label']]
output.append({
'text_a': text_a,
'text_b': text_b,
'text_c': text_c,
'label': label
})
return output
def process_vitaminc(self):
output = []
for example in tqdm(self.datasets['vitaminc'], desc=f'Constructing vitaminc'):
text_a = example[DATASET_CONFIG['vitaminc']['text_a']]
text_b = [example[DATASET_CONFIG['vitaminc']['text_b']]]
text_c = []
raw_label = example[DATASET_CONFIG['vitaminc']['label']]
if raw_label == 'SUPPORTS': # convert to nli style label
label = 0
elif raw_label == 'REFUTES':
label = 2
else:
label = 1
output.append({
'text_a': text_a,
'text_b': text_b,
'text_c': text_c,
'label': label
})
return output
def process_stsb(self):
output = []
for example in tqdm(self.datasets['stsb'], desc=f'Constructing stsb'):
text_a = example[DATASET_CONFIG['stsb']['text_a']]
text_b = [example[DATASET_CONFIG['stsb']['text_b']]]
text_c = []
label = example[DATASET_CONFIG['stsb']['label']] / 5.0
output.append({
'text_a': text_a,
'text_b': text_b,
'text_c': text_c,
'label': label
})
return output
def process_sick(self):
output = []
for example in tqdm(self.datasets['sick'], desc=f'Constructing sick'):
text_a = example[DATASET_CONFIG['sick']['text_a']]
text_b = [example[DATASET_CONFIG['sick']['text_b']]]
text_c = []
label = example[DATASET_CONFIG['sick']['label']] / 5.0
output.append({
'text_a': text_a,
'text_b': text_b,
'text_c': text_c,
'label': label
})
return output
def process_mrpc(self):
output = []
for example in tqdm(self.datasets['mrpc'], desc=f'Constructing mrpc'):
text_a = example[DATASET_CONFIG['mrpc']['text_a']]
text_b = [example[DATASET_CONFIG['mrpc']['text_b']]]
text_c = []
label = example[DATASET_CONFIG['mrpc']['label']]
output.append({
'text_a': text_a,
'text_b': text_b,
'text_c': text_c,
'label': label
})
return output
def process_mrpc_val(self):
output = []
for example in tqdm(self.datasets['mrpc_val'], desc=f'Constructing mrpc_val'):
text_a = example[DATASET_CONFIG['mrpc_val']['text_a']]
text_b = [example[DATASET_CONFIG['mrpc_val']['text_b']]]
text_c = []
label = example[DATASET_CONFIG['mrpc_val']['label']]
output.append({
'text_a': text_a,
'text_b': text_b,
'text_c': text_c,
'label': label
})
return output
def process_paws_val(self):
output = []
for example in tqdm(self.datasets['paws_val'], desc=f'Constructing paws_val'):
text_a = example[DATASET_CONFIG['paws_val']['text_a']]
text_b = [example[DATASET_CONFIG['paws_val']['text_b']]]
text_c = []
label = example[DATASET_CONFIG['paws_val']['label']]
output.append({
'text_a': text_a,
'text_b': text_b,
'text_c': text_c,
'label': label
})
return output
def process_paws_unlabeled(self):
output = []
for example in tqdm(self.datasets['paws_unlabeled'], desc=f'Constructing paws_unlabeled'):
text_a = example[DATASET_CONFIG['paws_unlabeled']['text_a']]
text_b = [example[DATASET_CONFIG['paws_unlabeled']['text_b']]]
text_c = []
label = example[DATASET_CONFIG['paws_unlabeled']['label']]
output.append({
'text_a': text_a,
'text_b': text_b,
'text_c': text_c,
'label': label
})
return output
def process_qqp(self):
output = []
for example in tqdm(self.datasets['qqp'], desc=f'Constructing qqp'):
text_a = example[DATASET_CONFIG['qqp']['text_a']]
text_b = [example[DATASET_CONFIG['qqp']['text_b']]]
text_c = []
label = example[DATASET_CONFIG['qqp']['label']]
output.append({
'text_a': text_a,
'text_b': text_b,
'text_c': text_c,
'label': label
})
return output
def process_qqp_val(self):
output = []