-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdata.py
1084 lines (932 loc) · 38.9 KB
/
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
import collections
import json
import logging
import os
import random
import time
from io import open
import gzip
import datetime
import csv
import string
import re
from torch.utils.data import DataLoader, TensorDataset
from datasets import load_dataset
INITIAL_REWARD = 1
class SquadExample(object):
"""
A single training/test example for the Squad dataset.
For examples without an answer, the start and end position are -1.
"""
def __init__(self,
qas_id,
question_text,
paragraph_text,
orig_answer_text=None,
start_position=None,
end_position=None,
is_impossible=None):
self.qas_id = qas_id
self.question_text = question_text
self.paragraph_text = paragraph_text
self.orig_answer_text = orig_answer_text
self.start_position = start_position
self.end_position = end_position
self.is_impossible = is_impossible
def __str__(self):
return self.__repr__()
def __repr__(self):
s = ""
s += "qas_id: %s" % (self.qas_id)
s += ", question_text: %s" % (self.question_text)
s += ", paragraph_text: %s" % (self.paragraph_text)
if self.start_position:
s += ", start_position: %d" % (self.start_position)
if self.end_position:
s += ", end_position: %d" % (self.end_position)
if self.is_impossible:
s += ", is_impossible: %r" % (self.is_impossible)
return s
class FeedbackFeatures(object):
"""A single set of features of data."""
def __init__(self,
unique_id,
example_index,
tokens,
token_to_orig_map,
doc_token_offset,
input_ids,
input_mask,
segment_ids,
token_is_max_context,
start_sample=None,
end_sample=None,
class_sample=None,
reward=0,
class_reward=0,
log_prob=0,
class_log_prob=0):
self.unique_id = unique_id
self.example_index = example_index
self.tokens = tokens
self.token_to_orig_map = token_to_orig_map
self.doc_token_offset = doc_token_offset
self.input_ids = input_ids
self.input_mask = input_mask
self.segment_ids = segment_ids
self.token_is_max_context = token_is_max_context
self.start_sample = start_sample
self.end_sample = end_sample
self.class_sample = class_sample
self.reward = reward
self.class_reward = class_reward
self.log_prob = log_prob
self.class_log_prob = class_log_prob
def normalize_answer(s):
def remove_articles(text):
regex = re.compile(r'\b(a|an|the)\b', re.UNICODE)
return re.sub(regex, ' ', text)
def white_space_fix(text):
return ' '.join(text.split())
def remove_punc(text):
exclude = set(string.punctuation)
return ''.join(ch for ch in text if ch not in exclude)
def lower(text):
return text.lower()
return white_space_fix(remove_articles(remove_punc(lower(s))))
def get_tydi_data(input_file):
"""
Only load Enligsh data from tydi qa dataset
"""
input_data = []
with gzip.GzipFile(input_file, 'r') as reader:
# skip header
content = reader.read().decode('utf-8').strip().split('\n')[1:]
for line in content:
ex = json.loads(line)
# only choose english
if ex['language'] == 'english':
YES_NO = [annotation['yes_no_answer'] for annotation in ex['annotations']]
# ignore YES/NO examples
if 'YES' not in YES_NO:
input_data.append(ex)
assert (len(input_data) != 0)
return input_data
def get_mrqa_data(input_file):
input_data = []
id_=0
with gzip.GzipFile(input_file, 'r') as reader:
# skip header
content = reader.read().decode('utf-8').strip().split('\n')[1:]
for line in content:
ex = json.loads(line)
for qa in ex['qas']:
inst = {}
inst['title'] = ''
inst['context'] = ex['context']
inst['question'] = qa['question']
inst['example_id'] = str(id_)
inst['id'] = str(inst['example_id'])
inst['annotations'] = [{'orig_answer_text':l} for l in qa['answers']]
inst['detected_answers'] = qa['detected_answers']
id_ += 1
input_data.append(inst)
assert (len(input_data) != 0)
return input_data
def get_nq_data(input_file):
"""
Only load Enligsh data from tydi qa dataset
"""
input_data = []
id_ = 0
with gzip.GzipFile(input_file, 'r') as reader:
# skip header
content = reader.read().decode('utf-8').strip().split('\n')[1:]
for line in content:
ex = json.loads(line)
for qa in ex['qas']:
inst = {}
inst['title'] = ''
inst['context'] = ex['context']
inst['question'] = qa['question']
inst['example_id'] = str(id_)
inst['id'] = str(inst['example_id'])
inst['annotations'] = [{'orig_answer_text': l} for l in qa['answers']]
id_ += 1
input_data.append(inst)
assert (len(input_data) != 0)
return input_data
def get_feedback_data(input_file):
# read data
with gzip.GzipFile(input_file, 'r') as reader:
content = reader.read().decode('utf-8').strip().split('\n')
input_data = [json.loads(line) for line in content]
for i, inst in enumerate(input_data):
inst['example_id'] = str(i)
## for validation, keep the format the same as SQuAD data
if 'annotations' in inst:
if 'orig_answer_text' not in inst['annotations'][0]:
inst['annotations'] = [{'orig_answer_text': l} for l in inst['annotations']]
elif 'annotation' in inst:
inst['annotations'] = [{'orig_answer_text': inst['annotation']}]
return input_data
# https://github.com/google-research-datasets/tydiqa/blob/43cde6d598c1cf88c1a8b9ed32e89263ffb5e03b/tydi_eval.py#L239
# return a string
def byte_slice(text, start, end):
byte_str = bytes(text, 'utf-8')
# return str(byte_str[start:end])
return byte_str[start:end].decode('utf-8')
def read_mrqa_examples_and_features(is_training,
version_2_with_negative,
tokenizer,
max_seq_length,
prepend_title,
input_data,
get_dataset=False):
"""Read a SQuAD json file into a list of SquadExample."""
assert (len(input_data) != 0)
def is_whitespace(c):
if c == " " or c == "\t" or c == "\r" or c == "\n" or ord(c) == 0x202F:
return True
return False
examples = []
dataset = []
features = []
truncated_cnt = 0
filtered = 0
unique_id = 1000000000
example_index = 0
for entry in input_data:
title = entry["title"]
paragraph_text = entry["context"]
qas_id = entry["id"]
question_text = entry["question"]
start_position = None
end_position = None
orig_answer_text = None
is_impossible = False
padding_length = 0
# prepare inputs
query_tokens = tokenizer.tokenize(question_text)
context_tokens = tokenizer.tokenize(paragraph_text)
if prepend_title:
title_tokens = tokenizer.tokenize(title)
# truncate if needed
if prepend_title:
max_context_length = max_seq_length - len(query_tokens) - len(title_tokens) - 4
else:
max_context_length = max_seq_length - len(query_tokens) - 3
if len(query_tokens) > 100:
filtered += 1
continue
if len(context_tokens) > max_context_length:
context_tokens = context_tokens[0:max_context_length]
else:
padding_length = max_context_length - len(context_tokens)
# convert to indices
tokens = []
segment_ids = []
token_is_max_context = {}
doc_token_offset = 0
tokens.append("[CLS]")
segment_ids.append(0)
for token in query_tokens:
tokens.append(token)
segment_ids.append(0)
tokens.append("[SEP]")
segment_ids.append(0)
# prepend title tokens
if prepend_title:
for token in title_tokens:
tokens.append(token)
segment_ids.append(2)
tokens.append("[SEP]")
segment_ids.append(2)
doc_token_offset = len(tokens)
for token in context_tokens:
token_is_max_context[len(tokens)] = True
tokens.append(token)
segment_ids.append(1)
tokens.append("[SEP]")
segment_ids.append(1)
if padding_length > 0:
for _ in range(padding_length):
tokens.append("[PAD]")
segment_ids.append(0)
input_ids = tokenizer.convert_tokens_to_ids(tokens)
input_mask = [1] * (max_seq_length - padding_length) + [0] * padding_length
# filter [CLS] token to get the real offset mapping
offset_mapping = tokenizer(paragraph_text,
return_offsets_mapping=True,
truncation=True,
max_length=max_context_length +
2)['offset_mapping'][1:-1]
# get character to wrod offset for the document(context)
char_to_word_offset = {}
for index, offset in enumerate(offset_mapping):
assert (offset[0] + offset[1])
for o in range(offset[0], offset[1]):
char_to_word_offset[o] = index
orig_answer_text = entry["detected_answers"][0]["text"]
answer_length = len(orig_answer_text)
char_start = entry["detected_answers"][0]["char_spans"][0][0]
char_end = entry["detected_answers"][0]["char_spans"][0][1]
# char_end = char_start + answer_length - 1
# check if the answer is truncated by tokenization
if (char_start not in char_to_word_offset or char_end not in char_to_word_offset):
max_char = max([k for k in char_to_word_offset.keys()])
start_position = -1
end_position = -1
orig_answer_text = ""
if is_training:
truncated_cnt += 1
continue
else:
start_position = char_to_word_offset[char_start] + doc_token_offset
end_position = char_to_word_offset[char_end] + doc_token_offset
# check if the tokenized answer matches the original one
if normalize_answer(orig_answer_text).replace(" ", "") != normalize_answer("".join(
paragraph_text[offset_mapping[start_position-doc_token_offset][0]:
offset_mapping[end_position -
doc_token_offset][1]])).replace(" ", ""):
if is_training:
filtered += 1
continue
example = SquadExample(qas_id=qas_id,
question_text=question_text,
paragraph_text=paragraph_text,
orig_answer_text=orig_answer_text,
start_position=start_position,
end_position=end_position,
is_impossible=False)
examples.append(example)
features.append(
FeedbackFeatures(unique_id=unique_id,
example_index=example_index,
tokens=tokens,
token_to_orig_map=offset_mapping,
token_is_max_context=token_is_max_context,
doc_token_offset=doc_token_offset,
input_ids=input_ids,
input_mask=input_mask,
segment_ids=segment_ids,
start_sample=start_position,
end_sample=end_position,
reward=INITIAL_REWARD
)
)
unique_id += 1
example_index += 1
if get_dataset:
dataset.append(entry)
print('filtered %d examples..., truncated %d examples'%(filtered, truncated_cnt))
assert len(features) == len(examples)
if get_dataset:
assert len(dataset) == len(examples)
return examples, dataset, features
def read_squad_examples_and_features(is_training,
version_2_with_negative,
tokenizer,
max_seq_length,
prepend_title,
input_data,
get_dataset=True):
"""Read a SQuAD json file into a list of SquadExample."""
assert (len(input_data) != 0)
def is_whitespace(c):
if c == " " or c == "\t" or c == "\r" or c == "\n" or ord(c) == 0x202F:
return True
return False
examples = []
dataset = []
features = []
truncated_cnt = 0
filtered = 0
unique_id = 1000000000
example_index = 0
for entry in input_data:
title = entry["title"]
paragraph_text = entry["context"]
qas_id = entry["id"]
question_text = entry["question"]
start_position = None
end_position = None
orig_answer_text = None
is_impossible = False
padding_length = 0
# prepare inputs
query_tokens = tokenizer.tokenize(question_text)
context_tokens = tokenizer.tokenize(paragraph_text)
if prepend_title:
title_tokens = tokenizer.tokenize(title)
# truncate if needed
if prepend_title:
max_context_length = max_seq_length - len(query_tokens) - len(title_tokens) - 4
else:
max_context_length = max_seq_length - len(query_tokens) - 3
if len(query_tokens) > 100:
filtered += 1
continue
if len(context_tokens) > max_context_length:
context_tokens = context_tokens[0:max_context_length]
else:
padding_length = max_context_length - len(context_tokens)
# convert to indices
tokens = []
segment_ids = []
token_is_max_context = {}
doc_token_offset = 0
tokens.append("[CLS]")
segment_ids.append(0)
for token in query_tokens:
tokens.append(token)
segment_ids.append(0)
tokens.append("[SEP]")
segment_ids.append(0)
# prepend title tokens
if prepend_title:
for token in title_tokens:
tokens.append(token)
segment_ids.append(2)
tokens.append("[SEP]")
segment_ids.append(2)
doc_token_offset = len(tokens)
for token in context_tokens:
token_is_max_context[len(tokens)] = True
tokens.append(token)
segment_ids.append(1)
tokens.append("[SEP]")
segment_ids.append(1)
if padding_length > 0:
for _ in range(padding_length):
tokens.append("[PAD]")
segment_ids.append(0)
input_ids = tokenizer.convert_tokens_to_ids(tokens)
input_mask = [1] * (max_seq_length - padding_length) + [0] * padding_length
# filter [CLS] token to get the real offset mapping
offset_mapping = tokenizer(paragraph_text,
return_offsets_mapping=True,
truncation=True,
max_length=max_context_length + 2)['offset_mapping'][1:-1]
# get character to wrod offset for the document(context)
char_to_word_offset = {}
for index, offset in enumerate(offset_mapping):
assert (offset[0] + offset[1])
for o in range(offset[0], offset[1]):
char_to_word_offset[o] = index
# get the start & end positions for the answer
if is_training:
if version_2_with_negative:
is_impossible = (len(entry["answers"]["text"]) == 0)
if (len(entry["answers"]["text"]) != 1) and (not is_impossible):
raise ValueError("For training, each question should have exactly 1 answer.")
if not is_impossible:
orig_answer_text = entry["answers"]["text"][0]
answer_length = len(orig_answer_text)
char_start = entry["answers"]["answer_start"][0]
char_end = char_start + answer_length - 1
# check if the answer is truncated by tokenization
if char_start not in char_to_word_offset or char_end not in char_to_word_offset:
truncated_cnt += 1
start_position = -1
end_position = -1
orig_answer_text = ""
is_impossible = True
continue
else:
start_position = char_to_word_offset[char_start] + doc_token_offset
end_position = char_to_word_offset[char_end] + doc_token_offset
# check if the tokenized answer matches the original one
if normalize_answer(orig_answer_text).replace(" ", "") != normalize_answer("".join(
paragraph_text[offset_mapping[start_position - doc_token_offset][0]:
offset_mapping[end_position -
doc_token_offset][1]])).replace(" ", ""):
filtered += 1
continue
else:
start_position = -1
end_position = -1
orig_answer_text = ""
example = SquadExample(qas_id=qas_id,
question_text=question_text,
paragraph_text=paragraph_text,
orig_answer_text=orig_answer_text,
start_position=start_position,
end_position=end_position,
is_impossible=version_2_with_negative and is_impossible)
examples.append(example)
if get_dataset:
dataset.append({
'question_text':
question_text,
'example_id':
qas_id,
'context':
paragraph_text,
# for SQuAD 2.0, 'annotations' would be an empty list
'annotations': [{
'orig_answer_text': a
} for a in entry['answers']['text']],
'is_impossible': (len(entry["answers"]["text"]) == 0),
})
features.append(
FeedbackFeatures(unique_id=unique_id,
example_index=example_index,
tokens=tokens,
token_to_orig_map=offset_mapping,
token_is_max_context=token_is_max_context,
doc_token_offset=doc_token_offset,
input_ids=input_ids,
input_mask=input_mask,
segment_ids=segment_ids,
start_sample=start_position,
end_sample=end_position,
reward=INITIAL_REWARD))
unique_id += 1
example_index += 1
print('filtered %d examples..., truncated %d examples' % (filtered, truncated_cnt))
if get_dataset:
assert len(examples) == len(dataset)
assert len(features) == len(examples)
return examples, dataset, features
def read_tydi_examples_and_features(input_data, is_training, version_2_with_negative, tokenizer,
max_seq_length, prepend_title):
"""Read a tydi json file into a list of SquadExample."""
unique_id = 1000000000
examples = []
features = []
num_impos = 0
example_index = 0
truncated_cnt = 0
for entry in input_data:
is_impossible_list = []
for idx in range(len(entry['annotations'])):
is_impossible_list.append(
entry['annotations'][idx]['minimal_answer']['plaintext_start_byte'] == -1)
is_impossible = (is_impossible_list.count(True) > is_impossible_list.count(False))
if is_training:
# for training, only 1 annotation
pas_index = entry['annotations'][0]['passage_answer']['candidate_index']
if pas_index == -1:
pas_index = 0
else:
# for eval
if is_impossible: # if is unanswerable, should be unanswerable for any passage (?)
pas_index = 0
else:
pas_index = -1
annotation_idx = 0
while pas_index == -1:
pas_index = entry['annotations'][annotation_idx]['passage_answer'][
'candidate_index']
annotation_idx += 1
# skip pas_index=1 if only having 1 passage
if pas_index >= len(entry['passage_answer_candidates']):
continue
# get passage and answer starting position in byte
pas_start_byte = entry['passage_answer_candidates'][pas_index]['plaintext_start_byte']
pas_end_byte = entry['passage_answer_candidates'][pas_index]['plaintext_end_byte']
plaintext_start_byte = entry['annotations'][0]['minimal_answer']['plaintext_start_byte']
plaintext_end_byte = entry['annotations'][0]['minimal_answer']['plaintext_end_byte']
relative_start_byte = plaintext_start_byte - pas_start_byte
relative_end_byte = plaintext_end_byte - pas_start_byte
paragraph_text = byte_slice(entry['document_plaintext'], pas_start_byte, pas_end_byte)
# get byte to char offset
byte_to_char = []
for idx, c in enumerate(paragraph_text):
for _ in range(len(c.encode())):
byte_to_char.append(idx)
qas_id = entry['example_id'] # FIXME shared by two passages
question_text = entry['question_text']
title = entry['document_title']
start_position = None
end_position = None
orig_answer_text = byte_slice(text=entry['document_plaintext'],
start=plaintext_start_byte,
end=plaintext_end_byte)
padding_length = 0
# prepare inputs
query_tokens = tokenizer.tokenize(question_text)
context_tokens = tokenizer.tokenize(paragraph_text)
if prepend_title:
title_tokens = tokenizer.tokenize(title)
# truncate if needed
if prepend_title:
max_context_length = max_seq_length - len(query_tokens) - len(title_tokens) - 4
else:
max_context_length = max_seq_length - len(query_tokens) - 3
if len(context_tokens) > max_context_length:
context_tokens = context_tokens[0:max_context_length]
else:
padding_length = max_context_length - len(context_tokens)
# convert to indices
tokens = []
segment_ids = []
token_is_max_context = {}
doc_token_offset = 0
tokens.append("[CLS]")
segment_ids.append(0)
for token in query_tokens:
tokens.append(token)
segment_ids.append(0)
tokens.append("[SEP]")
segment_ids.append(0)
# prepend title tokens
if prepend_title:
for token in title_tokens:
tokens.append(token)
segment_ids.append(2)
tokens.append("[SEP]")
segment_ids.append(2)
doc_token_offset = len(tokens)
for token in context_tokens:
token_is_max_context[len(tokens)] = True
tokens.append(token)
segment_ids.append(1)
tokens.append("[SEP]")
segment_ids.append(1)
if padding_length > 0:
for _ in range(padding_length):
tokens.append("[PAD]")
segment_ids.append(0)
input_ids = tokenizer.convert_tokens_to_ids(tokens)
input_mask = [1] * (max_seq_length - padding_length) + [0] * padding_length
# filter [CLS] token to get the real offset mapping
offset_mapping = tokenizer(paragraph_text,
return_offsets_mapping=True,
truncation=True,
max_length=max_context_length + 2)['offset_mapping'][1:-1]
# get character to wrod offset for the document(context)
char_to_word_offset = {}
for index, offset in enumerate(offset_mapping):
assert (offset[0] + offset[1])
for o in range(offset[0], offset[1]):
char_to_word_offset[o] = index
if is_training:
if version_2_with_negative:
assert is_impossible == (relative_start_byte < 0) or (
relative_start_byte >=
(pas_end_byte - pas_start_byte)) or (relative_end_byte >=
(pas_end_byte - pas_start_byte))
if (len(entry['annotations']) != 1) and (not is_impossible):
raise ValueError("For training, each question should have exactly 1 answer.")
if not is_impossible:
char_start = byte_to_char[relative_start_byte]
char_end = byte_to_char[relative_end_byte - 1]
if char_start not in char_to_word_offset:
truncated_cnt += 1
start_position = -1
end_position = -1
orig_answer_text = ""
is_impossible = True
else:
start_position = char_to_word_offset[char_start] + doc_token_offset
end_position = char_to_word_offset[char_end] + doc_token_offset
else:
start_position = -1
end_position = -1
orig_answer_text = ""
num_impos += 1
example = SquadExample(
qas_id=qas_id,
question_text=question_text,
paragraph_text=paragraph_text,
orig_answer_text=orig_answer_text,
start_position=(start_position if start_position == None else start_position -
doc_token_offset),
end_position=(end_position if end_position == None else end_position -
doc_token_offset),
is_impossible=is_impossible)
examples.append(example)
features.append(
FeedbackFeatures(unique_id=unique_id,
example_index=example_index,
tokens=tokens,
token_to_orig_map=offset_mapping,
token_is_max_context=token_is_max_context,
doc_token_offset=doc_token_offset,
input_ids=input_ids,
input_mask=input_mask,
segment_ids=segment_ids,
start_sample=start_position,
end_sample=end_position,
reward=INITIAL_REWARD))
unique_id += 1
example_index += 1
print('truncated', truncated_cnt)
assert len(examples) == len(features)
return examples, features
def read_feedback_examples_and_features(input_data,
negative_reward,
partial_reward,
reward_wrong_unans,
reward_correct_span,
reward_correct_unans,
reward_class_wrong,
reward_class_correct_ans,
tokenizer,
max_seq_length,
prepend_title,
load_log_prob=False):
unique_id = 1000000000
examples = []
features = []
i = 0
for inst in input_data:
qas_id = inst['example_id']
question_text = inst['question']
paragraph_text = inst['context']
feedback = inst['feedback']
title = inst['topic'] + ' [SEP] ' + inst['aspect']
startidx = inst['startidx']
endidx = inst['endidx']
padding_length = 0
# prepare inputs
query_tokens = tokenizer.tokenize(question_text)
context_tokens = tokenizer.tokenize(paragraph_text)
if prepend_title:
title_tokens = tokenizer.tokenize(title)
# truncate if needed
if prepend_title:
max_context_length = max_seq_length - len(query_tokens) - len(title_tokens) - 4
else:
max_context_length = max_seq_length - len(query_tokens) - 3
if len(context_tokens) > max_context_length:
context_tokens = context_tokens[0:max_context_length]
else:
padding_length = max_context_length - len(context_tokens)
# convert to indices
tokens = []
segment_ids = []
token_is_max_context = {}
doc_token_offset = 0
tokens.append("[CLS]")
segment_ids.append(0)
for token in query_tokens:
tokens.append(token)
segment_ids.append(0)
tokens.append("[SEP]")
segment_ids.append(0)
# prepend title tokens
if prepend_title:
for token in title_tokens:
tokens.append(token)
segment_ids.append(2)
tokens.append("[SEP]")
segment_ids.append(2)
doc_token_offset = len(tokens)
for token in context_tokens:
token_is_max_context[len(tokens)] = True
tokens.append(token)
segment_ids.append(1)
tokens.append("[SEP]")
segment_ids.append(1)
if padding_length > 0:
for _ in range(padding_length):
tokens.append("[PAD]")
segment_ids.append(0)
input_ids = tokenizer.convert_tokens_to_ids(tokens)
input_mask = [1] * (max_seq_length - padding_length) + [0] * padding_length
offset_mapping = tokenizer(
paragraph_text,
return_offsets_mapping=True,
truncation=True,
max_length=max_context_length +
2)['offset_mapping'][1:-1] # filter [CLS] token to get the real offset mapping
# get character to wrod offset for the document(context)
char_to_word_offset = {}
for index, offset in enumerate(offset_mapping):
assert (offset[0] + offset[1])
for o in range(offset[0], offset[1]):
char_to_word_offset[o] = index
if feedback in ['Unanswerable', 'Answerable']:
# just as placeholder, not for eval or training
start_position = -1
end_position = -1
class_position = 0
reward = 0
class_reward = 0
else:
pred = inst['pred']
# handle unanswerable
if pred == '[Unanswerable given the paragraph below]':
start_position = -1
end_position = -1
class_position = 0
else:
start_position = startidx
end_position = endidx
class_position = 1
if pred == '[Unanswerable given the paragraph below]': # predict unans, second action reward = 0
reward = 0
if feedback == 'Correct':
class_reward = 1
elif feedback == 'Wrong':
class_reward = -1
else:
class_reward = 0
else:
if feedback == 'Correct':
class_reward = reward_class_correct_ans
reward = reward_correct_span
elif feedback == 'Wrong':
class_reward = reward_class_wrong
reward = negative_reward
else:
class_reward = reward_class_correct_ans
reward = partial_reward * reward_correct_span
if load_log_prob:
assert 'log_prob' in inst
log_prob = float(inst['log_prob'])
assert 'class_log_prob' in inst
class_log_prob = float(inst['class_log_prob'])
else:
log_prob = 0
class_log_prob = 0
assert log_prob <= 0
assert class_log_prob <= 0
features.append(
FeedbackFeatures(unique_id=unique_id,
example_index=i,
tokens=tokens,
token_to_orig_map=offset_mapping,
token_is_max_context=token_is_max_context,
doc_token_offset=doc_token_offset,
input_ids=input_ids,
input_mask=input_mask,
segment_ids=segment_ids,
start_sample=start_position,
end_sample=end_position,
class_sample=class_position,
reward=reward,
class_reward=class_reward,
log_prob=log_prob,
class_log_prob=class_log_prob
))
examples.append(
SquadExample(qas_id=qas_id,
question_text=question_text,
paragraph_text=paragraph_text,
start_position=start_position,
end_position=end_position))
# keep track of counts
i += 1
unique_id += 1
return examples, features
def read_feedback_examples_and_features_supervised(input_data,
tokenizer,
max_seq_length,
prepend_title):
unique_id = 1000000000
dataset = []
examples = []
features = []
i = 0
for inst in input_data:
qas_id = inst['example_id']
question_text = inst['question']
paragraph_text = inst['context']
feedback = inst['feedback']
if feedback != 'Correct' and feedback not in ['Unanswerable', 'Answerable']:
continue
title = inst['topic'] + ' [SEP] ' + inst['aspect']
startidx = inst['startidx']
endidx = inst['endidx']
padding_length = 0
# prepare inputs
query_tokens = tokenizer.tokenize(question_text)
context_tokens = tokenizer.tokenize(paragraph_text)
if prepend_title:
title_tokens = tokenizer.tokenize(title)
# truncate if needed
if prepend_title:
max_context_length = max_seq_length - len(query_tokens) - len(title_tokens) - 4
else:
max_context_length = max_seq_length - len(query_tokens) - 3
if len(context_tokens) > max_context_length:
context_tokens = context_tokens[0:max_context_length]
else:
padding_length = max_context_length - len(context_tokens)
# convert to indices
tokens = []
segment_ids = []
token_is_max_context = {}
doc_token_offset = 0
tokens.append("[CLS]")
segment_ids.append(0)
for token in query_tokens:
tokens.append(token)
segment_ids.append(0)
tokens.append("[SEP]")