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_classifier.py 34 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
  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. """BERT finetuning runner."""
  16. from __future__ import absolute_import
  17. from __future__ import division
  18. from __future__ import print_function
  19. import collections
  20. import csv
  21. import os
  22. import modeling
  23. import optimization
  24. import tokenization
  25. import tensorflow as tf
  26. flags = tf.flags
  27. FLAGS = flags.FLAGS
  28. ## Required parameters
  29. flags.DEFINE_string(
  30. "data_dir", None,
  31. "The input data dir. Should contain the .tsv files (or other data files) "
  32. "for the task.")
  33. flags.DEFINE_string(
  34. "bert_config_file", None,
  35. "The config json file corresponding to the pre-trained BERT model. "
  36. "This specifies the model architecture.")
  37. flags.DEFINE_string("task_name", None, "The name of the task to train.")
  38. flags.DEFINE_string("vocab_file", None,
  39. "The vocabulary file that the BERT model was trained on.")
  40. flags.DEFINE_string(
  41. "output_dir", None,
  42. "The output directory where the model checkpoints will be written.")
  43. ## Other parameters
  44. flags.DEFINE_string(
  45. "init_checkpoint", None,
  46. "Initial checkpoint (usually from a pre-trained BERT model).")
  47. flags.DEFINE_bool(
  48. "do_lower_case", True,
  49. "Whether to lower case the input text. Should be True for uncased "
  50. "models and False for cased models.")
  51. flags.DEFINE_integer(
  52. "max_seq_length", 128,
  53. "The maximum total input sequence length after WordPiece tokenization. "
  54. "Sequences longer than this will be truncated, and sequences shorter "
  55. "than this will be padded.")
  56. flags.DEFINE_bool("do_train", False, "Whether to run training.")
  57. flags.DEFINE_bool("do_eval", False, "Whether to run eval on the dev set.")
  58. flags.DEFINE_bool(
  59. "do_predict", False,
  60. "Whether to run the model in inference mode on the test set.")
  61. flags.DEFINE_integer("train_batch_size", 32, "Total batch size for training.")
  62. flags.DEFINE_integer("eval_batch_size", 8, "Total batch size for eval.")
  63. flags.DEFINE_integer("predict_batch_size", 8, "Total batch size for predict.")
  64. flags.DEFINE_float("learning_rate", 5e-5, "The initial learning rate for Adam.")
  65. flags.DEFINE_float("num_train_epochs", 3.0,
  66. "Total number of training epochs to perform.")
  67. flags.DEFINE_float(
  68. "warmup_proportion", 0.1,
  69. "Proportion of training to perform linear learning rate warmup for. "
  70. "E.g., 0.1 = 10% of training.")
  71. flags.DEFINE_integer("save_checkpoints_steps", 1000,
  72. "How often to save the model checkpoint.")
  73. flags.DEFINE_integer("iterations_per_loop", 1000,
  74. "How many steps to make in each estimator call.")
  75. flags.DEFINE_bool("use_tpu", False, "Whether to use TPU or GPU/CPU.")
  76. tf.flags.DEFINE_string(
  77. "tpu_name", None,
  78. "The Cloud TPU to use for training. This should be either the name "
  79. "used when creating the Cloud TPU, or a grpc://ip.address.of.tpu:8470 "
  80. "url.")
  81. tf.flags.DEFINE_string(
  82. "tpu_zone", None,
  83. "[Optional] GCE zone where the Cloud TPU is located in. If not "
  84. "specified, we will attempt to automatically detect the GCE project from "
  85. "metadata.")
  86. tf.flags.DEFINE_string(
  87. "gcp_project", None,
  88. "[Optional] Project name for the Cloud TPU-enabled project. If not "
  89. "specified, we will attempt to automatically detect the GCE project from "
  90. "metadata.")
  91. tf.flags.DEFINE_string("master", None, "[Optional] TensorFlow master URL.")
  92. flags.DEFINE_integer(
  93. "num_tpu_cores", 8,
  94. "Only used if `use_tpu` is True. Total number of TPU cores to use.")
  95. class InputExample(object):
  96. """A single training/test example for simple sequence classification."""
  97. def __init__(self, guid, text_a, text_b=None, label=None):
  98. """Constructs a InputExample.
  99. Args:
  100. guid: Unique id for the example.
  101. text_a: string. The untokenized text of the first sequence. For single
  102. sequence tasks, only this sequence must be specified.
  103. text_b: (Optional) string. The untokenized text of the second sequence.
  104. Only must be specified for sequence pair tasks.
  105. label: (Optional) string. The label of the example. This should be
  106. specified for train and dev examples, but not for test examples.
  107. """
  108. self.guid = guid
  109. self.text_a = text_a
  110. self.text_b = text_b
  111. self.label = label
  112. class PaddingInputExample(object):
  113. """Fake example so the num input examples is a multiple of the batch size.
  114. When running eval/predict on the TPU, we need to pad the number of examples
  115. to be a multiple of the batch size, because the TPU requires a fixed batch
  116. size. The alternative is to drop the last batch, which is bad because it means
  117. the entire output data won't be generated.
  118. We use this class instead of `None` because treating `None` as padding
  119. battches could cause silent errors.
  120. """
  121. class InputFeatures(object):
  122. """A single set of features of data."""
  123. def __init__(self,
  124. input_ids,
  125. input_mask,
  126. segment_ids,
  127. label_id,
  128. is_real_example=True):
  129. self.input_ids = input_ids
  130. self.input_mask = input_mask
  131. self.segment_ids = segment_ids
  132. self.label_id = label_id
  133. self.is_real_example = is_real_example
  134. class DataProcessor(object):
  135. """Base class for data converters for sequence classification data sets."""
  136. def get_train_examples(self, data_dir):
  137. """Gets a collection of `InputExample`s for the train set."""
  138. raise NotImplementedError()
  139. def get_dev_examples(self, data_dir):
  140. """Gets a collection of `InputExample`s for the dev set."""
  141. raise NotImplementedError()
  142. def get_test_examples(self, data_dir):
  143. """Gets a collection of `InputExample`s for prediction."""
  144. raise NotImplementedError()
  145. def get_labels(self):
  146. """Gets the list of labels for this data set."""
  147. raise NotImplementedError()
  148. @classmethod
  149. def _read_tsv(cls, input_file, quotechar=None):
  150. """Reads a tab separated value file."""
  151. with tf.gfile.Open(input_file, "r") as f:
  152. reader = csv.reader(f, delimiter="\t", quotechar=quotechar)
  153. lines = []
  154. for line in reader:
  155. lines.append(line)
  156. return lines
  157. class XnliProcessor(DataProcessor):
  158. """Processor for the XNLI data set."""
  159. def __init__(self):
  160. self.language = "zh"
  161. def get_train_examples(self, data_dir):
  162. """See base class."""
  163. lines = self._read_tsv(
  164. os.path.join(data_dir, "multinli",
  165. "multinli.train.%s.tsv" % self.language))
  166. examples = []
  167. for (i, line) in enumerate(lines):
  168. if i == 0:
  169. continue
  170. guid = "train-%d" % (i)
  171. text_a = tokenization.convert_to_unicode(line[0])
  172. text_b = tokenization.convert_to_unicode(line[1])
  173. label = tokenization.convert_to_unicode(line[2])
  174. if label == tokenization.convert_to_unicode("contradictory"):
  175. label = tokenization.convert_to_unicode("contradiction")
  176. examples.append(
  177. InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))
  178. return examples
  179. def get_dev_examples(self, data_dir):
  180. """See base class."""
  181. lines = self._read_tsv(os.path.join(data_dir, "xnli.dev.tsv"))
  182. examples = []
  183. for (i, line) in enumerate(lines):
  184. if i == 0:
  185. continue
  186. guid = "dev-%d" % (i)
  187. language = tokenization.convert_to_unicode(line[0])
  188. if language != tokenization.convert_to_unicode(self.language):
  189. continue
  190. text_a = tokenization.convert_to_unicode(line[6])
  191. text_b = tokenization.convert_to_unicode(line[7])
  192. label = tokenization.convert_to_unicode(line[1])
  193. examples.append(
  194. InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))
  195. return examples
  196. def get_labels(self):
  197. """See base class."""
  198. return ["contradiction", "entailment", "neutral"]
  199. class MnliProcessor(DataProcessor):
  200. """Processor for the MultiNLI data set (GLUE version)."""
  201. def get_train_examples(self, data_dir):
  202. """See base class."""
  203. return self._create_examples(
  204. self._read_tsv(os.path.join(data_dir, "train.tsv")), "train")
  205. def get_dev_examples(self, data_dir):
  206. """See base class."""
  207. return self._create_examples(
  208. self._read_tsv(os.path.join(data_dir, "dev_matched.tsv")),
  209. "dev_matched")
  210. def get_test_examples(self, data_dir):
  211. """See base class."""
  212. return self._create_examples(
  213. self._read_tsv(os.path.join(data_dir, "test_matched.tsv")), "test")
  214. def get_labels(self):
  215. """See base class."""
  216. return ["contradiction", "entailment", "neutral"]
  217. def _create_examples(self, lines, set_type):
  218. """Creates examples for the training and dev sets."""
  219. examples = []
  220. for (i, line) in enumerate(lines):
  221. if i == 0:
  222. continue
  223. guid = "%s-%s" % (set_type, tokenization.convert_to_unicode(line[0]))
  224. text_a = tokenization.convert_to_unicode(line[8])
  225. text_b = tokenization.convert_to_unicode(line[9])
  226. if set_type == "test":
  227. label = "contradiction"
  228. else:
  229. label = tokenization.convert_to_unicode(line[-1])
  230. examples.append(
  231. InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))
  232. return examples
  233. class MrpcProcessor(DataProcessor):
  234. """Processor for the MRPC data set (GLUE version)."""
  235. def get_train_examples(self, data_dir):
  236. """See base class."""
  237. return self._create_examples(
  238. self._read_tsv(os.path.join(data_dir, "train.tsv")), "train")
  239. def get_dev_examples(self, data_dir):
  240. """See base class."""
  241. return self._create_examples(
  242. self._read_tsv(os.path.join(data_dir, "dev.tsv")), "dev")
  243. def get_test_examples(self, data_dir):
  244. """See base class."""
  245. return self._create_examples(
  246. self._read_tsv(os.path.join(data_dir, "test.tsv")), "test")
  247. def get_labels(self):
  248. """See base class."""
  249. return ["0", "1"]
  250. def _create_examples(self, lines, set_type):
  251. """Creates examples for the training and dev sets."""
  252. examples = []
  253. for (i, line) in enumerate(lines):
  254. if i == 0:
  255. continue
  256. guid = "%s-%s" % (set_type, i)
  257. text_a = tokenization.convert_to_unicode(line[3])
  258. text_b = tokenization.convert_to_unicode(line[4])
  259. if set_type == "test":
  260. label = "0"
  261. else:
  262. label = tokenization.convert_to_unicode(line[0])
  263. examples.append(
  264. InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))
  265. return examples
  266. class ColaProcessor(DataProcessor):
  267. """Processor for the CoLA data set (GLUE version)."""
  268. def get_train_examples(self, data_dir):
  269. """See base class."""
  270. return self._create_examples(
  271. self._read_tsv(os.path.join(data_dir, "train.tsv")), "train")
  272. def get_dev_examples(self, data_dir):
  273. """See base class."""
  274. return self._create_examples(
  275. self._read_tsv(os.path.join(data_dir, "dev.tsv")), "dev")
  276. def get_test_examples(self, data_dir):
  277. """See base class."""
  278. return self._create_examples(
  279. self._read_tsv(os.path.join(data_dir, "test.tsv")), "test")
  280. def get_labels(self):
  281. """See base class."""
  282. return ["0", "1"]
  283. def _create_examples(self, lines, set_type):
  284. """Creates examples for the training and dev sets."""
  285. examples = []
  286. for (i, line) in enumerate(lines):
  287. # Only the test set has a header
  288. if set_type == "test" and i == 0:
  289. continue
  290. guid = "%s-%s" % (set_type, i)
  291. if set_type == "test":
  292. text_a = tokenization.convert_to_unicode(line[1])
  293. label = "0"
  294. else:
  295. text_a = tokenization.convert_to_unicode(line[3])
  296. label = tokenization.convert_to_unicode(line[1])
  297. examples.append(
  298. InputExample(guid=guid, text_a=text_a, text_b=None, label=label))
  299. return examples
  300. def convert_single_example(ex_index, example, label_list, max_seq_length,
  301. tokenizer):
  302. """Converts a single `InputExample` into a single `InputFeatures`."""
  303. if isinstance(example, PaddingInputExample):
  304. return InputFeatures(
  305. input_ids=[0] * max_seq_length,
  306. input_mask=[0] * max_seq_length,
  307. segment_ids=[0] * max_seq_length,
  308. label_id=0,
  309. is_real_example=False)
  310. label_map = {}
  311. for (i, label) in enumerate(label_list):
  312. label_map[label] = i
  313. tokens_a = tokenizer.tokenize(example.text_a)
  314. tokens_b = None
  315. if example.text_b:
  316. tokens_b = tokenizer.tokenize(example.text_b)
  317. if tokens_b:
  318. # Modifies `tokens_a` and `tokens_b` in place so that the total
  319. # length is less than the specified length.
  320. # Account for [CLS], [SEP], [SEP] with "- 3"
  321. _truncate_seq_pair(tokens_a, tokens_b, max_seq_length - 3)
  322. else:
  323. # Account for [CLS] and [SEP] with "- 2"
  324. if len(tokens_a) > max_seq_length - 2:
  325. tokens_a = tokens_a[0:(max_seq_length - 2)]
  326. # The convention in BERT is:
  327. # (a) For sequence pairs:
  328. # tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP]
  329. # type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1
  330. # (b) For single sequences:
  331. # tokens: [CLS] the dog is hairy . [SEP]
  332. # type_ids: 0 0 0 0 0 0 0
  333. #
  334. # Where "type_ids" are used to indicate whether this is the first
  335. # sequence or the second sequence. The embedding vectors for `type=0` and
  336. # `type=1` were learned during pre-training and are added to the wordpiece
  337. # embedding vector (and position vector). This is not *strictly* necessary
  338. # since the [SEP] token unambiguously separates the sequences, but it makes
  339. # it easier for the model to learn the concept of sequences.
  340. #
  341. # For classification tasks, the first vector (corresponding to [CLS]) is
  342. # used as the "sentence vector". Note that this only makes sense because
  343. # the entire model is fine-tuned.
  344. tokens = []
  345. segment_ids = []
  346. tokens.append("[CLS]")
  347. segment_ids.append(0)
  348. for token in tokens_a:
  349. tokens.append(token)
  350. segment_ids.append(0)
  351. tokens.append("[SEP]")
  352. segment_ids.append(0)
  353. if tokens_b:
  354. for token in tokens_b:
  355. tokens.append(token)
  356. segment_ids.append(1)
  357. tokens.append("[SEP]")
  358. segment_ids.append(1)
  359. input_ids = tokenizer.convert_tokens_to_ids(tokens)
  360. # The mask has 1 for real tokens and 0 for padding tokens. Only real
  361. # tokens are attended to.
  362. input_mask = [1] * len(input_ids)
  363. # Zero-pad up to the sequence length.
  364. while len(input_ids) < max_seq_length:
  365. input_ids.append(0)
  366. input_mask.append(0)
  367. segment_ids.append(0)
  368. assert len(input_ids) == max_seq_length
  369. assert len(input_mask) == max_seq_length
  370. assert len(segment_ids) == max_seq_length
  371. label_id = label_map[example.label]
  372. if ex_index < 5:
  373. tf.logging.info("*** Example ***")
  374. tf.logging.info("guid: %s" % (example.guid))
  375. tf.logging.info("tokens: %s" % " ".join(
  376. [tokenization.printable_text(x) for x in tokens]))
  377. tf.logging.info("input_ids: %s" % " ".join([str(x) for x in input_ids]))
  378. tf.logging.info("input_mask: %s" % " ".join([str(x) for x in input_mask]))
  379. tf.logging.info("segment_ids: %s" % " ".join([str(x) for x in segment_ids]))
  380. tf.logging.info("label: %s (id = %d)" % (example.label, label_id))
  381. feature = InputFeatures(
  382. input_ids=input_ids,
  383. input_mask=input_mask,
  384. segment_ids=segment_ids,
  385. label_id=label_id,
  386. is_real_example=True)
  387. return feature
  388. def file_based_convert_examples_to_features(
  389. examples, label_list, max_seq_length, tokenizer, output_file):
  390. """Convert a set of `InputExample`s to a TFRecord file."""
  391. writer = tf.python_io.TFRecordWriter(output_file)
  392. for (ex_index, example) in enumerate(examples):
  393. if ex_index % 10000 == 0:
  394. tf.logging.info("Writing example %d of %d" % (ex_index, len(examples)))
  395. feature = convert_single_example(ex_index, example, label_list,
  396. max_seq_length, tokenizer)
  397. def create_int_feature(values):
  398. f = tf.train.Feature(int64_list=tf.train.Int64List(value=list(values)))
  399. return f
  400. features = collections.OrderedDict()
  401. features["input_ids"] = create_int_feature(feature.input_ids)
  402. features["input_mask"] = create_int_feature(feature.input_mask)
  403. features["segment_ids"] = create_int_feature(feature.segment_ids)
  404. features["label_ids"] = create_int_feature([feature.label_id])
  405. features["is_real_example"] = create_int_feature(
  406. [int(feature.is_real_example)])
  407. tf_example = tf.train.Example(features=tf.train.Features(feature=features))
  408. writer.write(tf_example.SerializeToString())
  409. writer.close()
  410. def file_based_input_fn_builder(input_file, seq_length, is_training,
  411. drop_remainder):
  412. """Creates an `input_fn` closure to be passed to TPUEstimator."""
  413. name_to_features = {
  414. "input_ids": tf.FixedLenFeature([seq_length], tf.int64),
  415. "input_mask": tf.FixedLenFeature([seq_length], tf.int64),
  416. "segment_ids": tf.FixedLenFeature([seq_length], tf.int64),
  417. "label_ids": tf.FixedLenFeature([], tf.int64),
  418. "is_real_example": tf.FixedLenFeature([], tf.int64),
  419. }
  420. def _decode_record(record, name_to_features):
  421. """Decodes a record to a TensorFlow example."""
  422. example = tf.parse_single_example(record, name_to_features)
  423. # tf.Example only supports tf.int64, but the TPU only supports tf.int32.
  424. # So cast all int64 to int32.
  425. for name in list(example.keys()):
  426. t = example[name]
  427. if t.dtype == tf.int64:
  428. t = tf.to_int32(t)
  429. example[name] = t
  430. return example
  431. def input_fn(params):
  432. """The actual input function."""
  433. batch_size = params["batch_size"]
  434. # For training, we want a lot of parallel reading and shuffling.
  435. # For eval, we want no shuffling and parallel reading doesn't matter.
  436. d = tf.data.TFRecordDataset(input_file)
  437. if is_training:
  438. d = d.repeat()
  439. d = d.shuffle(buffer_size=100)
  440. d = d.apply(
  441. tf.contrib.data.map_and_batch(
  442. lambda record: _decode_record(record, name_to_features),
  443. batch_size=batch_size,
  444. drop_remainder=drop_remainder))
  445. return d
  446. return input_fn
  447. def _truncate_seq_pair(tokens_a, tokens_b, max_length):
  448. """Truncates a sequence pair in place to the maximum length."""
  449. # This is a simple heuristic which will always truncate the longer sequence
  450. # one token at a time. This makes more sense than truncating an equal percent
  451. # of tokens from each, since if one sequence is very short then each token
  452. # that's truncated likely contains more information than a longer sequence.
  453. while True:
  454. total_length = len(tokens_a) + len(tokens_b)
  455. if total_length <= max_length:
  456. break
  457. if len(tokens_a) > len(tokens_b):
  458. tokens_a.pop()
  459. else:
  460. tokens_b.pop()
  461. def create_model(bert_config, is_training, input_ids, input_mask, segment_ids,
  462. labels, num_labels, use_one_hot_embeddings):
  463. """Creates a classification model."""
  464. model = modeling.BertModel(
  465. config=bert_config,
  466. is_training=is_training,
  467. input_ids=input_ids,
  468. input_mask=input_mask,
  469. token_type_ids=segment_ids,
  470. use_one_hot_embeddings=use_one_hot_embeddings)
  471. # In the demo, we are doing a simple classification task on the entire
  472. # segment.
  473. #
  474. # If you want to use the token-level output, use model.get_sequence_output()
  475. # instead.
  476. output_layer = model.get_pooled_output()
  477. hidden_size = output_layer.shape[-1].value
  478. output_weights = tf.get_variable(
  479. "output_weights", [num_labels, hidden_size],
  480. initializer=tf.truncated_normal_initializer(stddev=0.02))
  481. output_bias = tf.get_variable(
  482. "output_bias", [num_labels], initializer=tf.zeros_initializer())
  483. with tf.variable_scope("loss"):
  484. if is_training:
  485. # I.e., 0.1 dropout
  486. output_layer = tf.nn.dropout(output_layer, keep_prob=0.9)
  487. logits = tf.matmul(output_layer, output_weights, transpose_b=True)
  488. logits = tf.nn.bias_add(logits, output_bias)
  489. probabilities = tf.nn.softmax(logits, axis=-1)
  490. log_probs = tf.nn.log_softmax(logits, axis=-1)
  491. one_hot_labels = tf.one_hot(labels, depth=num_labels, dtype=tf.float32)
  492. per_example_loss = -tf.reduce_sum(one_hot_labels * log_probs, axis=-1)
  493. loss = tf.reduce_mean(per_example_loss)
  494. return (loss, per_example_loss, logits, probabilities)
  495. def model_fn_builder(bert_config, num_labels, 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. input_ids = features["input_ids"]
  505. input_mask = features["input_mask"]
  506. segment_ids = features["segment_ids"]
  507. label_ids = features["label_ids"]
  508. is_real_example = None
  509. if "is_real_example" in features:
  510. is_real_example = tf.cast(features["is_real_example"], dtype=tf.float32)
  511. else:
  512. is_real_example = tf.ones(tf.shape(label_ids), dtype=tf.float32)
  513. is_training = (mode == tf.estimator.ModeKeys.TRAIN)
  514. (total_loss, per_example_loss, logits, probabilities) = create_model(
  515. bert_config, is_training, input_ids, input_mask, segment_ids, label_ids,
  516. num_labels, use_one_hot_embeddings)
  517. tvars = tf.trainable_variables()
  518. initialized_variable_names = {}
  519. scaffold_fn = None
  520. if init_checkpoint:
  521. (assignment_map, initialized_variable_names
  522. ) = modeling.get_assignment_map_from_checkpoint(tvars, init_checkpoint)
  523. if use_tpu:
  524. def tpu_scaffold():
  525. tf.train.init_from_checkpoint(init_checkpoint, assignment_map)
  526. return tf.train.Scaffold()
  527. scaffold_fn = tpu_scaffold
  528. else:
  529. tf.train.init_from_checkpoint(init_checkpoint, assignment_map)
  530. tf.logging.info("**** Trainable Variables ****")
  531. for var in tvars:
  532. init_string = ""
  533. if var.name in initialized_variable_names:
  534. init_string = ", *INIT_FROM_CKPT*"
  535. tf.logging.info(" name = %s, shape = %s%s", var.name, var.shape,
  536. init_string)
  537. output_spec = None
  538. if mode == tf.estimator.ModeKeys.TRAIN:
  539. train_op = optimization.create_optimizer(
  540. total_loss, learning_rate, num_train_steps, num_warmup_steps, use_tpu)
  541. output_spec = tf.contrib.tpu.TPUEstimatorSpec(
  542. mode=mode,
  543. loss=total_loss,
  544. train_op=train_op,
  545. scaffold_fn=scaffold_fn)
  546. elif mode == tf.estimator.ModeKeys.EVAL:
  547. def metric_fn(per_example_loss, label_ids, logits, is_real_example):
  548. predictions = tf.argmax(logits, axis=-1, output_type=tf.int32)
  549. accuracy = tf.metrics.accuracy(
  550. labels=label_ids, predictions=predictions, weights=is_real_example)
  551. loss = tf.metrics.mean(values=per_example_loss, weights=is_real_example)
  552. return {
  553. "eval_accuracy": accuracy,
  554. "eval_loss": loss,
  555. }
  556. eval_metrics = (metric_fn,
  557. [per_example_loss, label_ids, logits, is_real_example])
  558. output_spec = tf.contrib.tpu.TPUEstimatorSpec(
  559. mode=mode,
  560. loss=total_loss,
  561. eval_metrics=eval_metrics,
  562. scaffold_fn=scaffold_fn)
  563. else:
  564. output_spec = tf.contrib.tpu.TPUEstimatorSpec(
  565. mode=mode,
  566. predictions={"probabilities": probabilities},
  567. scaffold_fn=scaffold_fn)
  568. return output_spec
  569. return model_fn
  570. # This function is not used by this file but is still used by the Colab and
  571. # people who depend on it.
  572. def input_fn_builder(features, seq_length, is_training, drop_remainder):
  573. """Creates an `input_fn` closure to be passed to TPUEstimator."""
  574. all_input_ids = []
  575. all_input_mask = []
  576. all_segment_ids = []
  577. all_label_ids = []
  578. for feature in features:
  579. all_input_ids.append(feature.input_ids)
  580. all_input_mask.append(feature.input_mask)
  581. all_segment_ids.append(feature.segment_ids)
  582. all_label_ids.append(feature.label_id)
  583. def input_fn(params):
  584. """The actual input function."""
  585. batch_size = params["batch_size"]
  586. num_examples = len(features)
  587. # This is for demo purposes and does NOT scale to large data sets. We do
  588. # not use Dataset.from_generator() because that uses tf.py_func which is
  589. # not TPU compatible. The right way to load data is with TFRecordReader.
  590. d = tf.data.Dataset.from_tensor_slices({
  591. "input_ids":
  592. tf.constant(
  593. all_input_ids, shape=[num_examples, seq_length],
  594. dtype=tf.int32),
  595. "input_mask":
  596. tf.constant(
  597. all_input_mask,
  598. shape=[num_examples, seq_length],
  599. dtype=tf.int32),
  600. "segment_ids":
  601. tf.constant(
  602. all_segment_ids,
  603. shape=[num_examples, seq_length],
  604. dtype=tf.int32),
  605. "label_ids":
  606. tf.constant(all_label_ids, shape=[num_examples], dtype=tf.int32),
  607. })
  608. if is_training:
  609. d = d.repeat()
  610. d = d.shuffle(buffer_size=100)
  611. d = d.batch(batch_size=batch_size, drop_remainder=drop_remainder)
  612. return d
  613. return input_fn
  614. # This function is not used by this file but is still used by the Colab and
  615. # people who depend on it.
  616. def convert_examples_to_features(examples, label_list, max_seq_length,
  617. tokenizer):
  618. """Convert a set of `InputExample`s to a list of `InputFeatures`."""
  619. features = []
  620. for (ex_index, example) in enumerate(examples):
  621. if ex_index % 10000 == 0:
  622. tf.logging.info("Writing example %d of %d" % (ex_index, len(examples)))
  623. feature = convert_single_example(ex_index, example, label_list,
  624. max_seq_length, tokenizer)
  625. features.append(feature)
  626. return features
  627. def main(_):
  628. tf.logging.set_verbosity(tf.logging.INFO)
  629. processors = {
  630. "cola": ColaProcessor,
  631. "mnli": MnliProcessor,
  632. "mrpc": MrpcProcessor,
  633. "xnli": XnliProcessor,
  634. }
  635. tokenization.validate_case_matches_checkpoint(FLAGS.do_lower_case,
  636. FLAGS.init_checkpoint)
  637. if not FLAGS.do_train and not FLAGS.do_eval and not FLAGS.do_predict:
  638. raise ValueError(
  639. "At least one of `do_train`, `do_eval` or `do_predict' must be True.")
  640. bert_config = modeling.BertConfig.from_json_file(FLAGS.bert_config_file)
  641. if FLAGS.max_seq_length > bert_config.max_position_embeddings:
  642. raise ValueError(
  643. "Cannot use sequence length %d because the BERT model "
  644. "was only trained up to sequence length %d" %
  645. (FLAGS.max_seq_length, bert_config.max_position_embeddings))
  646. tf.gfile.MakeDirs(FLAGS.output_dir)
  647. task_name = FLAGS.task_name.lower()
  648. if task_name not in processors:
  649. raise ValueError("Task not found: %s" % (task_name))
  650. processor = processors[task_name]()
  651. label_list = processor.get_labels()
  652. tokenizer = tokenization.FullTokenizer(
  653. vocab_file=FLAGS.vocab_file, do_lower_case=FLAGS.do_lower_case)
  654. tpu_cluster_resolver = None
  655. if FLAGS.use_tpu and FLAGS.tpu_name:
  656. tpu_cluster_resolver = tf.contrib.cluster_resolver.TPUClusterResolver(
  657. FLAGS.tpu_name, zone=FLAGS.tpu_zone, project=FLAGS.gcp_project)
  658. is_per_host = tf.contrib.tpu.InputPipelineConfig.PER_HOST_V2
  659. run_config = tf.contrib.tpu.RunConfig(
  660. cluster=tpu_cluster_resolver,
  661. master=FLAGS.master,
  662. model_dir=FLAGS.output_dir,
  663. save_checkpoints_steps=FLAGS.save_checkpoints_steps,
  664. tpu_config=tf.contrib.tpu.TPUConfig(
  665. iterations_per_loop=FLAGS.iterations_per_loop,
  666. num_shards=FLAGS.num_tpu_cores,
  667. per_host_input_for_training=is_per_host))
  668. train_examples = None
  669. num_train_steps = None
  670. num_warmup_steps = None
  671. if FLAGS.do_train:
  672. train_examples = processor.get_train_examples(FLAGS.data_dir)
  673. num_train_steps = int(
  674. len(train_examples) / FLAGS.train_batch_size * FLAGS.num_train_epochs)
  675. num_warmup_steps = int(num_train_steps * FLAGS.warmup_proportion)
  676. model_fn = model_fn_builder(
  677. bert_config=bert_config,
  678. num_labels=len(label_list),
  679. init_checkpoint=FLAGS.init_checkpoint,
  680. learning_rate=FLAGS.learning_rate,
  681. num_train_steps=num_train_steps,
  682. num_warmup_steps=num_warmup_steps,
  683. use_tpu=FLAGS.use_tpu,
  684. use_one_hot_embeddings=FLAGS.use_tpu)
  685. # If TPU is not available, this will fall back to normal Estimator on CPU
  686. # or GPU.
  687. estimator = tf.contrib.tpu.TPUEstimator(
  688. use_tpu=FLAGS.use_tpu,
  689. model_fn=model_fn,
  690. config=run_config,
  691. train_batch_size=FLAGS.train_batch_size,
  692. eval_batch_size=FLAGS.eval_batch_size,
  693. predict_batch_size=FLAGS.predict_batch_size)
  694. if FLAGS.do_train:
  695. train_file = os.path.join(FLAGS.output_dir, "train.tf_record")
  696. file_based_convert_examples_to_features(
  697. train_examples, label_list, FLAGS.max_seq_length, tokenizer, train_file)
  698. tf.logging.info("***** Running training *****")
  699. tf.logging.info(" Num examples = %d", len(train_examples))
  700. tf.logging.info(" Batch size = %d", FLAGS.train_batch_size)
  701. tf.logging.info(" Num steps = %d", num_train_steps)
  702. train_input_fn = file_based_input_fn_builder(
  703. input_file=train_file,
  704. seq_length=FLAGS.max_seq_length,
  705. is_training=True,
  706. drop_remainder=True)
  707. estimator.train(input_fn=train_input_fn, max_steps=num_train_steps)
  708. if FLAGS.do_eval:
  709. eval_examples = processor.get_dev_examples(FLAGS.data_dir)
  710. num_actual_eval_examples = len(eval_examples)
  711. if FLAGS.use_tpu:
  712. # TPU requires a fixed batch size for all batches, therefore the number
  713. # of examples must be a multiple of the batch size, or else examples
  714. # will get dropped. So we pad with fake examples which are ignored
  715. # later on. These do NOT count towards the metric (all tf.metrics
  716. # support a per-instance weight, and these get a weight of 0.0).
  717. while len(eval_examples) % FLAGS.eval_batch_size != 0:
  718. eval_examples.append(PaddingInputExample())
  719. eval_file = os.path.join(FLAGS.output_dir, "eval.tf_record")
  720. file_based_convert_examples_to_features(
  721. eval_examples, label_list, FLAGS.max_seq_length, tokenizer, eval_file)
  722. tf.logging.info("***** Running evaluation *****")
  723. tf.logging.info(" Num examples = %d (%d actual, %d padding)",
  724. len(eval_examples), num_actual_eval_examples,
  725. len(eval_examples) - num_actual_eval_examples)
  726. tf.logging.info(" Batch size = %d", FLAGS.eval_batch_size)
  727. # This tells the estimator to run through the entire set.
  728. eval_steps = None
  729. # However, if running eval on the TPU, you will need to specify the
  730. # number of steps.
  731. if FLAGS.use_tpu:
  732. assert len(eval_examples) % FLAGS.eval_batch_size == 0
  733. eval_steps = int(len(eval_examples) // FLAGS.eval_batch_size)
  734. eval_drop_remainder = True if FLAGS.use_tpu else False
  735. eval_input_fn = file_based_input_fn_builder(
  736. input_file=eval_file,
  737. seq_length=FLAGS.max_seq_length,
  738. is_training=False,
  739. drop_remainder=eval_drop_remainder)
  740. result = estimator.evaluate(input_fn=eval_input_fn, steps=eval_steps)
  741. output_eval_file = os.path.join(FLAGS.output_dir, "eval_results.txt")
  742. with tf.gfile.GFile(output_eval_file, "w") as writer:
  743. tf.logging.info("***** Eval results *****")
  744. for key in sorted(result.keys()):
  745. tf.logging.info(" %s = %s", key, str(result[key]))
  746. writer.write("%s = %s\n" % (key, str(result[key])))
  747. if FLAGS.do_predict:
  748. predict_examples = processor.get_test_examples(FLAGS.data_dir)
  749. num_actual_predict_examples = len(predict_examples)
  750. if FLAGS.use_tpu:
  751. # TPU requires a fixed batch size for all batches, therefore the number
  752. # of examples must be a multiple of the batch size, or else examples
  753. # will get dropped. So we pad with fake examples which are ignored
  754. # later on.
  755. while len(predict_examples) % FLAGS.predict_batch_size != 0:
  756. predict_examples.append(PaddingInputExample())
  757. predict_file = os.path.join(FLAGS.output_dir, "predict.tf_record")
  758. file_based_convert_examples_to_features(predict_examples, label_list,
  759. FLAGS.max_seq_length, tokenizer,
  760. predict_file)
  761. tf.logging.info("***** Running prediction*****")
  762. tf.logging.info(" Num examples = %d (%d actual, %d padding)",
  763. len(predict_examples), num_actual_predict_examples,
  764. len(predict_examples) - num_actual_predict_examples)
  765. tf.logging.info(" Batch size = %d", FLAGS.predict_batch_size)
  766. predict_drop_remainder = True if FLAGS.use_tpu else False
  767. predict_input_fn = file_based_input_fn_builder(
  768. input_file=predict_file,
  769. seq_length=FLAGS.max_seq_length,
  770. is_training=False,
  771. drop_remainder=predict_drop_remainder)
  772. result = estimator.predict(input_fn=predict_input_fn)
  773. output_predict_file = os.path.join(FLAGS.output_dir, "test_results.tsv")
  774. with tf.gfile.GFile(output_predict_file, "w") as writer:
  775. num_written_lines = 0
  776. tf.logging.info("***** Predict results *****")
  777. for (i, prediction) in enumerate(result):
  778. probabilities = prediction["probabilities"]
  779. if i >= num_actual_predict_examples:
  780. break
  781. output_line = "\t".join(
  782. str(class_probability)
  783. for class_probability in probabilities) + "\n"
  784. writer.write(output_line)
  785. num_written_lines += 1
  786. assert num_written_lines == num_actual_predict_examples
  787. if __name__ == "__main__":
  788. flags.mark_flag_as_required("data_dir")
  789. flags.mark_flag_as_required("task_name")
  790. flags.mark_flag_as_required("vocab_file")
  791. flags.mark_flag_as_required("bert_config_file")
  792. flags.mark_flag_as_required("output_dir")
  793. tf.app.run()
Tip!

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

Comments

Loading...