-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathTF2.0 Baseline w BERT - (translated to TF2.0).py
1490 lines (1198 loc) · 50.6 KB
/
TF2.0 Baseline w BERT - (translated to TF2.0).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 __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import gzip
import json
import os
import random
import re
import enum
import bert_modeling as modeling
import bert_optimization as optimization
import bert_tokenization as tokenization
import absl
import sys
import numpy as np
import tensorflow as tf
def del_all_flags(FLAGS):
flags_dict = FLAGS._flags()
keys_list = [keys for keys in flags_dict]
for keys in keys_list:
FLAGS.__delattr__(keys)
del_all_flags(absl.flags.FLAGS)
flags = absl.flags
flags.DEFINE_string(
"bert_config_file", "/kaggle/input/bertjointbaseline/bert_config.json",
"The config json file corresponding to the pre-trained BERT model. "
"This specifies the model architecture.")
flags.DEFINE_string("vocab_file", "/kaggle/input/bertjointbaseline/vocab-nq.txt",
"The vocabulary file that the BERT model was trained on.")
flags.DEFINE_string(
"output_dir", "outdir",
"The output directory where the model checkpoints will be written.")
flags.DEFINE_string("train_precomputed_file", None,
"Precomputed tf records for training.")
flags.DEFINE_integer("train_num_precomputed", None,
"Number of precomputed tf records for training.")
flags.DEFINE_string(
"predict_file", "/kaggle/input/tensorflow2-question-answering/simplified-nq-test.jsonl/simplified-nq-test.jsonl",
"NQ json for predictions. E.g., dev-v1.1.jsonl.gz or test-v1.1.jsonl.gz")
flags.DEFINE_string(
"output_prediction_file", "predictions.json",
"Where to print predictions in NQ prediction format, to be passed to"
"natural_questions.nq_eval.")
flags.DEFINE_string(
"init_checkpoint", "/kaggle/input/bertjointbaseline/bert_joint.ckpt",
"Initial checkpoint (usually from a pre-trained BERT model).")
flags.DEFINE_bool(
"do_lower_case", True,
"Whether to lower case the input text. Should be True for uncased "
"models and False for cased models.")
flags.DEFINE_integer(
"max_seq_length", 384,
"The maximum total input sequence length after WordPiece tokenization. "
"Sequences longer than this will be truncated, and sequences shorter "
"than this will be padded.")
flags.DEFINE_integer(
"doc_stride", 128,
"When splitting up a long document into chunks, how much stride to "
"take between chunks.")
flags.DEFINE_integer(
"max_query_length", 64,
"The maximum number of tokens for the question. Questions longer than "
"this will be truncated to this length.")
flags.DEFINE_bool("do_train", False, "Whether to run training.")
flags.DEFINE_bool("do_predict", True, "Whether to run eval on the dev set.")
flags.DEFINE_integer("train_batch_size", 32, "Total batch size for training.")
flags.DEFINE_integer("predict_batch_size", 8,
"Total batch size for predictions.")
flags.DEFINE_float("learning_rate", 5e-5, "The initial learning rate for Adam.")
flags.DEFINE_float("num_train_epochs", 3.0,
"Total number of training epochs to perform.")
flags.DEFINE_float(
"warmup_proportion", 0.1,
"Proportion of training to perform linear learning rate warmup for. "
"E.g., 0.1 = 10% of training.")
flags.DEFINE_integer("save_checkpoints_steps", 1000,
"How often to save the model checkpoint.")
flags.DEFINE_integer("iterations_per_loop", 1000,
"How many steps to make in each estimator call.")
flags.DEFINE_integer(
"n_best_size", 20,
"The total number of n-best predictions to generate in the "
"nbest_predictions.json output file.")
flags.DEFINE_integer(
"verbosity", 1, "How verbose our error messages should be")
flags.DEFINE_integer(
"max_answer_length", 30,
"The maximum length of an answer that can be generated. This is needed "
"because the start and end predictions are not conditioned on one another.")
flags.DEFINE_float(
"include_unknowns", -1.0,
"If positive, probability of including answers of type `UNKNOWN`.")
flags.DEFINE_bool("use_tpu", False, "Whether to use TPU or GPU/CPU.")
absl.flags.DEFINE_string(
"tpu_name", None,
"The Cloud TPU to use for training. This should be either the name "
"used when creating the Cloud TPU, or a grpc://ip.address.of.tpu:8470 "
"url.")
absl.flags.DEFINE_string(
"tpu_zone", None,
"[Optional] GCE zone where the Cloud TPU is located in. If not "
"specified, we will attempt to automatically detect the GCE project from "
"metadata.")
absl.flags.DEFINE_string(
"gcp_project", None,
"[Optional] Project name for the Cloud TPU-enabled project. If not "
"specified, we will attempt to automatically detect the GCE project from "
"metadata.")
absl.flags.DEFINE_string("master", None, "[Optional] TensorFlow master URL.")
flags.DEFINE_integer(
"num_tpu_cores", 8,
"Only used if `use_tpu` is True. Total number of TPU cores to use.")
flags.DEFINE_bool(
"verbose_logging", False,
"If true, all of the warnings related to data processing will be printed. "
"A number of warnings are expected for a normal NQ evaluation.")
flags.DEFINE_boolean(
"skip_nested_contexts", True,
"Completely ignore context that are not top level nodes in the page.")
flags.DEFINE_integer("task_id", 0,
"Train and dev shard to read from and write to.")
flags.DEFINE_integer("max_contexts", 48,
"Maximum number of contexts to output for an example.")
flags.DEFINE_integer(
"max_position", 50,
"Maximum context position for which to generate special tokens.")
flags.DEFINE_boolean(
"logtostderr", True,
"Logs to stderr")
flags.DEFINE_boolean("undefok", True, "it's okay to be undefined")
flags.DEFINE_string('f', '', 'kernel')
FLAGS = flags.FLAGS
TextSpan = collections.namedtuple("TextSpan", "token_positions text")
class AnswerType(enum.IntEnum):
"""Type of NQ answer."""
UNKNOWN = 0
YES = 1
NO = 2
SHORT = 3
LONG = 4
class Answer(collections.namedtuple("Answer", ["type", "text", "offset"])):
"""Answer record.
An Answer contains the type of the answer and possibly the text (for
long) as well as the offset (for extractive).
"""
def __new__(cls, type_, text=None, offset=None):
return super(Answer, cls).__new__(cls, type_, text, offset)
class NqExample(object):
"""A single training/test example."""
def __init__(self,
example_id,
qas_id,
questions,
doc_tokens,
doc_tokens_map=None,
answer=None,
start_position=None,
end_position=None):
self.example_id = example_id
self.qas_id = qas_id
self.questions = questions
self.doc_tokens = doc_tokens
self.doc_tokens_map = doc_tokens_map
self.answer = answer
self.start_position = start_position
self.end_position = end_position
def has_long_answer(a):
return (a["long_answer"]["start_token"] >= 0 and
a["long_answer"]["end_token"] >= 0)
def should_skip_context(e, idx):
if (FLAGS.skip_nested_contexts and
not e["long_answer_candidates"][idx]["top_level"]):
return True
elif not get_candidate_text(e, idx).text.strip():
# Skip empty contexts.
return True
else:
return False
def get_first_annotation(e):
"""Returns the first short or long answer in the example.
Args:
e: (dict) annotated example.
Returns:
annotation: (dict) selected annotation
annotated_idx: (int) index of the first annotated candidate.
annotated_sa: (tuple) char offset of the start and end token
of the short answer. The end token is exclusive.
"""
if "annotations" not in e:
return None, -1, (-1, -1)
positive_annotations = sorted(
[a for a in e["annotations"] if has_long_answer(a)],
key=lambda a: a["long_answer"]["candidate_index"])
for a in positive_annotations:
if a["short_answers"]:
idx = a["long_answer"]["candidate_index"]
start_token = a["short_answers"][0]["start_token"]
end_token = a["short_answers"][-1]["end_token"]
return a, idx, (token_to_char_offset(e, idx, start_token),
token_to_char_offset(e, idx, end_token) - 1)
for a in positive_annotations:
idx = a["long_answer"]["candidate_index"]
return a, idx, (-1, -1)
return None, -1, (-1, -1)
def get_text_span(example, span):
"""Returns the text in the example's document in the given token span."""
token_positions = []
tokens = []
for i in range(span["start_token"], span["end_token"]):
t = example["document_tokens"][i]
if not t["html_token"]:
token_positions.append(i)
token = t["token"].replace(" ", "")
tokens.append(token)
return TextSpan(token_positions, " ".join(tokens))
def token_to_char_offset(e, candidate_idx, token_idx):
"""Converts a token index to the char offset within the candidate."""
c = e["long_answer_candidates"][candidate_idx]
char_offset = 0
for i in range(c["start_token"], token_idx):
t = e["document_tokens"][i]
if not t["html_token"]:
token = t["token"].replace(" ", "")
char_offset += len(token) + 1
return char_offset
def get_candidate_type(e, idx):
"""Returns the candidate's type: Table, Paragraph, List or Other."""
c = e["long_answer_candidates"][idx]
first_token = e["document_tokens"][c["start_token"]]["token"]
if first_token == "<Table>":
return "Table"
elif first_token == "<P>":
return "Paragraph"
elif first_token in ("<Ul>", "<Dl>", "<Ol>"):
return "List"
elif first_token in ("<Tr>", "<Li>", "<Dd>", "<Dt>"):
return "Other"
else:
absl.logging.warning("Unknoww candidate type found: %s", first_token)
return "Other"
def add_candidate_types_and_positions(e):
"""Adds type and position info to each candidate in the document."""
counts = collections.defaultdict(int)
for idx, c in candidates_iter(e):
context_type = get_candidate_type(e, idx)
if counts[context_type] < FLAGS.max_position:
counts[context_type] += 1
c["type_and_position"] = "[%s=%d]" % (context_type, counts[context_type])
def get_candidate_type_and_position(e, idx):
"""Returns type and position info for the candidate at the given index."""
if idx == -1:
return "[NoLongAnswer]"
else:
return e["long_answer_candidates"][idx]["type_and_position"]
def get_candidate_text(e, idx):
"""Returns a text representation of the candidate at the given index."""
# No candidate at this index.
if idx < 0 or idx >= len(e["long_answer_candidates"]):
return TextSpan([], "")
# This returns an actual candidate.
return get_text_span(e, e["long_answer_candidates"][idx])
def candidates_iter(e):
"""Yield's the candidates that should not be skipped in an example."""
for idx, c in enumerate(e["long_answer_candidates"]):
if should_skip_context(e, idx):
continue
yield idx, c
def create_example_from_jsonl(line):
"""Creates an NQ example from a given line of JSON."""
e = json.loads(line, object_pairs_hook=collections.OrderedDict)
document_tokens = e["document_text"].split(" ")
e["document_tokens"] = []
for token in document_tokens:
e["document_tokens"].append({"token":token, "start_byte":-1, "end_byte":-1, "html_token":"<" in token})
add_candidate_types_and_positions(e)
annotation, annotated_idx, annotated_sa = get_first_annotation(e)
# annotated_idx: index of the first annotated context, -1 if null.
# annotated_sa: short answer start and end char offsets, (-1, -1) if null.
question = {"input_text": e["question_text"]}
answer = {
"candidate_id": annotated_idx,
"span_text": "",
"span_start": -1,
"span_end": -1,
"input_text": "long",
}
# Yes/no answers are added in the input text.
if annotation is not None:
assert annotation["yes_no_answer"] in ("YES", "NO", "NONE")
if annotation["yes_no_answer"] in ("YES", "NO"):
answer["input_text"] = annotation["yes_no_answer"].lower()
# Add a short answer if one was found.
if annotated_sa != (-1, -1):
answer["input_text"] = "short"
span_text = get_candidate_text(e, annotated_idx).text
answer["span_text"] = span_text[annotated_sa[0]:annotated_sa[1]]
answer["span_start"] = annotated_sa[0]
answer["span_end"] = annotated_sa[1]
expected_answer_text = get_text_span(
e, {
"start_token": annotation["short_answers"][0]["start_token"],
"end_token": annotation["short_answers"][-1]["end_token"],
}).text
assert expected_answer_text == answer["span_text"], (expected_answer_text,
answer["span_text"])
# Add a long answer if one was found.
elif annotation and annotation["long_answer"]["candidate_index"] >= 0:
answer["span_text"] = get_candidate_text(e, annotated_idx).text
answer["span_start"] = 0
answer["span_end"] = len(answer["span_text"])
context_idxs = [-1]
context_list = [{"id": -1, "type": get_candidate_type_and_position(e, -1)}]
context_list[-1]["text_map"], context_list[-1]["text"] = (
get_candidate_text(e, -1))
for idx, _ in candidates_iter(e):
context = {"id": idx, "type": get_candidate_type_and_position(e, idx)}
context["text_map"], context["text"] = get_candidate_text(e, idx)
context_idxs.append(idx)
context_list.append(context)
if len(context_list) >= FLAGS.max_contexts:
break
if "document_title" not in e:
e["document_title"] = e["example_id"]
# Assemble example.
example = {
"name": e["document_title"],
"id": str(e["example_id"]),
"questions": [question],
"answers": [answer],
"has_correct_context": annotated_idx in context_idxs
}
single_map = []
single_context = []
offset = 0
for context in context_list:
single_map.extend([-1, -1])
single_context.append("[ContextId=%d] %s" %
(context["id"], context["type"]))
offset += len(single_context[-1]) + 1
if context["id"] == annotated_idx:
answer["span_start"] += offset
answer["span_end"] += offset
# Many contexts are empty once the HTML tags have been stripped, so we
# want to skip those.
if context["text"]:
single_map.extend(context["text_map"])
single_context.append(context["text"])
offset += len(single_context[-1]) + 1
example["contexts"] = " ".join(single_context)
example["contexts_map"] = single_map
if annotated_idx in context_idxs:
expected = example["contexts"][answer["span_start"]:answer["span_end"]]
# This is a sanity check to ensure that the calculated start and end
# indices match the reported span text. If this assert fails, it is likely
# a bug in the data preparation code above.
assert expected == answer["span_text"], (expected, answer["span_text"])
return example
def make_nq_answer(contexts, answer):
"""Makes an Answer object following NQ conventions.
Args:
contexts: string containing the context
answer: dictionary with `span_start` and `input_text` fields
Returns:
an Answer object. If the Answer type is YES or NO or LONG, the text
of the answer is the long answer. If the answer type is UNKNOWN, the text of
the answer is empty.
"""
start = answer["span_start"]
end = answer["span_end"]
input_text = answer["input_text"]
if (answer["candidate_id"] == -1 or start >= len(contexts) or
end > len(contexts)):
answer_type = AnswerType.UNKNOWN
start = 0
end = 1
elif input_text.lower() == "yes":
answer_type = AnswerType.YES
elif input_text.lower() == "no":
answer_type = AnswerType.NO
elif input_text.lower() == "long":
answer_type = AnswerType.LONG
else:
answer_type = AnswerType.SHORT
return Answer(answer_type, text=contexts[start:end], offset=start)
def read_nq_entry(entry, is_training):
"""Converts a NQ entry into a list of NqExamples."""
def is_whitespace(c):
return c in " \t\r\n" or ord(c) == 0x202F
examples = []
contexts_id = entry["id"]
contexts = entry["contexts"]
doc_tokens = []
char_to_word_offset = []
prev_is_whitespace = True
for c in contexts:
if is_whitespace(c):
prev_is_whitespace = True
else:
if prev_is_whitespace:
doc_tokens.append(c)
else:
doc_tokens[-1] += c
prev_is_whitespace = False
char_to_word_offset.append(len(doc_tokens) - 1)
questions = []
for i, question in enumerate(entry["questions"]):
qas_id = "{}".format(contexts_id)
question_text = question["input_text"]
start_position = None
end_position = None
answer = None
if is_training:
answer_dict = entry["answers"][i]
answer = make_nq_answer(contexts, answer_dict)
# For now, only handle extractive, yes, and no.
if answer is None or answer.offset is None:
continue
start_position = char_to_word_offset[answer.offset]
end_position = char_to_word_offset[answer.offset + len(answer.text) - 1]
# Only add answers where the text can be exactly recovered from the
# document. If this CAN'T happen it's likely due to weird Unicode
# stuff so we will just skip the example.
#
# Note that this means for training mode, every example is NOT
# guaranteed to be preserved.
actual_text = " ".join(doc_tokens[start_position:(end_position + 1)])
cleaned_answer_text = " ".join(
tokenization.whitespace_tokenize(answer.text))
if actual_text.find(cleaned_answer_text) == -1:
absl.logging.warning("Could not find answer: '%s' vs. '%s'", actual_text, cleaned_answer_text)
continue
questions.append(question_text)
example = NqExample(
example_id=int(contexts_id),
qas_id=qas_id,
questions=questions[:],
doc_tokens=doc_tokens,
doc_tokens_map=entry.get("contexts_map", None),
answer=answer,
start_position=start_position,
end_position=end_position)
examples.append(example)
return examples
def convert_examples_to_features(examples, tokenizer, is_training, output_fn):
"""Converts a list of NqExamples into InputFeatures."""
num_spans_to_ids = collections.defaultdict(list)
for example in examples:
example_index = example.example_id
features = convert_single_example(example, tokenizer, is_training)
num_spans_to_ids[len(features)].append(example.qas_id)
for feature in features:
feature.example_index = example_index
feature.unique_id = feature.example_index + feature.doc_span_index
output_fn(feature)
return num_spans_to_ids
def check_is_max_context(doc_spans, cur_span_index, position):
"""Check if this is the 'max context' doc span for the token."""
# Because of the sliding window approach taken to scoring documents, a single
# token can appear in multiple documents. E.g.
# Doc: the man went to the store and bought a gallon of milk
# Span A: the man went to the
# Span B: to the store and bought
# Span C: and bought a gallon of
# ...
#
# Now the word 'bought' will have two scores from spans B and C. We only
# want to consider the score with "maximum context", which we define as
# the *minimum* of its left and right context (the *sum* of left and
# right context will always be the same, of course).
#
# In the example the maximum context for 'bought' would be span C since
# it has 1 left context and 3 right context, while span B has 4 left context
# and 0 right context.
best_score = None
best_span_index = None
for (span_index, doc_span) in enumerate(doc_spans):
end = doc_span.start + doc_span.length - 1
if position < doc_span.start:
continue
if position > end:
continue
num_left_context = position - doc_span.start
num_right_context = end - position
score = min(num_left_context, num_right_context) + 0.01 * doc_span.length
if best_score is None or score > best_score:
best_score = score
best_span_index = span_index
return cur_span_index == best_span_index
def convert_single_example(example, tokenizer, is_training):
"""Converts a single NqExample into a list of InputFeatures."""
tok_to_orig_index = []
orig_to_tok_index = []
all_doc_tokens = []
features = []
for (i, token) in enumerate(example.doc_tokens):
orig_to_tok_index.append(len(all_doc_tokens))
sub_tokens = tokenize(tokenizer, token)
tok_to_orig_index.extend([i] * len(sub_tokens))
all_doc_tokens.extend(sub_tokens)
# `tok_to_orig_index` maps wordpiece indices to indices of whitespace
# tokenized word tokens in the contexts. The word tokens might themselves
# correspond to word tokens in a larger document, with the mapping given
# by `doc_tokens_map`.
if example.doc_tokens_map:
tok_to_orig_index = [
example.doc_tokens_map[index] for index in tok_to_orig_index
]
# QUERY
query_tokens = []
query_tokens.append("[Q]")
query_tokens.extend(tokenize(tokenizer, example.questions[-1]))
if len(query_tokens) > FLAGS.max_query_length:
query_tokens = query_tokens[-FLAGS.max_query_length:]
# ANSWER
tok_start_position = 0
tok_end_position = 0
if is_training:
tok_start_position = orig_to_tok_index[example.start_position]
if example.end_position < len(example.doc_tokens) - 1:
tok_end_position = orig_to_tok_index[example.end_position + 1] - 1
else:
tok_end_position = len(all_doc_tokens) - 1
# The -3 accounts for [CLS], [SEP] and [SEP]
max_tokens_for_doc = FLAGS.max_seq_length - len(query_tokens) - 3
# We can have documents that are longer than the maximum sequence length.
# To deal with this we do a sliding window approach, where we take chunks
# of up to our max length with a stride of `doc_stride`.
_DocSpan = collections.namedtuple( # pylint: disable=invalid-name
"DocSpan", ["start", "length"])
doc_spans = []
start_offset = 0
while start_offset < len(all_doc_tokens):
length = len(all_doc_tokens) - start_offset
length = min(length, max_tokens_for_doc)
doc_spans.append(_DocSpan(start=start_offset, length=length))
if start_offset + length == len(all_doc_tokens):
break
start_offset += min(length, FLAGS.doc_stride)
for (doc_span_index, doc_span) in enumerate(doc_spans):
tokens = []
token_to_orig_map = {}
token_is_max_context = {}
segment_ids = []
tokens.append("[CLS]")
segment_ids.append(0)
tokens.extend(query_tokens)
segment_ids.extend([0] * len(query_tokens))
tokens.append("[SEP]")
segment_ids.append(0)
for i in range(doc_span.length):
split_token_index = doc_span.start + i
token_to_orig_map[len(tokens)] = tok_to_orig_index[split_token_index]
is_max_context = check_is_max_context(doc_spans, doc_span_index,
split_token_index)
token_is_max_context[len(tokens)] = is_max_context
tokens.append(all_doc_tokens[split_token_index])
segment_ids.append(1)
tokens.append("[SEP]")
segment_ids.append(1)
assert len(tokens) == len(segment_ids)
input_ids = tokenizer.convert_tokens_to_ids(tokens)
# The mask has 1 for real tokens and 0 for padding tokens. Only real
# tokens are attended to.
input_mask = [1] * len(input_ids)
# Zero-pad up to the sequence length.
padding = [0] * (FLAGS.max_seq_length - len(input_ids))
input_ids.extend(padding)
input_mask.extend(padding)
segment_ids.extend(padding)
assert len(input_ids) == FLAGS.max_seq_length
assert len(input_mask) == FLAGS.max_seq_length
assert len(segment_ids) == FLAGS.max_seq_length
start_position = None
end_position = None
answer_type = None
answer_text = ""
if is_training:
doc_start = doc_span.start
doc_end = doc_span.start + doc_span.length - 1
# For training, if our document chunk does not contain an annotation
# we throw it out, since there is nothing to predict.
contains_an_annotation = (
tok_start_position >= doc_start and tok_end_position <= doc_end)
if ((not contains_an_annotation) or
example.answer.type == AnswerType.UNKNOWN):
# If an example has unknown answer type or does not contain the answer
# span, then we only include it with probability --include_unknowns.
# When we include an example with unknown answer type, we set the first
# token of the passage to be the annotated short span.
if (FLAGS.include_unknowns < 0 or
random.random() > FLAGS.include_unknowns):
continue
start_position = 0
end_position = 0
answer_type = AnswerType.UNKNOWN
else:
doc_offset = len(query_tokens) + 2
start_position = tok_start_position - doc_start + doc_offset
end_position = tok_end_position - doc_start + doc_offset
answer_type = example.answer.type
answer_text = " ".join(tokens[start_position:(end_position + 1)])
feature = InputFeatures(
unique_id=-1,
example_index=-1,
doc_span_index=doc_span_index,
tokens=tokens,
token_to_orig_map=token_to_orig_map,
token_is_max_context=token_is_max_context,
input_ids=input_ids,
input_mask=input_mask,
segment_ids=segment_ids,
start_position=start_position,
end_position=end_position,
answer_text=answer_text,
answer_type=answer_type)
features.append(feature)
return features
# A special token in NQ is made of non-space chars enclosed in square brackets.
_SPECIAL_TOKENS_RE = re.compile(r"^\[[^ ]*\]$", re.UNICODE)
def tokenize(tokenizer, text, apply_basic_tokenization=False):
"""Tokenizes text, optionally looking up special tokens separately.
Args:
tokenizer: a tokenizer from bert.tokenization.FullTokenizer
text: text to tokenize
apply_basic_tokenization: If True, apply the basic tokenization. If False,
apply the full tokenization (basic + wordpiece).
Returns:
tokenized text.
A special token is any text with no spaces enclosed in square brackets with no
space, so we separate those out and look them up in the dictionary before
doing actual tokenization.
"""
tokenize_fn = tokenizer.tokenize
if apply_basic_tokenization:
tokenize_fn = tokenizer.basic_tokenizer.tokenize
tokens = []
for token in text.split(" "):
if _SPECIAL_TOKENS_RE.match(token):
if token in tokenizer.vocab:
tokens.append(token)
else:
tokens.append(tokenizer.wordpiece_tokenizer.unk_token)
else:
tokens.extend(tokenize_fn(token))
return tokens
class CreateTFExampleFn(object):
"""Functor for creating NQ tf.Examples."""
def __init__(self, is_training):
self.is_training = is_training
self.tokenizer = tokenization.FullTokenizer(
vocab_file=FLAGS.vocab_file, do_lower_case=FLAGS.do_lower_case)
def process(self, example):
"""Coverts an NQ example in a list of serialized tf examples."""
nq_examples = read_nq_entry(example, self.is_training)
input_features = []
for nq_example in nq_examples:
input_features.extend(
convert_single_example(nq_example, self.tokenizer, self.is_training))
for input_feature in input_features:
input_feature.example_index = int(example["id"])
input_feature.unique_id = (
input_feature.example_index + input_feature.doc_span_index)
def create_int_feature(values):
return tf.train.Feature(
int64_list=tf.train.Int64List(value=list(values)))
features = collections.OrderedDict()
features["unique_ids"] = create_int_feature([input_feature.unique_id])
features["input_ids"] = create_int_feature(input_feature.input_ids)
features["input_mask"] = create_int_feature(input_feature.input_mask)
features["segment_ids"] = create_int_feature(input_feature.segment_ids)
if self.is_training:
features["start_positions"] = create_int_feature(
[input_feature.start_position])
features["end_positions"] = create_int_feature(
[input_feature.end_position])
features["answer_types"] = create_int_feature(
[input_feature.answer_type])
else:
token_map = [-1] * len(input_feature.input_ids)
for k, v in input_feature.token_to_orig_map.items():
token_map[k] = v
features["token_map"] = create_int_feature(token_map)
yield tf.train.Example(features=tf.train.Features(
feature=features)).SerializeToString()
class InputFeatures(object):
"""A single set of features of data."""
def __init__(self,
unique_id,
example_index,
doc_span_index,
tokens,
token_to_orig_map,
token_is_max_context,
input_ids,
input_mask,
segment_ids,
start_position=None,
end_position=None,
answer_text="",
answer_type=AnswerType.SHORT):
self.unique_id = unique_id
self.example_index = example_index
self.doc_span_index = doc_span_index
self.tokens = tokens
self.token_to_orig_map = token_to_orig_map
self.token_is_max_context = token_is_max_context
self.input_ids = input_ids
self.input_mask = input_mask
self.segment_ids = segment_ids
self.start_position = start_position
self.end_position = end_position
self.answer_text = answer_text
self.answer_type = answer_type
def read_nq_examples(input_file, is_training):
"""Read a NQ json file into a list of NqExample."""
input_paths = tf.io.gfile.glob(input_file)
input_data = []
def _open(path):
if path.endswith(".gz"):
return gzip.GzipFile(fileobj=tf.io.gfile.GFile(path, "rb"))
else:
return tf.io.gfile.GFile(path, "r")
for path in input_paths:
absl.logging.info("Reading: %s", path)
with _open(path) as input_file:
for index, line in enumerate(input_file):
input_data.append(create_example_from_jsonl(line))
# if index > 100:
# break
examples = []
for entry in input_data:
examples.extend(read_nq_entry(entry, is_training))
return examples
def create_model(bert_config, is_training, input_ids, input_mask, segment_ids,
use_one_hot_embeddings):
"""Creates a classification model."""
pooled_output, sequence_output = modeling.BertModel(config=bert_config)(
input_word_ids=input_ids,
input_mask=input_mask,
input_type_ids=segment_ids)
# Get the logits for the start and end predictions.
final_hidden = sequence_output #get_sequence_output()
final_hidden_shape = modeling.get_shape_list(final_hidden, expected_rank=3)
batch_size = final_hidden_shape[0]
seq_length = final_hidden_shape[1]
hidden_size = final_hidden_shape[2]
output_weights = tf.Variable(initial_value=tf.random.truncated_normal(stddev=0.02, shape=[2, hidden_size]),
name="cls/nq/output_weights", shape=[2, hidden_size])
output_bias = tf.Variable(initial_value=tf.zeros(shape=[2]),
name="cls/nq/output_bias", shape=[2])
final_hidden_matrix = tf.reshape(final_hidden,
[batch_size * seq_length, hidden_size])
logits = tf.matmul(final_hidden_matrix, output_weights, transpose_b=True)
logits = tf.nn.bias_add(logits, output_bias)
logits = tf.reshape(logits, [batch_size, seq_length, 2])
logits = tf.transpose(a=logits, perm=[2, 0, 1])
unstacked_logits = tf.unstack(logits, axis=0)
(start_logits, end_logits) = (unstacked_logits[0], unstacked_logits[1])
# Get the logits for the answer type prediction.
answer_type_output_layer = pooled_output #model.get_pooled_output()
answer_type_hidden_size = answer_type_output_layer.shape[-1] #.value
num_answer_types = 5 # YES, NO, UNKNOWN, SHORT, LONG
answer_type_output_weights = tf.Variable(initial_value=tf.random.truncated_normal(stddev=0.02, shape=[num_answer_types, answer_type_hidden_size]),
name="answer_type_output_weights",
shape=[num_answer_types, answer_type_hidden_size])
answer_type_output_bias = tf.Variable(initial_value=tf.zeros(shape=[num_answer_types]),
name="answer_type_output_bias",
shape=[num_answer_types])
answer_type_logits = tf.matmul(
answer_type_output_layer, answer_type_output_weights, transpose_b=True)
answer_type_logits = tf.nn.bias_add(answer_type_logits,
answer_type_output_bias)
return (start_logits, end_logits, answer_type_logits)
def model_fn_builder(bert_config, init_checkpoint, learning_rate,
num_train_steps, num_warmup_steps, use_tpu,
use_one_hot_embeddings):
"""Returns `model_fn` closure for TPUEstimator."""
def model_fn(features, labels, mode, params): # pylint: disable=unused-argument
"""The `model_fn` for TPUEstimator."""
absl.logging.info("*** Features ***")
for name in sorted(features.keys()):
absl.logging.info(" name = %s, shape = %s" % (name, features[name].shape))
unique_ids = features["unique_ids"]
input_ids = features["input_ids"]
input_mask = features["input_mask"]
segment_ids = features["segment_ids"]
is_training = (mode == tf.estimator.ModeKeys.TRAIN)
(start_logits, end_logits, answer_type_logits) = create_model(
bert_config=bert_config,
is_training=is_training,
input_ids=input_ids,
input_mask=input_mask,
segment_ids=segment_ids,
use_one_hot_embeddings=use_one_hot_embeddings)
initialized_variable_names = {}
scaffold_fn = None
if init_checkpoint:
model_tf = tf.keras.Model()
checkpoint_tf = tf.train.Checkpoint(model=model_tf)
checkpoint_tf.restore(init_checkpoint)
output_spec = None
if mode == tf.estimator.ModeKeys.TRAIN:
seq_length = modeling.get_shape_list(input_ids)[1]
# Computes the loss for positions.
def compute_loss(logits, positions):
one_hot_positions = tf.one_hot(
positions, depth=seq_length, dtype=tf.float32)
log_probs = tf.nn.log_softmax(logits, axis=-1)