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

run_squad.py 45 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
  1. # coding=utf-8
  2. # Copyright 2018 The Google AI Language Team Authors.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. """Run BERT on SQuAD 1.1 and SQuAD 2.0."""
  16. from __future__ import absolute_import
  17. from __future__ import division
  18. from __future__ import print_function
  19. import collections
  20. import json
  21. import math
  22. import os
  23. import random
  24. import modeling
  25. import optimization
  26. import tokenization
  27. import six
  28. import tensorflow as tf
  29. flags = tf.flags
  30. FLAGS = flags.FLAGS
  31. ## Required parameters
  32. flags.DEFINE_string(
  33. "bert_config_file", None,
  34. "The config json file corresponding to the pre-trained BERT model. "
  35. "This specifies the model architecture.")
  36. flags.DEFINE_string("vocab_file", None,
  37. "The vocabulary file that the BERT model was trained on.")
  38. flags.DEFINE_string(
  39. "output_dir", None,
  40. "The output directory where the model checkpoints will be written.")
  41. ## Other parameters
  42. flags.DEFINE_string("train_file", None,
  43. "SQuAD json for training. E.g., train-v1.1.json")
  44. flags.DEFINE_string(
  45. "predict_file", None,
  46. "SQuAD json for predictions. E.g., dev-v1.1.json or test-v1.1.json")
  47. flags.DEFINE_string(
  48. "init_checkpoint", None,
  49. "Initial checkpoint (usually from a pre-trained BERT model).")
  50. flags.DEFINE_bool(
  51. "do_lower_case", True,
  52. "Whether to lower case the input text. Should be True for uncased "
  53. "models and False for cased models.")
  54. flags.DEFINE_integer(
  55. "max_seq_length", 384,
  56. "The maximum total input sequence length after WordPiece tokenization. "
  57. "Sequences longer than this will be truncated, and sequences shorter "
  58. "than this will be padded.")
  59. flags.DEFINE_integer(
  60. "doc_stride", 128,
  61. "When splitting up a long document into chunks, how much stride to "
  62. "take between chunks.")
  63. flags.DEFINE_integer(
  64. "max_query_length", 64,
  65. "The maximum number of tokens for the question. Questions longer than "
  66. "this will be truncated to this length.")
  67. flags.DEFINE_bool("do_train", False, "Whether to run training.")
  68. flags.DEFINE_bool("do_predict", False, "Whether to run eval on the dev set.")
  69. flags.DEFINE_integer("train_batch_size", 32, "Total batch size for training.")
  70. flags.DEFINE_integer("predict_batch_size", 8,
  71. "Total batch size for predictions.")
  72. flags.DEFINE_float("learning_rate", 5e-5, "The initial learning rate for Adam.")
  73. flags.DEFINE_float("num_train_epochs", 3.0,
  74. "Total number of training epochs to perform.")
  75. flags.DEFINE_float(
  76. "warmup_proportion", 0.1,
  77. "Proportion of training to perform linear learning rate warmup for. "
  78. "E.g., 0.1 = 10% of training.")
  79. flags.DEFINE_integer("save_checkpoints_steps", 1000,
  80. "How often to save the model checkpoint.")
  81. flags.DEFINE_integer("iterations_per_loop", 1000,
  82. "How many steps to make in each estimator call.")
  83. flags.DEFINE_integer(
  84. "n_best_size", 20,
  85. "The total number of n-best predictions to generate in the "
  86. "nbest_predictions.json output file.")
  87. flags.DEFINE_integer(
  88. "max_answer_length", 30,
  89. "The maximum length of an answer that can be generated. This is needed "
  90. "because the start and end predictions are not conditioned on one another.")
  91. flags.DEFINE_bool("use_tpu", False, "Whether to use TPU or GPU/CPU.")
  92. tf.flags.DEFINE_string(
  93. "tpu_name", None,
  94. "The Cloud TPU to use for training. This should be either the name "
  95. "used when creating the Cloud TPU, or a grpc://ip.address.of.tpu:8470 "
  96. "url.")
  97. tf.flags.DEFINE_string(
  98. "tpu_zone", None,
  99. "[Optional] GCE zone where the Cloud TPU is located in. If not "
  100. "specified, we will attempt to automatically detect the GCE project from "
  101. "metadata.")
  102. tf.flags.DEFINE_string(
  103. "gcp_project", None,
  104. "[Optional] Project name for the Cloud TPU-enabled project. If not "
  105. "specified, we will attempt to automatically detect the GCE project from "
  106. "metadata.")
  107. tf.flags.DEFINE_string("master", None, "[Optional] TensorFlow master URL.")
  108. flags.DEFINE_integer(
  109. "num_tpu_cores", 8,
  110. "Only used if `use_tpu` is True. Total number of TPU cores to use.")
  111. flags.DEFINE_bool(
  112. "verbose_logging", False,
  113. "If true, all of the warnings related to data processing will be printed. "
  114. "A number of warnings are expected for a normal SQuAD evaluation.")
  115. flags.DEFINE_bool(
  116. "version_2_with_negative", False,
  117. "If true, the SQuAD examples contain some that do not have an answer.")
  118. flags.DEFINE_float(
  119. "null_score_diff_threshold", 0.0,
  120. "If null_score - best_non_null is greater than the threshold predict null.")
  121. class SquadExample(object):
  122. """A single training/test example for simple sequence classification.
  123. For examples without an answer, the start and end position are -1.
  124. """
  125. def __init__(self,
  126. qas_id,
  127. question_text,
  128. doc_tokens,
  129. orig_answer_text=None,
  130. start_position=None,
  131. end_position=None,
  132. is_impossible=False):
  133. self.qas_id = qas_id
  134. self.question_text = question_text
  135. self.doc_tokens = doc_tokens
  136. self.orig_answer_text = orig_answer_text
  137. self.start_position = start_position
  138. self.end_position = end_position
  139. self.is_impossible = is_impossible
  140. def __str__(self):
  141. return self.__repr__()
  142. def __repr__(self):
  143. s = ""
  144. s += "qas_id: %s" % (tokenization.printable_text(self.qas_id))
  145. s += ", question_text: %s" % (
  146. tokenization.printable_text(self.question_text))
  147. s += ", doc_tokens: [%s]" % (" ".join(self.doc_tokens))
  148. if self.start_position:
  149. s += ", start_position: %d" % (self.start_position)
  150. if self.start_position:
  151. s += ", end_position: %d" % (self.end_position)
  152. if self.start_position:
  153. s += ", is_impossible: %r" % (self.is_impossible)
  154. return s
  155. class InputFeatures(object):
  156. """A single set of features of data."""
  157. def __init__(self,
  158. unique_id,
  159. example_index,
  160. doc_span_index,
  161. tokens,
  162. token_to_orig_map,
  163. token_is_max_context,
  164. input_ids,
  165. input_mask,
  166. segment_ids,
  167. start_position=None,
  168. end_position=None,
  169. is_impossible=None):
  170. self.unique_id = unique_id
  171. self.example_index = example_index
  172. self.doc_span_index = doc_span_index
  173. self.tokens = tokens
  174. self.token_to_orig_map = token_to_orig_map
  175. self.token_is_max_context = token_is_max_context
  176. self.input_ids = input_ids
  177. self.input_mask = input_mask
  178. self.segment_ids = segment_ids
  179. self.start_position = start_position
  180. self.end_position = end_position
  181. self.is_impossible = is_impossible
  182. def read_squad_examples(input_file, is_training):
  183. """Read a SQuAD json file into a list of SquadExample."""
  184. with tf.gfile.Open(input_file, "r") as reader:
  185. input_data = json.load(reader)["data"]
  186. def is_whitespace(c):
  187. if c == " " or c == "\t" or c == "\r" or c == "\n" or ord(c) == 0x202F:
  188. return True
  189. return False
  190. examples = []
  191. for entry in input_data:
  192. for paragraph in entry["paragraphs"]:
  193. paragraph_text = paragraph["context"]
  194. doc_tokens = []
  195. char_to_word_offset = []
  196. prev_is_whitespace = True
  197. for c in paragraph_text:
  198. if is_whitespace(c):
  199. prev_is_whitespace = True
  200. else:
  201. if prev_is_whitespace:
  202. doc_tokens.append(c)
  203. else:
  204. doc_tokens[-1] += c
  205. prev_is_whitespace = False
  206. char_to_word_offset.append(len(doc_tokens) - 1)
  207. for qa in paragraph["qas"]:
  208. qas_id = qa["id"]
  209. question_text = qa["question"]
  210. start_position = None
  211. end_position = None
  212. orig_answer_text = None
  213. is_impossible = False
  214. if is_training:
  215. if FLAGS.version_2_with_negative:
  216. is_impossible = qa["is_impossible"]
  217. if (len(qa["answers"]) != 1) and (not is_impossible):
  218. raise ValueError(
  219. "For training, each question should have exactly 1 answer.")
  220. if not is_impossible:
  221. answer = qa["answers"][0]
  222. orig_answer_text = answer["text"]
  223. answer_offset = answer["answer_start"]
  224. answer_length = len(orig_answer_text)
  225. start_position = char_to_word_offset[answer_offset]
  226. end_position = char_to_word_offset[answer_offset + answer_length -
  227. 1]
  228. # Only add answers where the text can be exactly recovered from the
  229. # document. If this CAN'T happen it's likely due to weird Unicode
  230. # stuff so we will just skip the example.
  231. #
  232. # Note that this means for training mode, every example is NOT
  233. # guaranteed to be preserved.
  234. actual_text = " ".join(
  235. doc_tokens[start_position:(end_position + 1)])
  236. cleaned_answer_text = " ".join(
  237. tokenization.whitespace_tokenize(orig_answer_text))
  238. if actual_text.find(cleaned_answer_text) == -1:
  239. tf.logging.warning("Could not find answer: '%s' vs. '%s'",
  240. actual_text, cleaned_answer_text)
  241. continue
  242. else:
  243. start_position = -1
  244. end_position = -1
  245. orig_answer_text = ""
  246. example = SquadExample(
  247. qas_id=qas_id,
  248. question_text=question_text,
  249. doc_tokens=doc_tokens,
  250. orig_answer_text=orig_answer_text,
  251. start_position=start_position,
  252. end_position=end_position,
  253. is_impossible=is_impossible)
  254. examples.append(example)
  255. return examples
  256. def convert_examples_to_features(examples, tokenizer, max_seq_length,
  257. doc_stride, max_query_length, is_training,
  258. output_fn):
  259. """Loads a data file into a list of `InputBatch`s."""
  260. unique_id = 1000000000
  261. for (example_index, example) in enumerate(examples):
  262. query_tokens = tokenizer.tokenize(example.question_text)
  263. if len(query_tokens) > max_query_length:
  264. query_tokens = query_tokens[0:max_query_length]
  265. tok_to_orig_index = []
  266. orig_to_tok_index = []
  267. all_doc_tokens = []
  268. for (i, token) in enumerate(example.doc_tokens):
  269. orig_to_tok_index.append(len(all_doc_tokens))
  270. sub_tokens = tokenizer.tokenize(token)
  271. for sub_token in sub_tokens:
  272. tok_to_orig_index.append(i)
  273. all_doc_tokens.append(sub_token)
  274. tok_start_position = None
  275. tok_end_position = None
  276. if is_training and example.is_impossible:
  277. tok_start_position = -1
  278. tok_end_position = -1
  279. if is_training and not example.is_impossible:
  280. tok_start_position = orig_to_tok_index[example.start_position]
  281. if example.end_position < len(example.doc_tokens) - 1:
  282. tok_end_position = orig_to_tok_index[example.end_position + 1] - 1
  283. else:
  284. tok_end_position = len(all_doc_tokens) - 1
  285. (tok_start_position, tok_end_position) = _improve_answer_span(
  286. all_doc_tokens, tok_start_position, tok_end_position, tokenizer,
  287. example.orig_answer_text)
  288. # The -3 accounts for [CLS], [SEP] and [SEP]
  289. max_tokens_for_doc = max_seq_length - len(query_tokens) - 3
  290. # We can have documents that are longer than the maximum sequence length.
  291. # To deal with this we do a sliding window approach, where we take chunks
  292. # of the up to our max length with a stride of `doc_stride`.
  293. _DocSpan = collections.namedtuple( # pylint: disable=invalid-name
  294. "DocSpan", ["start", "length"])
  295. doc_spans = []
  296. start_offset = 0
  297. while start_offset < len(all_doc_tokens):
  298. length = len(all_doc_tokens) - start_offset
  299. if length > max_tokens_for_doc:
  300. length = max_tokens_for_doc
  301. doc_spans.append(_DocSpan(start=start_offset, length=length))
  302. if start_offset + length == len(all_doc_tokens):
  303. break
  304. start_offset += min(length, doc_stride)
  305. for (doc_span_index, doc_span) in enumerate(doc_spans):
  306. tokens = []
  307. token_to_orig_map = {}
  308. token_is_max_context = {}
  309. segment_ids = []
  310. tokens.append("[CLS]")
  311. segment_ids.append(0)
  312. for token in query_tokens:
  313. tokens.append(token)
  314. segment_ids.append(0)
  315. tokens.append("[SEP]")
  316. segment_ids.append(0)
  317. for i in range(doc_span.length):
  318. split_token_index = doc_span.start + i
  319. token_to_orig_map[len(tokens)] = tok_to_orig_index[split_token_index]
  320. is_max_context = _check_is_max_context(doc_spans, doc_span_index,
  321. split_token_index)
  322. token_is_max_context[len(tokens)] = is_max_context
  323. tokens.append(all_doc_tokens[split_token_index])
  324. segment_ids.append(1)
  325. tokens.append("[SEP]")
  326. segment_ids.append(1)
  327. input_ids = tokenizer.convert_tokens_to_ids(tokens)
  328. # The mask has 1 for real tokens and 0 for padding tokens. Only real
  329. # tokens are attended to.
  330. input_mask = [1] * len(input_ids)
  331. # Zero-pad up to the sequence length.
  332. while len(input_ids) < max_seq_length:
  333. input_ids.append(0)
  334. input_mask.append(0)
  335. segment_ids.append(0)
  336. assert len(input_ids) == max_seq_length
  337. assert len(input_mask) == max_seq_length
  338. assert len(segment_ids) == max_seq_length
  339. start_position = None
  340. end_position = None
  341. if is_training and not example.is_impossible:
  342. # For training, if our document chunk does not contain an annotation
  343. # we throw it out, since there is nothing to predict.
  344. doc_start = doc_span.start
  345. doc_end = doc_span.start + doc_span.length - 1
  346. out_of_span = False
  347. if not (tok_start_position >= doc_start and
  348. tok_end_position <= doc_end):
  349. out_of_span = True
  350. if out_of_span:
  351. start_position = 0
  352. end_position = 0
  353. else:
  354. doc_offset = len(query_tokens) + 2
  355. start_position = tok_start_position - doc_start + doc_offset
  356. end_position = tok_end_position - doc_start + doc_offset
  357. if is_training and example.is_impossible:
  358. start_position = 0
  359. end_position = 0
  360. if example_index < 20:
  361. tf.logging.info("*** Example ***")
  362. tf.logging.info("unique_id: %s" % (unique_id))
  363. tf.logging.info("example_index: %s" % (example_index))
  364. tf.logging.info("doc_span_index: %s" % (doc_span_index))
  365. tf.logging.info("tokens: %s" % " ".join(
  366. [tokenization.printable_text(x) for x in tokens]))
  367. tf.logging.info("token_to_orig_map: %s" % " ".join(
  368. ["%d:%d" % (x, y) for (x, y) in six.iteritems(token_to_orig_map)]))
  369. tf.logging.info("token_is_max_context: %s" % " ".join([
  370. "%d:%s" % (x, y) for (x, y) in six.iteritems(token_is_max_context)
  371. ]))
  372. tf.logging.info("input_ids: %s" % " ".join([str(x) for x in input_ids]))
  373. tf.logging.info(
  374. "input_mask: %s" % " ".join([str(x) for x in input_mask]))
  375. tf.logging.info(
  376. "segment_ids: %s" % " ".join([str(x) for x in segment_ids]))
  377. if is_training and example.is_impossible:
  378. tf.logging.info("impossible example")
  379. if is_training and not example.is_impossible:
  380. answer_text = " ".join(tokens[start_position:(end_position + 1)])
  381. tf.logging.info("start_position: %d" % (start_position))
  382. tf.logging.info("end_position: %d" % (end_position))
  383. tf.logging.info(
  384. "answer: %s" % (tokenization.printable_text(answer_text)))
  385. feature = InputFeatures(
  386. unique_id=unique_id,
  387. example_index=example_index,
  388. doc_span_index=doc_span_index,
  389. tokens=tokens,
  390. token_to_orig_map=token_to_orig_map,
  391. token_is_max_context=token_is_max_context,
  392. input_ids=input_ids,
  393. input_mask=input_mask,
  394. segment_ids=segment_ids,
  395. start_position=start_position,
  396. end_position=end_position,
  397. is_impossible=example.is_impossible)
  398. # Run callback
  399. output_fn(feature)
  400. unique_id += 1
  401. def _improve_answer_span(doc_tokens, input_start, input_end, tokenizer,
  402. orig_answer_text):
  403. """Returns tokenized answer spans that better match the annotated answer."""
  404. # The SQuAD annotations are character based. We first project them to
  405. # whitespace-tokenized words. But then after WordPiece tokenization, we can
  406. # often find a "better match". For example:
  407. #
  408. # Question: What year was John Smith born?
  409. # Context: The leader was John Smith (1895-1943).
  410. # Answer: 1895
  411. #
  412. # The original whitespace-tokenized answer will be "(1895-1943).". However
  413. # after tokenization, our tokens will be "( 1895 - 1943 ) .". So we can match
  414. # the exact answer, 1895.
  415. #
  416. # However, this is not always possible. Consider the following:
  417. #
  418. # Question: What country is the top exporter of electornics?
  419. # Context: The Japanese electronics industry is the lagest in the world.
  420. # Answer: Japan
  421. #
  422. # In this case, the annotator chose "Japan" as a character sub-span of
  423. # the word "Japanese". Since our WordPiece tokenizer does not split
  424. # "Japanese", we just use "Japanese" as the annotation. This is fairly rare
  425. # in SQuAD, but does happen.
  426. tok_answer_text = " ".join(tokenizer.tokenize(orig_answer_text))
  427. for new_start in range(input_start, input_end + 1):
  428. for new_end in range(input_end, new_start - 1, -1):
  429. text_span = " ".join(doc_tokens[new_start:(new_end + 1)])
  430. if text_span == tok_answer_text:
  431. return (new_start, new_end)
  432. return (input_start, input_end)
  433. def _check_is_max_context(doc_spans, cur_span_index, position):
  434. """Check if this is the 'max context' doc span for the token."""
  435. # Because of the sliding window approach taken to scoring documents, a single
  436. # token can appear in multiple documents. E.g.
  437. # Doc: the man went to the store and bought a gallon of milk
  438. # Span A: the man went to the
  439. # Span B: to the store and bought
  440. # Span C: and bought a gallon of
  441. # ...
  442. #
  443. # Now the word 'bought' will have two scores from spans B and C. We only
  444. # want to consider the score with "maximum context", which we define as
  445. # the *minimum* of its left and right context (the *sum* of left and
  446. # right context will always be the same, of course).
  447. #
  448. # In the example the maximum context for 'bought' would be span C since
  449. # it has 1 left context and 3 right context, while span B has 4 left context
  450. # and 0 right context.
  451. best_score = None
  452. best_span_index = None
  453. for (span_index, doc_span) in enumerate(doc_spans):
  454. end = doc_span.start + doc_span.length - 1
  455. if position < doc_span.start:
  456. continue
  457. if position > end:
  458. continue
  459. num_left_context = position - doc_span.start
  460. num_right_context = end - position
  461. score = min(num_left_context, num_right_context) + 0.01 * doc_span.length
  462. if best_score is None or score > best_score:
  463. best_score = score
  464. best_span_index = span_index
  465. return cur_span_index == best_span_index
  466. def create_model(bert_config, is_training, input_ids, input_mask, segment_ids,
  467. use_one_hot_embeddings):
  468. """Creates a classification model."""
  469. model = modeling.BertModel(
  470. config=bert_config,
  471. is_training=is_training,
  472. input_ids=input_ids,
  473. input_mask=input_mask,
  474. token_type_ids=segment_ids,
  475. use_one_hot_embeddings=use_one_hot_embeddings)
  476. final_hidden = model.get_sequence_output()
  477. final_hidden_shape = modeling.get_shape_list(final_hidden, expected_rank=3)
  478. batch_size = final_hidden_shape[0]
  479. seq_length = final_hidden_shape[1]
  480. hidden_size = final_hidden_shape[2]
  481. output_weights = tf.get_variable(
  482. "cls/squad/output_weights", [2, hidden_size],
  483. initializer=tf.truncated_normal_initializer(stddev=0.02))
  484. output_bias = tf.get_variable(
  485. "cls/squad/output_bias", [2], initializer=tf.zeros_initializer())
  486. final_hidden_matrix = tf.reshape(final_hidden,
  487. [batch_size * seq_length, hidden_size])
  488. logits = tf.matmul(final_hidden_matrix, output_weights, transpose_b=True)
  489. logits = tf.nn.bias_add(logits, output_bias)
  490. logits = tf.reshape(logits, [batch_size, seq_length, 2])
  491. logits = tf.transpose(logits, [2, 0, 1])
  492. unstacked_logits = tf.unstack(logits, axis=0)
  493. (start_logits, end_logits) = (unstacked_logits[0], unstacked_logits[1])
  494. return (start_logits, end_logits)
  495. def model_fn_builder(bert_config, init_checkpoint, learning_rate,
  496. num_train_steps, num_warmup_steps, use_tpu,
  497. use_one_hot_embeddings):
  498. """Returns `model_fn` closure for TPUEstimator."""
  499. def model_fn(features, labels, mode, params): # pylint: disable=unused-argument
  500. """The `model_fn` for TPUEstimator."""
  501. tf.logging.info("*** Features ***")
  502. for name in sorted(features.keys()):
  503. tf.logging.info(" name = %s, shape = %s" % (name, features[name].shape))
  504. unique_ids = features["unique_ids"]
  505. input_ids = features["input_ids"]
  506. input_mask = features["input_mask"]
  507. segment_ids = features["segment_ids"]
  508. is_training = (mode == tf.estimator.ModeKeys.TRAIN)
  509. (start_logits, end_logits) = create_model(
  510. bert_config=bert_config,
  511. is_training=is_training,
  512. input_ids=input_ids,
  513. input_mask=input_mask,
  514. segment_ids=segment_ids,
  515. use_one_hot_embeddings=use_one_hot_embeddings)
  516. tvars = tf.trainable_variables()
  517. initialized_variable_names = {}
  518. scaffold_fn = None
  519. if init_checkpoint:
  520. (assignment_map, initialized_variable_names
  521. ) = modeling.get_assignment_map_from_checkpoint(tvars, init_checkpoint)
  522. if use_tpu:
  523. def tpu_scaffold():
  524. tf.train.init_from_checkpoint(init_checkpoint, assignment_map)
  525. return tf.train.Scaffold()
  526. scaffold_fn = tpu_scaffold
  527. else:
  528. tf.train.init_from_checkpoint(init_checkpoint, assignment_map)
  529. tf.logging.info("**** Trainable Variables ****")
  530. for var in tvars:
  531. init_string = ""
  532. if var.name in initialized_variable_names:
  533. init_string = ", *INIT_FROM_CKPT*"
  534. tf.logging.info(" name = %s, shape = %s%s", var.name, var.shape,
  535. init_string)
  536. output_spec = None
  537. if mode == tf.estimator.ModeKeys.TRAIN:
  538. seq_length = modeling.get_shape_list(input_ids)[1]
  539. def compute_loss(logits, positions):
  540. one_hot_positions = tf.one_hot(
  541. positions, depth=seq_length, dtype=tf.float32)
  542. log_probs = tf.nn.log_softmax(logits, axis=-1)
  543. loss = -tf.reduce_mean(
  544. tf.reduce_sum(one_hot_positions * log_probs, axis=-1))
  545. return loss
  546. start_positions = features["start_positions"]
  547. end_positions = features["end_positions"]
  548. start_loss = compute_loss(start_logits, start_positions)
  549. end_loss = compute_loss(end_logits, end_positions)
  550. total_loss = (start_loss + end_loss) / 2.0
  551. train_op = optimization.create_optimizer(
  552. total_loss, learning_rate, num_train_steps, num_warmup_steps, use_tpu)
  553. output_spec = tf.contrib.tpu.TPUEstimatorSpec(
  554. mode=mode,
  555. loss=total_loss,
  556. train_op=train_op,
  557. scaffold_fn=scaffold_fn)
  558. elif mode == tf.estimator.ModeKeys.PREDICT:
  559. predictions = {
  560. "unique_ids": unique_ids,
  561. "start_logits": start_logits,
  562. "end_logits": end_logits,
  563. }
  564. output_spec = tf.contrib.tpu.TPUEstimatorSpec(
  565. mode=mode, predictions=predictions, scaffold_fn=scaffold_fn)
  566. else:
  567. raise ValueError(
  568. "Only TRAIN and PREDICT modes are supported: %s" % (mode))
  569. return output_spec
  570. return model_fn
  571. def input_fn_builder(input_file, seq_length, is_training, drop_remainder):
  572. """Creates an `input_fn` closure to be passed to TPUEstimator."""
  573. name_to_features = {
  574. "unique_ids": tf.FixedLenFeature([], tf.int64),
  575. "input_ids": tf.FixedLenFeature([seq_length], tf.int64),
  576. "input_mask": tf.FixedLenFeature([seq_length], tf.int64),
  577. "segment_ids": tf.FixedLenFeature([seq_length], tf.int64),
  578. }
  579. if is_training:
  580. name_to_features["start_positions"] = tf.FixedLenFeature([], tf.int64)
  581. name_to_features["end_positions"] = tf.FixedLenFeature([], tf.int64)
  582. def _decode_record(record, name_to_features):
  583. """Decodes a record to a TensorFlow example."""
  584. example = tf.parse_single_example(record, name_to_features)
  585. # tf.Example only supports tf.int64, but the TPU only supports tf.int32.
  586. # So cast all int64 to int32.
  587. for name in list(example.keys()):
  588. t = example[name]
  589. if t.dtype == tf.int64:
  590. t = tf.to_int32(t)
  591. example[name] = t
  592. return example
  593. def input_fn(params):
  594. """The actual input function."""
  595. batch_size = params["batch_size"]
  596. # For training, we want a lot of parallel reading and shuffling.
  597. # For eval, we want no shuffling and parallel reading doesn't matter.
  598. d = tf.data.TFRecordDataset(input_file)
  599. if is_training:
  600. d = d.repeat()
  601. d = d.shuffle(buffer_size=100)
  602. d = d.apply(
  603. tf.contrib.data.map_and_batch(
  604. lambda record: _decode_record(record, name_to_features),
  605. batch_size=batch_size,
  606. drop_remainder=drop_remainder))
  607. return d
  608. return input_fn
  609. RawResult = collections.namedtuple("RawResult",
  610. ["unique_id", "start_logits", "end_logits"])
  611. def write_predictions(all_examples, all_features, all_results, n_best_size,
  612. max_answer_length, do_lower_case, output_prediction_file,
  613. output_nbest_file, output_null_log_odds_file):
  614. """Write final predictions to the json file and log-odds of null if needed."""
  615. tf.logging.info("Writing predictions to: %s" % (output_prediction_file))
  616. tf.logging.info("Writing nbest to: %s" % (output_nbest_file))
  617. example_index_to_features = collections.defaultdict(list)
  618. for feature in all_features:
  619. example_index_to_features[feature.example_index].append(feature)
  620. unique_id_to_result = {}
  621. for result in all_results:
  622. unique_id_to_result[result.unique_id] = result
  623. _PrelimPrediction = collections.namedtuple( # pylint: disable=invalid-name
  624. "PrelimPrediction",
  625. ["feature_index", "start_index", "end_index", "start_logit", "end_logit"])
  626. all_predictions = collections.OrderedDict()
  627. all_nbest_json = collections.OrderedDict()
  628. scores_diff_json = collections.OrderedDict()
  629. for (example_index, example) in enumerate(all_examples):
  630. features = example_index_to_features[example_index]
  631. prelim_predictions = []
  632. # keep track of the minimum score of null start+end of position 0
  633. score_null = 1000000 # large and positive
  634. min_null_feature_index = 0 # the paragraph slice with min mull score
  635. null_start_logit = 0 # the start logit at the slice with min null score
  636. null_end_logit = 0 # the end logit at the slice with min null score
  637. for (feature_index, feature) in enumerate(features):
  638. result = unique_id_to_result[feature.unique_id]
  639. start_indexes = _get_best_indexes(result.start_logits, n_best_size)
  640. end_indexes = _get_best_indexes(result.end_logits, n_best_size)
  641. # if we could have irrelevant answers, get the min score of irrelevant
  642. if FLAGS.version_2_with_negative:
  643. feature_null_score = result.start_logits[0] + result.end_logits[0]
  644. if feature_null_score < score_null:
  645. score_null = feature_null_score
  646. min_null_feature_index = feature_index
  647. null_start_logit = result.start_logits[0]
  648. null_end_logit = result.end_logits[0]
  649. for start_index in start_indexes:
  650. for end_index in end_indexes:
  651. # We could hypothetically create invalid predictions, e.g., predict
  652. # that the start of the span is in the question. We throw out all
  653. # invalid predictions.
  654. if start_index >= len(feature.tokens):
  655. continue
  656. if end_index >= len(feature.tokens):
  657. continue
  658. if start_index not in feature.token_to_orig_map:
  659. continue
  660. if end_index not in feature.token_to_orig_map:
  661. continue
  662. if not feature.token_is_max_context.get(start_index, False):
  663. continue
  664. if end_index < start_index:
  665. continue
  666. length = end_index - start_index + 1
  667. if length > max_answer_length:
  668. continue
  669. prelim_predictions.append(
  670. _PrelimPrediction(
  671. feature_index=feature_index,
  672. start_index=start_index,
  673. end_index=end_index,
  674. start_logit=result.start_logits[start_index],
  675. end_logit=result.end_logits[end_index]))
  676. if FLAGS.version_2_with_negative:
  677. prelim_predictions.append(
  678. _PrelimPrediction(
  679. feature_index=min_null_feature_index,
  680. start_index=0,
  681. end_index=0,
  682. start_logit=null_start_logit,
  683. end_logit=null_end_logit))
  684. prelim_predictions = sorted(
  685. prelim_predictions,
  686. key=lambda x: (x.start_logit + x.end_logit),
  687. reverse=True)
  688. _NbestPrediction = collections.namedtuple( # pylint: disable=invalid-name
  689. "NbestPrediction", ["text", "start_logit", "end_logit"])
  690. seen_predictions = {}
  691. nbest = []
  692. for pred in prelim_predictions:
  693. if len(nbest) >= n_best_size:
  694. break
  695. feature = features[pred.feature_index]
  696. if pred.start_index > 0: # this is a non-null prediction
  697. tok_tokens = feature.tokens[pred.start_index:(pred.end_index + 1)]
  698. orig_doc_start = feature.token_to_orig_map[pred.start_index]
  699. orig_doc_end = feature.token_to_orig_map[pred.end_index]
  700. orig_tokens = example.doc_tokens[orig_doc_start:(orig_doc_end + 1)]
  701. tok_text = " ".join(tok_tokens)
  702. # De-tokenize WordPieces that have been split off.
  703. tok_text = tok_text.replace(" ##", "")
  704. tok_text = tok_text.replace("##", "")
  705. # Clean whitespace
  706. tok_text = tok_text.strip()
  707. tok_text = " ".join(tok_text.split())
  708. orig_text = " ".join(orig_tokens)
  709. final_text = get_final_text(tok_text, orig_text, do_lower_case)
  710. if final_text in seen_predictions:
  711. continue
  712. seen_predictions[final_text] = True
  713. else:
  714. final_text = ""
  715. seen_predictions[final_text] = True
  716. nbest.append(
  717. _NbestPrediction(
  718. text=final_text,
  719. start_logit=pred.start_logit,
  720. end_logit=pred.end_logit))
  721. # if we didn't inlude the empty option in the n-best, inlcude it
  722. if FLAGS.version_2_with_negative:
  723. if "" not in seen_predictions:
  724. nbest.append(
  725. _NbestPrediction(
  726. text="", start_logit=null_start_logit,
  727. end_logit=null_end_logit))
  728. # In very rare edge cases we could have no valid predictions. So we
  729. # just create a nonce prediction in this case to avoid failure.
  730. if not nbest:
  731. nbest.append(
  732. _NbestPrediction(text="empty", start_logit=0.0, end_logit=0.0))
  733. assert len(nbest) >= 1
  734. total_scores = []
  735. best_non_null_entry = None
  736. for entry in nbest:
  737. total_scores.append(entry.start_logit + entry.end_logit)
  738. if not best_non_null_entry:
  739. if entry.text:
  740. best_non_null_entry = entry
  741. probs = _compute_softmax(total_scores)
  742. nbest_json = []
  743. for (i, entry) in enumerate(nbest):
  744. output = collections.OrderedDict()
  745. output["text"] = entry.text
  746. output["probability"] = probs[i]
  747. output["start_logit"] = entry.start_logit
  748. output["end_logit"] = entry.end_logit
  749. nbest_json.append(output)
  750. assert len(nbest_json) >= 1
  751. if not FLAGS.version_2_with_negative:
  752. all_predictions[example.qas_id] = nbest_json[0]["text"]
  753. else:
  754. # predict "" iff the null score - the score of best non-null > threshold
  755. score_diff = score_null - best_non_null_entry.start_logit - (
  756. best_non_null_entry.end_logit)
  757. scores_diff_json[example.qas_id] = score_diff
  758. if score_diff > FLAGS.null_score_diff_threshold:
  759. all_predictions[example.qas_id] = ""
  760. else:
  761. all_predictions[example.qas_id] = best_non_null_entry.text
  762. all_nbest_json[example.qas_id] = nbest_json
  763. with tf.gfile.GFile(output_prediction_file, "w") as writer:
  764. writer.write(json.dumps(all_predictions, indent=4) + "\n")
  765. with tf.gfile.GFile(output_nbest_file, "w") as writer:
  766. writer.write(json.dumps(all_nbest_json, indent=4) + "\n")
  767. if FLAGS.version_2_with_negative:
  768. with tf.gfile.GFile(output_null_log_odds_file, "w") as writer:
  769. writer.write(json.dumps(scores_diff_json, indent=4) + "\n")
  770. def get_final_text(pred_text, orig_text, do_lower_case):
  771. """Project the tokenized prediction back to the original text."""
  772. # When we created the data, we kept track of the alignment between original
  773. # (whitespace tokenized) tokens and our WordPiece tokenized tokens. So
  774. # now `orig_text` contains the span of our original text corresponding to the
  775. # span that we predicted.
  776. #
  777. # However, `orig_text` may contain extra characters that we don't want in
  778. # our prediction.
  779. #
  780. # For example, let's say:
  781. # pred_text = steve smith
  782. # orig_text = Steve Smith's
  783. #
  784. # We don't want to return `orig_text` because it contains the extra "'s".
  785. #
  786. # We don't want to return `pred_text` because it's already been normalized
  787. # (the SQuAD eval script also does punctuation stripping/lower casing but
  788. # our tokenizer does additional normalization like stripping accent
  789. # characters).
  790. #
  791. # What we really want to return is "Steve Smith".
  792. #
  793. # Therefore, we have to apply a semi-complicated alignment heruistic between
  794. # `pred_text` and `orig_text` to get a character-to-charcter alignment. This
  795. # can fail in certain cases in which case we just return `orig_text`.
  796. def _strip_spaces(text):
  797. ns_chars = []
  798. ns_to_s_map = collections.OrderedDict()
  799. for (i, c) in enumerate(text):
  800. if c == " ":
  801. continue
  802. ns_to_s_map[len(ns_chars)] = i
  803. ns_chars.append(c)
  804. ns_text = "".join(ns_chars)
  805. return (ns_text, ns_to_s_map)
  806. # We first tokenize `orig_text`, strip whitespace from the result
  807. # and `pred_text`, and check if they are the same length. If they are
  808. # NOT the same length, the heuristic has failed. If they are the same
  809. # length, we assume the characters are one-to-one aligned.
  810. tokenizer = tokenization.BasicTokenizer(do_lower_case=do_lower_case)
  811. tok_text = " ".join(tokenizer.tokenize(orig_text))
  812. start_position = tok_text.find(pred_text)
  813. if start_position == -1:
  814. if FLAGS.verbose_logging:
  815. tf.logging.info(
  816. "Unable to find text: '%s' in '%s'" % (pred_text, orig_text))
  817. return orig_text
  818. end_position = start_position + len(pred_text) - 1
  819. (orig_ns_text, orig_ns_to_s_map) = _strip_spaces(orig_text)
  820. (tok_ns_text, tok_ns_to_s_map) = _strip_spaces(tok_text)
  821. if len(orig_ns_text) != len(tok_ns_text):
  822. if FLAGS.verbose_logging:
  823. tf.logging.info("Length not equal after stripping spaces: '%s' vs '%s'",
  824. orig_ns_text, tok_ns_text)
  825. return orig_text
  826. # We then project the characters in `pred_text` back to `orig_text` using
  827. # the character-to-character alignment.
  828. tok_s_to_ns_map = {}
  829. for (i, tok_index) in six.iteritems(tok_ns_to_s_map):
  830. tok_s_to_ns_map[tok_index] = i
  831. orig_start_position = None
  832. if start_position in tok_s_to_ns_map:
  833. ns_start_position = tok_s_to_ns_map[start_position]
  834. if ns_start_position in orig_ns_to_s_map:
  835. orig_start_position = orig_ns_to_s_map[ns_start_position]
  836. if orig_start_position is None:
  837. if FLAGS.verbose_logging:
  838. tf.logging.info("Couldn't map start position")
  839. return orig_text
  840. orig_end_position = None
  841. if end_position in tok_s_to_ns_map:
  842. ns_end_position = tok_s_to_ns_map[end_position]
  843. if ns_end_position in orig_ns_to_s_map:
  844. orig_end_position = orig_ns_to_s_map[ns_end_position]
  845. if orig_end_position is None:
  846. if FLAGS.verbose_logging:
  847. tf.logging.info("Couldn't map end position")
  848. return orig_text
  849. output_text = orig_text[orig_start_position:(orig_end_position + 1)]
  850. return output_text
  851. def _get_best_indexes(logits, n_best_size):
  852. """Get the n-best logits from a list."""
  853. index_and_score = sorted(enumerate(logits), key=lambda x: x[1], reverse=True)
  854. best_indexes = []
  855. for i in range(len(index_and_score)):
  856. if i >= n_best_size:
  857. break
  858. best_indexes.append(index_and_score[i][0])
  859. return best_indexes
  860. def _compute_softmax(scores):
  861. """Compute softmax probability over raw logits."""
  862. if not scores:
  863. return []
  864. max_score = None
  865. for score in scores:
  866. if max_score is None or score > max_score:
  867. max_score = score
  868. exp_scores = []
  869. total_sum = 0.0
  870. for score in scores:
  871. x = math.exp(score - max_score)
  872. exp_scores.append(x)
  873. total_sum += x
  874. probs = []
  875. for score in exp_scores:
  876. probs.append(score / total_sum)
  877. return probs
  878. class FeatureWriter(object):
  879. """Writes InputFeature to TF example file."""
  880. def __init__(self, filename, is_training):
  881. self.filename = filename
  882. self.is_training = is_training
  883. self.num_features = 0
  884. self._writer = tf.python_io.TFRecordWriter(filename)
  885. def process_feature(self, feature):
  886. """Write a InputFeature to the TFRecordWriter as a tf.train.Example."""
  887. self.num_features += 1
  888. def create_int_feature(values):
  889. feature = tf.train.Feature(
  890. int64_list=tf.train.Int64List(value=list(values)))
  891. return feature
  892. features = collections.OrderedDict()
  893. features["unique_ids"] = create_int_feature([feature.unique_id])
  894. features["input_ids"] = create_int_feature(feature.input_ids)
  895. features["input_mask"] = create_int_feature(feature.input_mask)
  896. features["segment_ids"] = create_int_feature(feature.segment_ids)
  897. if self.is_training:
  898. features["start_positions"] = create_int_feature([feature.start_position])
  899. features["end_positions"] = create_int_feature([feature.end_position])
  900. impossible = 0
  901. if feature.is_impossible:
  902. impossible = 1
  903. features["is_impossible"] = create_int_feature([impossible])
  904. tf_example = tf.train.Example(features=tf.train.Features(feature=features))
  905. self._writer.write(tf_example.SerializeToString())
  906. def close(self):
  907. self._writer.close()
  908. def validate_flags_or_throw(bert_config):
  909. """Validate the input FLAGS or throw an exception."""
  910. tokenization.validate_case_matches_checkpoint(FLAGS.do_lower_case,
  911. FLAGS.init_checkpoint)
  912. if not FLAGS.do_train and not FLAGS.do_predict:
  913. raise ValueError("At least one of `do_train` or `do_predict` must be True.")
  914. if FLAGS.do_train:
  915. if not FLAGS.train_file:
  916. raise ValueError(
  917. "If `do_train` is True, then `train_file` must be specified.")
  918. if FLAGS.do_predict:
  919. if not FLAGS.predict_file:
  920. raise ValueError(
  921. "If `do_predict` is True, then `predict_file` must be specified.")
  922. if FLAGS.max_seq_length > bert_config.max_position_embeddings:
  923. raise ValueError(
  924. "Cannot use sequence length %d because the BERT model "
  925. "was only trained up to sequence length %d" %
  926. (FLAGS.max_seq_length, bert_config.max_position_embeddings))
  927. if FLAGS.max_seq_length <= FLAGS.max_query_length + 3:
  928. raise ValueError(
  929. "The max_seq_length (%d) must be greater than max_query_length "
  930. "(%d) + 3" % (FLAGS.max_seq_length, FLAGS.max_query_length))
  931. def main(_):
  932. tf.logging.set_verbosity(tf.logging.INFO)
  933. bert_config = modeling.BertConfig.from_json_file(FLAGS.bert_config_file)
  934. validate_flags_or_throw(bert_config)
  935. tf.gfile.MakeDirs(FLAGS.output_dir)
  936. tokenizer = tokenization.FullTokenizer(
  937. vocab_file=FLAGS.vocab_file, do_lower_case=FLAGS.do_lower_case)
  938. tpu_cluster_resolver = None
  939. if FLAGS.use_tpu and FLAGS.tpu_name:
  940. tpu_cluster_resolver = tf.contrib.cluster_resolver.TPUClusterResolver(
  941. FLAGS.tpu_name, zone=FLAGS.tpu_zone, project=FLAGS.gcp_project)
  942. is_per_host = tf.contrib.tpu.InputPipelineConfig.PER_HOST_V2
  943. run_config = tf.contrib.tpu.RunConfig(
  944. cluster=tpu_cluster_resolver,
  945. master=FLAGS.master,
  946. model_dir=FLAGS.output_dir,
  947. save_checkpoints_steps=FLAGS.save_checkpoints_steps,
  948. tpu_config=tf.contrib.tpu.TPUConfig(
  949. iterations_per_loop=FLAGS.iterations_per_loop,
  950. num_shards=FLAGS.num_tpu_cores,
  951. per_host_input_for_training=is_per_host))
  952. train_examples = None
  953. num_train_steps = None
  954. num_warmup_steps = None
  955. if FLAGS.do_train:
  956. train_examples = read_squad_examples(
  957. input_file=FLAGS.train_file, is_training=True)
  958. num_train_steps = int(
  959. len(train_examples) / FLAGS.train_batch_size * FLAGS.num_train_epochs)
  960. num_warmup_steps = int(num_train_steps * FLAGS.warmup_proportion)
  961. # Pre-shuffle the input to avoid having to make a very large shuffle
  962. # buffer in in the `input_fn`.
  963. rng = random.Random(12345)
  964. rng.shuffle(train_examples)
  965. model_fn = model_fn_builder(
  966. bert_config=bert_config,
  967. init_checkpoint=FLAGS.init_checkpoint,
  968. learning_rate=FLAGS.learning_rate,
  969. num_train_steps=num_train_steps,
  970. num_warmup_steps=num_warmup_steps,
  971. use_tpu=FLAGS.use_tpu,
  972. use_one_hot_embeddings=FLAGS.use_tpu)
  973. # If TPU is not available, this will fall back to normal Estimator on CPU
  974. # or GPU.
  975. estimator = tf.contrib.tpu.TPUEstimator(
  976. use_tpu=FLAGS.use_tpu,
  977. model_fn=model_fn,
  978. config=run_config,
  979. train_batch_size=FLAGS.train_batch_size,
  980. predict_batch_size=FLAGS.predict_batch_size)
  981. if FLAGS.do_train:
  982. # We write to a temporary file to avoid storing very large constant tensors
  983. # in memory.
  984. train_writer = FeatureWriter(
  985. filename=os.path.join(FLAGS.output_dir, "train.tf_record"),
  986. is_training=True)
  987. convert_examples_to_features(
  988. examples=train_examples,
  989. tokenizer=tokenizer,
  990. max_seq_length=FLAGS.max_seq_length,
  991. doc_stride=FLAGS.doc_stride,
  992. max_query_length=FLAGS.max_query_length,
  993. is_training=True,
  994. output_fn=train_writer.process_feature)
  995. train_writer.close()
  996. tf.logging.info("***** Running training *****")
  997. tf.logging.info(" Num orig examples = %d", len(train_examples))
  998. tf.logging.info(" Num split examples = %d", train_writer.num_features)
  999. tf.logging.info(" Batch size = %d", FLAGS.train_batch_size)
  1000. tf.logging.info(" Num steps = %d", num_train_steps)
  1001. del train_examples
  1002. train_input_fn = input_fn_builder(
  1003. input_file=train_writer.filename,
  1004. seq_length=FLAGS.max_seq_length,
  1005. is_training=True,
  1006. drop_remainder=True)
  1007. estimator.train(input_fn=train_input_fn, max_steps=num_train_steps)
  1008. if FLAGS.do_predict:
  1009. eval_examples = read_squad_examples(
  1010. input_file=FLAGS.predict_file, is_training=False)
  1011. eval_writer = FeatureWriter(
  1012. filename=os.path.join(FLAGS.output_dir, "eval.tf_record"),
  1013. is_training=False)
  1014. eval_features = []
  1015. def append_feature(feature):
  1016. eval_features.append(feature)
  1017. eval_writer.process_feature(feature)
  1018. convert_examples_to_features(
  1019. examples=eval_examples,
  1020. tokenizer=tokenizer,
  1021. max_seq_length=FLAGS.max_seq_length,
  1022. doc_stride=FLAGS.doc_stride,
  1023. max_query_length=FLAGS.max_query_length,
  1024. is_training=False,
  1025. output_fn=append_feature)
  1026. eval_writer.close()
  1027. tf.logging.info("***** Running predictions *****")
  1028. tf.logging.info(" Num orig examples = %d", len(eval_examples))
  1029. tf.logging.info(" Num split examples = %d", len(eval_features))
  1030. tf.logging.info(" Batch size = %d", FLAGS.predict_batch_size)
  1031. all_results = []
  1032. predict_input_fn = input_fn_builder(
  1033. input_file=eval_writer.filename,
  1034. seq_length=FLAGS.max_seq_length,
  1035. is_training=False,
  1036. drop_remainder=False)
  1037. # If running eval on the TPU, you will need to specify the number of
  1038. # steps.
  1039. all_results = []
  1040. for result in estimator.predict(
  1041. predict_input_fn, yield_single_examples=True):
  1042. if len(all_results) % 1000 == 0:
  1043. tf.logging.info("Processing example: %d" % (len(all_results)))
  1044. unique_id = int(result["unique_ids"])
  1045. start_logits = [float(x) for x in result["start_logits"].flat]
  1046. end_logits = [float(x) for x in result["end_logits"].flat]
  1047. all_results.append(
  1048. RawResult(
  1049. unique_id=unique_id,
  1050. start_logits=start_logits,
  1051. end_logits=end_logits))
  1052. output_prediction_file = os.path.join(FLAGS.output_dir, "predictions.json")
  1053. output_nbest_file = os.path.join(FLAGS.output_dir, "nbest_predictions.json")
  1054. output_null_log_odds_file = os.path.join(FLAGS.output_dir, "null_odds.json")
  1055. write_predictions(eval_examples, eval_features, all_results,
  1056. FLAGS.n_best_size, FLAGS.max_answer_length,
  1057. FLAGS.do_lower_case, output_prediction_file,
  1058. output_nbest_file, output_null_log_odds_file)
  1059. if __name__ == "__main__":
  1060. flags.mark_flag_as_required("vocab_file")
  1061. flags.mark_flag_as_required("bert_config_file")
  1062. flags.mark_flag_as_required("output_dir")
  1063. tf.app.run()
Tip!

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

Comments

Loading...