SinaTools 0.1.40__py2.py3-none-any.whl → 1.0.1__py2.py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. {SinaTools-0.1.40.dist-info → SinaTools-1.0.1.dist-info}/METADATA +1 -1
  2. SinaTools-1.0.1.dist-info/RECORD +73 -0
  3. sinatools/VERSION +1 -1
  4. sinatools/ner/__init__.py +5 -7
  5. sinatools/ner/trainers/BertNestedTrainer.py +203 -203
  6. sinatools/ner/trainers/BertTrainer.py +163 -163
  7. sinatools/ner/trainers/__init__.py +2 -2
  8. SinaTools-0.1.40.dist-info/RECORD +0 -123
  9. sinatools/arabert/arabert/__init__.py +0 -14
  10. sinatools/arabert/arabert/create_classification_data.py +0 -260
  11. sinatools/arabert/arabert/create_pretraining_data.py +0 -534
  12. sinatools/arabert/arabert/extract_features.py +0 -444
  13. sinatools/arabert/arabert/lamb_optimizer.py +0 -158
  14. sinatools/arabert/arabert/modeling.py +0 -1027
  15. sinatools/arabert/arabert/optimization.py +0 -202
  16. sinatools/arabert/arabert/run_classifier.py +0 -1078
  17. sinatools/arabert/arabert/run_pretraining.py +0 -593
  18. sinatools/arabert/arabert/run_squad.py +0 -1440
  19. sinatools/arabert/arabert/tokenization.py +0 -414
  20. sinatools/arabert/araelectra/__init__.py +0 -1
  21. sinatools/arabert/araelectra/build_openwebtext_pretraining_dataset.py +0 -103
  22. sinatools/arabert/araelectra/build_pretraining_dataset.py +0 -230
  23. sinatools/arabert/araelectra/build_pretraining_dataset_single_file.py +0 -90
  24. sinatools/arabert/araelectra/configure_finetuning.py +0 -172
  25. sinatools/arabert/araelectra/configure_pretraining.py +0 -143
  26. sinatools/arabert/araelectra/finetune/__init__.py +0 -14
  27. sinatools/arabert/araelectra/finetune/feature_spec.py +0 -56
  28. sinatools/arabert/araelectra/finetune/preprocessing.py +0 -173
  29. sinatools/arabert/araelectra/finetune/scorer.py +0 -54
  30. sinatools/arabert/araelectra/finetune/task.py +0 -74
  31. sinatools/arabert/araelectra/finetune/task_builder.py +0 -70
  32. sinatools/arabert/araelectra/flops_computation.py +0 -215
  33. sinatools/arabert/araelectra/model/__init__.py +0 -14
  34. sinatools/arabert/araelectra/model/modeling.py +0 -1029
  35. sinatools/arabert/araelectra/model/optimization.py +0 -193
  36. sinatools/arabert/araelectra/model/tokenization.py +0 -355
  37. sinatools/arabert/araelectra/pretrain/__init__.py +0 -14
  38. sinatools/arabert/araelectra/pretrain/pretrain_data.py +0 -160
  39. sinatools/arabert/araelectra/pretrain/pretrain_helpers.py +0 -229
  40. sinatools/arabert/araelectra/run_finetuning.py +0 -323
  41. sinatools/arabert/araelectra/run_pretraining.py +0 -469
  42. sinatools/arabert/araelectra/util/__init__.py +0 -14
  43. sinatools/arabert/araelectra/util/training_utils.py +0 -112
  44. sinatools/arabert/araelectra/util/utils.py +0 -109
  45. sinatools/arabert/aragpt2/__init__.py +0 -2
  46. sinatools/arabert/aragpt2/create_pretraining_data.py +0 -95
  47. sinatools/arabert/aragpt2/gpt2/__init__.py +0 -2
  48. sinatools/arabert/aragpt2/gpt2/lamb_optimizer.py +0 -158
  49. sinatools/arabert/aragpt2/gpt2/optimization.py +0 -225
  50. sinatools/arabert/aragpt2/gpt2/run_pretraining.py +0 -397
  51. sinatools/arabert/aragpt2/grover/__init__.py +0 -0
  52. sinatools/arabert/aragpt2/grover/dataloader.py +0 -161
  53. sinatools/arabert/aragpt2/grover/modeling.py +0 -803
  54. sinatools/arabert/aragpt2/grover/modeling_gpt2.py +0 -1196
  55. sinatools/arabert/aragpt2/grover/optimization_adafactor.py +0 -234
  56. sinatools/arabert/aragpt2/grover/train_tpu.py +0 -187
  57. sinatools/arabert/aragpt2/grover/utils.py +0 -234
  58. sinatools/arabert/aragpt2/train_bpe_tokenizer.py +0 -59
  59. {SinaTools-0.1.40.data → SinaTools-1.0.1.data}/data/sinatools/environment.yml +0 -0
  60. {SinaTools-0.1.40.dist-info → SinaTools-1.0.1.dist-info}/AUTHORS.rst +0 -0
  61. {SinaTools-0.1.40.dist-info → SinaTools-1.0.1.dist-info}/LICENSE +0 -0
  62. {SinaTools-0.1.40.dist-info → SinaTools-1.0.1.dist-info}/WHEEL +0 -0
  63. {SinaTools-0.1.40.dist-info → SinaTools-1.0.1.dist-info}/entry_points.txt +0 -0
  64. {SinaTools-0.1.40.dist-info → SinaTools-1.0.1.dist-info}/top_level.txt +0 -0
@@ -1,1078 +0,0 @@
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
-
17
- from __future__ import absolute_import
18
- from __future__ import division
19
- from __future__ import print_function
20
-
21
- import collections
22
- import csv
23
- import os
24
- import modeling
25
- import optimization
26
- import tokenization
27
- import tensorflow as tf
28
-
29
- flags = tf.flags
30
-
31
- FLAGS = flags.FLAGS
32
-
33
- ## Required parameters
34
- flags.DEFINE_string(
35
- "data_dir",
36
- None,
37
- "The input data dir. Should contain the .tsv files (or other data files) "
38
- "for the task.",
39
- )
40
-
41
- flags.DEFINE_string(
42
- "bert_config_file",
43
- None,
44
- "The config json file corresponding to the pre-trained BERT model. "
45
- "This specifies the model architecture.",
46
- )
47
-
48
- flags.DEFINE_string("task_name", None, "The name of the task to train.")
49
-
50
- flags.DEFINE_string(
51
- "vocab_file", None, "The vocabulary file that the BERT model was trained on."
52
- )
53
-
54
- flags.DEFINE_string(
55
- "output_dir",
56
- None,
57
- "The output directory where the model checkpoints will be written.",
58
- )
59
-
60
- ## Other parameters
61
-
62
- flags.DEFINE_string(
63
- "init_checkpoint",
64
- None,
65
- "Initial checkpoint (usually from a pre-trained BERT model).",
66
- )
67
-
68
- flags.DEFINE_bool(
69
- "do_lower_case",
70
- True,
71
- "Whether to lower case the input text. Should be True for uncased "
72
- "models and False for cased models.",
73
- )
74
-
75
- flags.DEFINE_integer(
76
- "max_seq_length",
77
- 128,
78
- "The maximum total input sequence length after WordPiece tokenization. "
79
- "Sequences longer than this will be truncated, and sequences shorter "
80
- "than this will be padded.",
81
- )
82
-
83
- flags.DEFINE_bool("do_train", False, "Whether to run training.")
84
-
85
- flags.DEFINE_bool("do_eval", False, "Whether to run eval on the dev set.")
86
-
87
- flags.DEFINE_bool(
88
- "do_predict", False, "Whether to run the model in inference mode on the test set."
89
- )
90
-
91
- flags.DEFINE_integer("train_batch_size", 32, "Total batch size for training.")
92
-
93
- flags.DEFINE_integer("eval_batch_size", 8, "Total batch size for eval.")
94
-
95
- flags.DEFINE_integer("predict_batch_size", 8, "Total batch size for predict.")
96
-
97
- flags.DEFINE_float("learning_rate", 5e-5, "The initial learning rate for Adam.")
98
-
99
- flags.DEFINE_float(
100
- "num_train_epochs", 3.0, "Total number of training epochs to perform."
101
- )
102
-
103
- flags.DEFINE_float(
104
- "warmup_proportion",
105
- 0.1,
106
- "Proportion of training to perform linear learning rate warmup for. "
107
- "E.g., 0.1 = 10% of training.",
108
- )
109
-
110
- flags.DEFINE_integer(
111
- "save_checkpoints_steps", 1000, "How often to save the model checkpoint."
112
- )
113
-
114
- flags.DEFINE_integer(
115
- "iterations_per_loop", 1000, "How many steps to make in each estimator call."
116
- )
117
-
118
- flags.DEFINE_bool("use_tpu", False, "Whether to use TPU or GPU/CPU.")
119
-
120
- tf.flags.DEFINE_string(
121
- "tpu_name",
122
- None,
123
- "The Cloud TPU to use for training. This should be either the name "
124
- "used when creating the Cloud TPU, or a grpc://ip.address.of.tpu:8470 "
125
- "url.",
126
- )
127
-
128
- tf.flags.DEFINE_string(
129
- "tpu_zone",
130
- None,
131
- "[Optional] GCE zone where the Cloud TPU is located in. If not "
132
- "specified, we will attempt to automatically detect the GCE project from "
133
- "metadata.",
134
- )
135
-
136
- tf.flags.DEFINE_string(
137
- "gcp_project",
138
- None,
139
- "[Optional] Project name for the Cloud TPU-enabled project. If not "
140
- "specified, we will attempt to automatically detect the GCE project from "
141
- "metadata.",
142
- )
143
-
144
- tf.flags.DEFINE_string("master", None, "[Optional] TensorFlow master URL.")
145
-
146
- flags.DEFINE_integer(
147
- "num_tpu_cores",
148
- 8,
149
- "Only used if `use_tpu` is True. Total number of TPU cores to use.",
150
- )
151
-
152
-
153
- class InputExample(object):
154
- """A single training/test example for simple sequence classification."""
155
-
156
- def __init__(self, guid, text_a, text_b=None, label=None):
157
- """Constructs a InputExample.
158
-
159
- Args:
160
- guid: Unique id for the example.
161
- text_a: string. The untokenized text of the first sequence. For single
162
- sequence tasks, only this sequence must be specified.
163
- text_b: (Optional) string. The untokenized text of the second sequence.
164
- Only must be specified for sequence pair tasks.
165
- label: (Optional) string. The label of the example. This should be
166
- specified for train and dev examples, but not for test examples.
167
- """
168
- self.guid = guid
169
- self.text_a = text_a
170
- self.text_b = text_b
171
- self.label = label
172
-
173
-
174
- class PaddingInputExample(object):
175
- """Fake example so the num input examples is a multiple of the batch size.
176
-
177
- When running eval/predict on the TPU, we need to pad the number of examples
178
- to be a multiple of the batch size, because the TPU requires a fixed batch
179
- size. The alternative is to drop the last batch, which is bad because it means
180
- the entire output data won't be generated.
181
-
182
- We use this class instead of `None` because treating `None` as padding
183
- battches could cause silent errors.
184
- """
185
-
186
-
187
- class InputFeatures(object):
188
- """A single set of features of data."""
189
-
190
- def __init__(
191
- self, input_ids, input_mask, segment_ids, label_id, is_real_example=True
192
- ):
193
- self.input_ids = input_ids
194
- self.input_mask = input_mask
195
- self.segment_ids = segment_ids
196
- self.label_id = label_id
197
- self.is_real_example = is_real_example
198
-
199
-
200
- class DataProcessor(object):
201
- """Base class for data converters for sequence classification data sets."""
202
-
203
- def get_train_examples(self, data_dir):
204
- """Gets a collection of `InputExample`s for the train set."""
205
- raise NotImplementedError()
206
-
207
- def get_dev_examples(self, data_dir):
208
- """Gets a collection of `InputExample`s for the dev set."""
209
- raise NotImplementedError()
210
-
211
- def get_test_examples(self, data_dir):
212
- """Gets a collection of `InputExample`s for prediction."""
213
- raise NotImplementedError()
214
-
215
- def get_labels(self):
216
- """Gets the list of labels for this data set."""
217
- raise NotImplementedError()
218
-
219
- @classmethod
220
- def _read_tsv(cls, input_file, quotechar=None):
221
- """Reads a tab separated value file."""
222
- with tf.gfile.Open(input_file, "r") as f:
223
- reader = csv.reader(f, delimiter="\t", quotechar=quotechar)
224
- lines = []
225
- for line in reader:
226
- lines.append(line)
227
- return lines
228
-
229
-
230
- class XnliProcessor(DataProcessor):
231
- """Processor for the XNLI data set."""
232
-
233
- def __init__(self):
234
- self.language = "ar"
235
-
236
- def get_train_examples(self, data_dir):
237
- """See base class."""
238
- lines = self._read_tsv(
239
- os.path.join(data_dir, "multinli", "multinli.train.%s.tsv" % self.language)
240
- )
241
- examples = []
242
- for (i, line) in enumerate(lines):
243
- if i == 0:
244
- continue
245
- guid = "train-%d" % (i)
246
- text_a = tokenization.convert_to_unicode(line[0])
247
- text_b = tokenization.convert_to_unicode(line[1])
248
- label = tokenization.convert_to_unicode(line[2])
249
- if label == tokenization.convert_to_unicode("contradictory"):
250
- label = tokenization.convert_to_unicode("contradiction")
251
- examples.append(
252
- InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label)
253
- )
254
- return examples
255
-
256
- def get_dev_examples(self, data_dir):
257
- """See base class."""
258
- lines = self._read_tsv(os.path.join(data_dir, "xnli.dev.tsv"))
259
- examples = []
260
- for (i, line) in enumerate(lines):
261
- if i == 0:
262
- continue
263
- guid = "dev-%d" % (i)
264
- language = tokenization.convert_to_unicode(line[0])
265
- if language != tokenization.convert_to_unicode(self.language):
266
- continue
267
- text_a = tokenization.convert_to_unicode(line[6])
268
- text_b = tokenization.convert_to_unicode(line[7])
269
- label = tokenization.convert_to_unicode(line[1])
270
- examples.append(
271
- InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label)
272
- )
273
- return examples
274
-
275
- def get_labels(self):
276
- """See base class."""
277
- return ["contradiction", "entailment", "neutral"]
278
-
279
-
280
- class MnliProcessor(DataProcessor):
281
- """Processor for the MultiNLI data set (GLUE version)."""
282
-
283
- def get_train_examples(self, data_dir):
284
- """See base class."""
285
- return self._create_examples(
286
- self._read_tsv(os.path.join(data_dir, "train.tsv")), "train"
287
- )
288
-
289
- def get_dev_examples(self, data_dir):
290
- """See base class."""
291
- return self._create_examples(
292
- self._read_tsv(os.path.join(data_dir, "dev_matched.tsv")), "dev_matched"
293
- )
294
-
295
- def get_test_examples(self, data_dir):
296
- """See base class."""
297
- return self._create_examples(
298
- self._read_tsv(os.path.join(data_dir, "test_matched.tsv")), "test"
299
- )
300
-
301
- def get_labels(self):
302
- """See base class."""
303
- return ["contradiction", "entailment", "neutral"]
304
-
305
- def _create_examples(self, lines, set_type):
306
- """Creates examples for the training and dev sets."""
307
- examples = []
308
- for (i, line) in enumerate(lines):
309
- if i == 0:
310
- continue
311
- guid = "%s-%s" % (set_type, tokenization.convert_to_unicode(line[0]))
312
- text_a = tokenization.convert_to_unicode(line[8])
313
- text_b = tokenization.convert_to_unicode(line[9])
314
- if set_type == "test":
315
- label = "contradiction"
316
- else:
317
- label = tokenization.convert_to_unicode(line[-1])
318
- examples.append(
319
- InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label)
320
- )
321
- return examples
322
-
323
-
324
- class MrpcProcessor(DataProcessor):
325
- """Processor for the MRPC data set (GLUE version)."""
326
-
327
- def get_train_examples(self, data_dir):
328
- """See base class."""
329
- return self._create_examples(
330
- self._read_tsv(os.path.join(data_dir, "train.tsv")), "train"
331
- )
332
-
333
- def get_dev_examples(self, data_dir):
334
- """See base class."""
335
- return self._create_examples(
336
- self._read_tsv(os.path.join(data_dir, "dev.tsv")), "dev"
337
- )
338
-
339
- def get_test_examples(self, data_dir):
340
- """See base class."""
341
- return self._create_examples(
342
- self._read_tsv(os.path.join(data_dir, "test.tsv")), "test"
343
- )
344
-
345
- def get_labels(self):
346
- """See base class."""
347
- return ["0", "1"]
348
-
349
- def _create_examples(self, lines, set_type):
350
- """Creates examples for the training and dev sets."""
351
- examples = []
352
- for (i, line) in enumerate(lines):
353
- if i == 0:
354
- continue
355
- guid = "%s-%s" % (set_type, i)
356
- text_a = tokenization.convert_to_unicode(line[3])
357
- text_b = tokenization.convert_to_unicode(line[4])
358
- if set_type == "test":
359
- label = "0"
360
- else:
361
- label = tokenization.convert_to_unicode(line[0])
362
- examples.append(
363
- InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label)
364
- )
365
- return examples
366
-
367
-
368
- class ColaProcessor(DataProcessor):
369
- """Processor for the CoLA data set (GLUE version)."""
370
-
371
- def get_train_examples(self, data_dir):
372
- """See base class."""
373
- return self._create_examples(
374
- self._read_tsv(os.path.join(data_dir, "train.tsv")), "train"
375
- )
376
-
377
- def get_dev_examples(self, data_dir):
378
- """See base class."""
379
- return self._create_examples(
380
- self._read_tsv(os.path.join(data_dir, "dev.tsv")), "dev"
381
- )
382
-
383
- def get_test_examples(self, data_dir):
384
- """See base class."""
385
- return self._create_examples(
386
- self._read_tsv(os.path.join(data_dir, "test.tsv")), "test"
387
- )
388
-
389
- def get_labels(self):
390
- """See base class."""
391
- return ["0", "1"]
392
-
393
- def _create_examples(self, lines, set_type):
394
- """Creates examples for the training and dev sets."""
395
- examples = []
396
- for (i, line) in enumerate(lines):
397
- # Only the test set has a header
398
- if set_type == "test" and i == 0:
399
- continue
400
- guid = "%s-%s" % (set_type, i)
401
- if set_type == "test":
402
- text_a = tokenization.convert_to_unicode(line[1])
403
- label = "0"
404
- else:
405
- text_a = tokenization.convert_to_unicode(line[3])
406
- label = tokenization.convert_to_unicode(line[1])
407
- examples.append(
408
- InputExample(guid=guid, text_a=text_a, text_b=None, label=label)
409
- )
410
- return examples
411
-
412
-
413
- def convert_single_example(ex_index, example, label_list, max_seq_length, tokenizer):
414
- """Converts a single `InputExample` into a single `InputFeatures`."""
415
-
416
- if isinstance(example, PaddingInputExample):
417
- return InputFeatures(
418
- input_ids=[0] * max_seq_length,
419
- input_mask=[0] * max_seq_length,
420
- segment_ids=[0] * max_seq_length,
421
- label_id=0,
422
- is_real_example=False,
423
- )
424
-
425
- label_map = {}
426
- for (i, label) in enumerate(label_list):
427
- label_map[label] = i
428
-
429
- tokens_a = tokenizer.tokenize(example.text_a)
430
- tokens_b = None
431
- if example.text_b:
432
- tokens_b = tokenizer.tokenize(example.text_b)
433
-
434
- if tokens_b:
435
- # Modifies `tokens_a` and `tokens_b` in place so that the total
436
- # length is less than the specified length.
437
- # Account for [CLS], [SEP], [SEP] with "- 3"
438
- _truncate_seq_pair(tokens_a, tokens_b, max_seq_length - 3)
439
- else:
440
- # Account for [CLS] and [SEP] with "- 2"
441
- if len(tokens_a) > max_seq_length - 2:
442
- tokens_a = tokens_a[0 : (max_seq_length - 2)]
443
-
444
- # The convention in BERT is:
445
- # (a) For sequence pairs:
446
- # tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP]
447
- # type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1
448
- # (b) For single sequences:
449
- # tokens: [CLS] the dog is hairy . [SEP]
450
- # type_ids: 0 0 0 0 0 0 0
451
- #
452
- # Where "type_ids" are used to indicate whether this is the first
453
- # sequence or the second sequence. The embedding vectors for `type=0` and
454
- # `type=1` were learned during pre-training and are added to the wordpiece
455
- # embedding vector (and position vector). This is not *strictly* necessary
456
- # since the [SEP] token unambiguously separates the sequences, but it makes
457
- # it easier for the model to learn the concept of sequences.
458
- #
459
- # For classification tasks, the first vector (corresponding to [CLS]) is
460
- # used as the "sentence vector". Note that this only makes sense because
461
- # the entire model is fine-tuned.
462
- tokens = []
463
- segment_ids = []
464
- tokens.append("[CLS]")
465
- segment_ids.append(0)
466
- for token in tokens_a:
467
- tokens.append(token)
468
- segment_ids.append(0)
469
- tokens.append("[SEP]")
470
- segment_ids.append(0)
471
-
472
- if tokens_b:
473
- for token in tokens_b:
474
- tokens.append(token)
475
- segment_ids.append(1)
476
- tokens.append("[SEP]")
477
- segment_ids.append(1)
478
-
479
- input_ids = tokenizer.convert_tokens_to_ids(tokens)
480
-
481
- # The mask has 1 for real tokens and 0 for padding tokens. Only real
482
- # tokens are attended to.
483
- input_mask = [1] * len(input_ids)
484
-
485
- # Zero-pad up to the sequence length.
486
- while len(input_ids) < max_seq_length:
487
- input_ids.append(0)
488
- input_mask.append(0)
489
- segment_ids.append(0)
490
-
491
- assert len(input_ids) == max_seq_length
492
- assert len(input_mask) == max_seq_length
493
- assert len(segment_ids) == max_seq_length
494
-
495
- label_id = label_map[example.label]
496
- if ex_index < 5:
497
- tf.logging.info("*** Example ***")
498
- tf.logging.info("guid: %s" % (example.guid))
499
- tf.logging.info(
500
- "tokens: %s" % " ".join([tokenization.printable_text(x) for x in tokens])
501
- )
502
- tf.logging.info("input_ids: %s" % " ".join([str(x) for x in input_ids]))
503
- tf.logging.info("input_mask: %s" % " ".join([str(x) for x in input_mask]))
504
- tf.logging.info("segment_ids: %s" % " ".join([str(x) for x in segment_ids]))
505
- tf.logging.info("label: %s (id = %d)" % (example.label, label_id))
506
-
507
- feature = InputFeatures(
508
- input_ids=input_ids,
509
- input_mask=input_mask,
510
- segment_ids=segment_ids,
511
- label_id=label_id,
512
- is_real_example=True,
513
- )
514
- return feature
515
-
516
-
517
- def file_based_convert_examples_to_features(
518
- examples, label_list, max_seq_length, tokenizer, output_file
519
- ):
520
- """Convert a set of `InputExample`s to a TFRecord file."""
521
-
522
- writer = tf.python_io.TFRecordWriter(output_file)
523
-
524
- for (ex_index, example) in enumerate(examples):
525
- if ex_index % 10000 == 0:
526
- tf.logging.info("Writing example %d of %d" % (ex_index, len(examples)))
527
-
528
- feature = convert_single_example(
529
- ex_index, example, label_list, max_seq_length, tokenizer
530
- )
531
-
532
- def create_int_feature(values):
533
- f = tf.train.Feature(int64_list=tf.train.Int64List(value=list(values)))
534
- return f
535
-
536
- features = collections.OrderedDict()
537
- features["input_ids"] = create_int_feature(feature.input_ids)
538
- features["input_mask"] = create_int_feature(feature.input_mask)
539
- features["segment_ids"] = create_int_feature(feature.segment_ids)
540
- features["label_ids"] = create_int_feature([feature.label_id])
541
- features["is_real_example"] = create_int_feature([int(feature.is_real_example)])
542
-
543
- tf_example = tf.train.Example(features=tf.train.Features(feature=features))
544
- writer.write(tf_example.SerializeToString())
545
- writer.close()
546
-
547
-
548
- def file_based_input_fn_builder(input_file, seq_length, is_training, drop_remainder):
549
- """Creates an `input_fn` closure to be passed to TPUEstimator."""
550
-
551
- name_to_features = {
552
- "input_ids": tf.FixedLenFeature([seq_length], tf.int64),
553
- "input_mask": tf.FixedLenFeature([seq_length], tf.int64),
554
- "segment_ids": tf.FixedLenFeature([seq_length], tf.int64),
555
- "label_ids": tf.FixedLenFeature([], tf.int64),
556
- "is_real_example": tf.FixedLenFeature([], tf.int64),
557
- }
558
-
559
- def _decode_record(record, name_to_features):
560
- """Decodes a record to a TensorFlow example."""
561
- example = tf.parse_single_example(record, name_to_features)
562
-
563
- # tf.Example only supports tf.int64, but the TPU only supports tf.int32.
564
- # So cast all int64 to int32.
565
- for name in list(example.keys()):
566
- t = example[name]
567
- if t.dtype == tf.int64:
568
- t = tf.to_int32(t)
569
- example[name] = t
570
-
571
- return example
572
-
573
- def input_fn(params):
574
- """The actual input function."""
575
- batch_size = params["batch_size"]
576
-
577
- # For training, we want a lot of parallel reading and shuffling.
578
- # For eval, we want no shuffling and parallel reading doesn't matter.
579
- d = tf.data.TFRecordDataset(input_file)
580
- if is_training:
581
- d = d.repeat()
582
- d = d.shuffle(buffer_size=100)
583
-
584
- d = d.apply(
585
- tf.contrib.data.map_and_batch(
586
- lambda record: _decode_record(record, name_to_features),
587
- batch_size=batch_size,
588
- drop_remainder=drop_remainder,
589
- )
590
- )
591
-
592
- return d
593
-
594
- return input_fn
595
-
596
-
597
- def _truncate_seq_pair(tokens_a, tokens_b, max_length):
598
- """Truncates a sequence pair in place to the maximum length."""
599
-
600
- # This is a simple heuristic which will always truncate the longer sequence
601
- # one token at a time. This makes more sense than truncating an equal percent
602
- # of tokens from each, since if one sequence is very short then each token
603
- # that's truncated likely contains more information than a longer sequence.
604
- while True:
605
- total_length = len(tokens_a) + len(tokens_b)
606
- if total_length <= max_length:
607
- break
608
- if len(tokens_a) > len(tokens_b):
609
- tokens_a.pop()
610
- else:
611
- tokens_b.pop()
612
-
613
-
614
- def create_model(
615
- bert_config,
616
- is_training,
617
- input_ids,
618
- input_mask,
619
- segment_ids,
620
- labels,
621
- num_labels,
622
- use_one_hot_embeddings,
623
- ):
624
- """Creates a classification model."""
625
- model = modeling.BertModel(
626
- config=bert_config,
627
- is_training=is_training,
628
- input_ids=input_ids,
629
- input_mask=input_mask,
630
- token_type_ids=segment_ids,
631
- use_one_hot_embeddings=use_one_hot_embeddings,
632
- )
633
-
634
- # In the demo, we are doing a simple classification task on the entire
635
- # segment.
636
- #
637
- # If you want to use the token-level output, use model.get_sequence_output()
638
- # instead.
639
- output_layer = model.get_pooled_output()
640
-
641
- hidden_size = output_layer.shape[-1].value
642
-
643
- output_weights = tf.get_variable(
644
- "output_weights",
645
- [num_labels, hidden_size],
646
- initializer=tf.truncated_normal_initializer(stddev=0.02),
647
- )
648
-
649
- output_bias = tf.get_variable(
650
- "output_bias", [num_labels], initializer=tf.zeros_initializer()
651
- )
652
-
653
- with tf.variable_scope("loss"):
654
- if is_training:
655
- # I.e., 0.1 dropout
656
- output_layer = tf.nn.dropout(output_layer, keep_prob=0.9)
657
-
658
- logits = tf.matmul(output_layer, output_weights, transpose_b=True)
659
- logits = tf.nn.bias_add(logits, output_bias)
660
- probabilities = tf.nn.softmax(logits, axis=-1)
661
- log_probs = tf.nn.log_softmax(logits, axis=-1)
662
-
663
- one_hot_labels = tf.one_hot(labels, depth=num_labels, dtype=tf.float32)
664
-
665
- per_example_loss = -tf.reduce_sum(one_hot_labels * log_probs, axis=-1)
666
- loss = tf.reduce_mean(per_example_loss)
667
-
668
- return (loss, per_example_loss, logits, probabilities)
669
-
670
-
671
- def model_fn_builder(
672
- bert_config,
673
- num_labels,
674
- init_checkpoint,
675
- learning_rate,
676
- num_train_steps,
677
- num_warmup_steps,
678
- use_tpu,
679
- use_one_hot_embeddings,
680
- ):
681
- """Returns `model_fn` closure for TPUEstimator."""
682
-
683
- def model_fn(features, labels, mode, params): # pylint: disable=unused-argument
684
- """The `model_fn` for TPUEstimator."""
685
-
686
- tf.logging.info("*** Features ***")
687
- for name in sorted(features.keys()):
688
- tf.logging.info(" name = %s, shape = %s" % (name, features[name].shape))
689
-
690
- input_ids = features["input_ids"]
691
- input_mask = features["input_mask"]
692
- segment_ids = features["segment_ids"]
693
- label_ids = features["label_ids"]
694
- is_real_example = None
695
- if "is_real_example" in features:
696
- is_real_example = tf.cast(features["is_real_example"], dtype=tf.float32)
697
- else:
698
- is_real_example = tf.ones(tf.shape(label_ids), dtype=tf.float32)
699
-
700
- is_training = mode == tf.estimator.ModeKeys.TRAIN
701
-
702
- (total_loss, per_example_loss, logits, probabilities) = create_model(
703
- bert_config,
704
- is_training,
705
- input_ids,
706
- input_mask,
707
- segment_ids,
708
- label_ids,
709
- num_labels,
710
- use_one_hot_embeddings,
711
- )
712
-
713
- tvars = tf.trainable_variables()
714
- initialized_variable_names = {}
715
- scaffold_fn = None
716
- if init_checkpoint:
717
- (
718
- assignment_map,
719
- initialized_variable_names,
720
- ) = modeling.get_assignment_map_from_checkpoint(tvars, init_checkpoint)
721
- if use_tpu:
722
-
723
- def tpu_scaffold():
724
- tf.train.init_from_checkpoint(init_checkpoint, assignment_map)
725
- return tf.train.Scaffold()
726
-
727
- scaffold_fn = tpu_scaffold
728
- else:
729
- tf.train.init_from_checkpoint(init_checkpoint, assignment_map)
730
-
731
- tf.logging.info("**** Trainable Variables ****")
732
- for var in tvars:
733
- init_string = ""
734
- if var.name in initialized_variable_names:
735
- init_string = ", *INIT_FROM_CKPT*"
736
- tf.logging.info(
737
- " name = %s, shape = %s%s", var.name, var.shape, init_string
738
- )
739
-
740
- output_spec = None
741
- if mode == tf.estimator.ModeKeys.TRAIN:
742
-
743
- train_op = optimization.create_optimizer(
744
- total_loss, learning_rate, num_train_steps, num_warmup_steps, use_tpu
745
- )
746
-
747
- output_spec = tf.contrib.tpu.TPUEstimatorSpec(
748
- mode=mode, loss=total_loss, train_op=train_op, scaffold_fn=scaffold_fn
749
- )
750
- elif mode == tf.estimator.ModeKeys.EVAL:
751
-
752
- def metric_fn(per_example_loss, label_ids, logits, is_real_example):
753
- predictions = tf.argmax(logits, axis=-1, output_type=tf.int32)
754
- accuracy = tf.metrics.accuracy(
755
- labels=label_ids, predictions=predictions, weights=is_real_example
756
- )
757
- loss = tf.metrics.mean(values=per_example_loss, weights=is_real_example)
758
- return {
759
- "eval_accuracy": accuracy,
760
- "eval_loss": loss,
761
- }
762
-
763
- eval_metrics = (
764
- metric_fn,
765
- [per_example_loss, label_ids, logits, is_real_example],
766
- )
767
- output_spec = tf.contrib.tpu.TPUEstimatorSpec(
768
- mode=mode,
769
- loss=total_loss,
770
- eval_metrics=eval_metrics,
771
- scaffold_fn=scaffold_fn,
772
- )
773
- else:
774
- output_spec = tf.contrib.tpu.TPUEstimatorSpec(
775
- mode=mode,
776
- predictions={"probabilities": probabilities},
777
- scaffold_fn=scaffold_fn,
778
- )
779
- return output_spec
780
-
781
- return model_fn
782
-
783
-
784
- # This function is not used by this file but is still used by the Colab and
785
- # people who depend on it.
786
- def input_fn_builder(features, seq_length, is_training, drop_remainder):
787
- """Creates an `input_fn` closure to be passed to TPUEstimator."""
788
-
789
- all_input_ids = []
790
- all_input_mask = []
791
- all_segment_ids = []
792
- all_label_ids = []
793
-
794
- for feature in features:
795
- all_input_ids.append(feature.input_ids)
796
- all_input_mask.append(feature.input_mask)
797
- all_segment_ids.append(feature.segment_ids)
798
- all_label_ids.append(feature.label_id)
799
-
800
- def input_fn(params):
801
- """The actual input function."""
802
- batch_size = params["batch_size"]
803
-
804
- num_examples = len(features)
805
-
806
- # This is for demo purposes and does NOT scale to large data sets. We do
807
- # not use Dataset.from_generator() because that uses tf.py_func which is
808
- # not TPU compatible. The right way to load data is with TFRecordReader.
809
- d = tf.data.Dataset.from_tensor_slices(
810
- {
811
- "input_ids": tf.constant(
812
- all_input_ids, shape=[num_examples, seq_length], dtype=tf.int32
813
- ),
814
- "input_mask": tf.constant(
815
- all_input_mask, shape=[num_examples, seq_length], dtype=tf.int32
816
- ),
817
- "segment_ids": tf.constant(
818
- all_segment_ids, shape=[num_examples, seq_length], dtype=tf.int32
819
- ),
820
- "label_ids": tf.constant(
821
- all_label_ids, shape=[num_examples], dtype=tf.int32
822
- ),
823
- }
824
- )
825
-
826
- if is_training:
827
- d = d.repeat()
828
- d = d.shuffle(buffer_size=100)
829
-
830
- d = d.batch(batch_size=batch_size, drop_remainder=drop_remainder)
831
- return d
832
-
833
- return input_fn
834
-
835
-
836
- # This function is not used by this file but is still used by the Colab and
837
- # people who depend on it.
838
- def convert_examples_to_features(examples, label_list, max_seq_length, tokenizer):
839
- """Convert a set of `InputExample`s to a list of `InputFeatures`."""
840
-
841
- features = []
842
- for (ex_index, example) in enumerate(examples):
843
- if ex_index % 10000 == 0:
844
- tf.logging.info("Writing example %d of %d" % (ex_index, len(examples)))
845
-
846
- feature = convert_single_example(
847
- ex_index, example, label_list, max_seq_length, tokenizer
848
- )
849
-
850
- features.append(feature)
851
- return features
852
-
853
-
854
- def main(_):
855
- tf.logging.set_verbosity(tf.logging.INFO)
856
- logger = tf.get_logger()
857
- logger.propagate = False
858
-
859
- processors = {
860
- "cola": ColaProcessor,
861
- "mnli": MnliProcessor,
862
- "mrpc": MrpcProcessor,
863
- "xnli": XnliProcessor,
864
- }
865
-
866
- tokenization.validate_case_matches_checkpoint(
867
- FLAGS.do_lower_case, FLAGS.init_checkpoint
868
- )
869
-
870
- if not FLAGS.do_train and not FLAGS.do_eval and not FLAGS.do_predict:
871
- raise ValueError(
872
- "At least one of `do_train`, `do_eval` or `do_predict' must be True."
873
- )
874
-
875
- bert_config = modeling.BertConfig.from_json_file(FLAGS.bert_config_file)
876
-
877
- if FLAGS.max_seq_length > bert_config.max_position_embeddings:
878
- raise ValueError(
879
- "Cannot use sequence length %d because the BERT model "
880
- "was only trained up to sequence length %d"
881
- % (FLAGS.max_seq_length, bert_config.max_position_embeddings)
882
- )
883
-
884
- tf.gfile.MakeDirs(FLAGS.output_dir)
885
-
886
- task_name = FLAGS.task_name.lower()
887
-
888
- if task_name not in processors:
889
- raise ValueError("Task not found: %s" % (task_name))
890
-
891
- processor = processors[task_name]()
892
-
893
- label_list = processor.get_labels()
894
-
895
- tokenizer = tokenization.FullTokenizer(
896
- vocab_file=FLAGS.vocab_file, do_lower_case=FLAGS.do_lower_case
897
- )
898
-
899
- tpu_cluster_resolver = None
900
- if FLAGS.use_tpu and FLAGS.tpu_name:
901
- tpu_cluster_resolver = tf.contrib.cluster_resolver.TPUClusterResolver(
902
- FLAGS.tpu_name, zone=FLAGS.tpu_zone, project=FLAGS.gcp_project
903
- )
904
-
905
- is_per_host = tf.contrib.tpu.InputPipelineConfig.PER_HOST_V2
906
- run_config = tf.contrib.tpu.RunConfig(
907
- cluster=tpu_cluster_resolver,
908
- master=FLAGS.master,
909
- model_dir=FLAGS.output_dir,
910
- save_checkpoints_steps=FLAGS.save_checkpoints_steps,
911
- tpu_config=tf.contrib.tpu.TPUConfig(
912
- iterations_per_loop=FLAGS.iterations_per_loop,
913
- num_shards=FLAGS.num_tpu_cores,
914
- per_host_input_for_training=is_per_host,
915
- ),
916
- )
917
-
918
- train_examples = None
919
- num_train_steps = None
920
- num_warmup_steps = None
921
- if FLAGS.do_train:
922
- train_examples = processor.get_train_examples(FLAGS.data_dir)
923
- num_train_steps = int(
924
- len(train_examples) / FLAGS.train_batch_size * FLAGS.num_train_epochs
925
- )
926
- num_warmup_steps = int(num_train_steps * FLAGS.warmup_proportion)
927
-
928
- model_fn = model_fn_builder(
929
- bert_config=bert_config,
930
- num_labels=len(label_list),
931
- init_checkpoint=FLAGS.init_checkpoint,
932
- learning_rate=FLAGS.learning_rate,
933
- num_train_steps=num_train_steps,
934
- num_warmup_steps=num_warmup_steps,
935
- use_tpu=FLAGS.use_tpu,
936
- use_one_hot_embeddings=FLAGS.use_tpu,
937
- )
938
-
939
- # If TPU is not available, this will fall back to normal Estimator on CPU
940
- # or GPU.
941
- estimator = tf.contrib.tpu.TPUEstimator(
942
- use_tpu=FLAGS.use_tpu,
943
- model_fn=model_fn,
944
- config=run_config,
945
- train_batch_size=FLAGS.train_batch_size,
946
- eval_batch_size=FLAGS.eval_batch_size,
947
- predict_batch_size=FLAGS.predict_batch_size,
948
- )
949
-
950
- if FLAGS.do_train:
951
- train_file = os.path.join(FLAGS.output_dir, "train.tf_record")
952
- file_based_convert_examples_to_features(
953
- train_examples, label_list, FLAGS.max_seq_length, tokenizer, train_file
954
- )
955
- tf.logging.info("***** Running training *****")
956
- tf.logging.info(" Num examples = %d", len(train_examples))
957
- tf.logging.info(" Batch size = %d", FLAGS.train_batch_size)
958
- tf.logging.info(" Num steps = %d", num_train_steps)
959
- train_input_fn = file_based_input_fn_builder(
960
- input_file=train_file,
961
- seq_length=FLAGS.max_seq_length,
962
- is_training=True,
963
- drop_remainder=True,
964
- )
965
- estimator.train(input_fn=train_input_fn, max_steps=num_train_steps)
966
-
967
- if FLAGS.do_eval:
968
- eval_examples = processor.get_dev_examples(FLAGS.data_dir)
969
- num_actual_eval_examples = len(eval_examples)
970
- if FLAGS.use_tpu:
971
- # TPU requires a fixed batch size for all batches, therefore the number
972
- # of examples must be a multiple of the batch size, or else examples
973
- # will get dropped. So we pad with fake examples which are ignored
974
- # later on. These do NOT count towards the metric (all tf.metrics
975
- # support a per-instance weight, and these get a weight of 0.0).
976
- while len(eval_examples) % FLAGS.eval_batch_size != 0:
977
- eval_examples.append(PaddingInputExample())
978
-
979
- eval_file = os.path.join(FLAGS.output_dir, "eval.tf_record")
980
- file_based_convert_examples_to_features(
981
- eval_examples, label_list, FLAGS.max_seq_length, tokenizer, eval_file
982
- )
983
-
984
- tf.logging.info("***** Running evaluation *****")
985
- tf.logging.info(
986
- " Num examples = %d (%d actual, %d padding)",
987
- len(eval_examples),
988
- num_actual_eval_examples,
989
- len(eval_examples) - num_actual_eval_examples,
990
- )
991
- tf.logging.info(" Batch size = %d", FLAGS.eval_batch_size)
992
-
993
- # This tells the estimator to run through the entire set.
994
- eval_steps = None
995
- # However, if running eval on the TPU, you will need to specify the
996
- # number of steps.
997
- if FLAGS.use_tpu:
998
- assert len(eval_examples) % FLAGS.eval_batch_size == 0
999
- eval_steps = int(len(eval_examples) // FLAGS.eval_batch_size)
1000
-
1001
- eval_drop_remainder = True if FLAGS.use_tpu else False
1002
- eval_input_fn = file_based_input_fn_builder(
1003
- input_file=eval_file,
1004
- seq_length=FLAGS.max_seq_length,
1005
- is_training=False,
1006
- drop_remainder=eval_drop_remainder,
1007
- )
1008
-
1009
- result = estimator.evaluate(input_fn=eval_input_fn, steps=eval_steps)
1010
-
1011
- output_eval_file = os.path.join(FLAGS.output_dir, "eval_results.txt")
1012
- with tf.gfile.GFile(output_eval_file, "w") as writer:
1013
- tf.logging.info("***** Eval results *****")
1014
- for key in sorted(result.keys()):
1015
- tf.logging.info(" %s = %s", key, str(result[key]))
1016
- writer.write("%s = %s\n" % (key, str(result[key])))
1017
-
1018
- if FLAGS.do_predict:
1019
- predict_examples = processor.get_test_examples(FLAGS.data_dir)
1020
- num_actual_predict_examples = len(predict_examples)
1021
- if FLAGS.use_tpu:
1022
- # TPU requires a fixed batch size for all batches, therefore the number
1023
- # of examples must be a multiple of the batch size, or else examples
1024
- # will get dropped. So we pad with fake examples which are ignored
1025
- # later on.
1026
- while len(predict_examples) % FLAGS.predict_batch_size != 0:
1027
- predict_examples.append(PaddingInputExample())
1028
-
1029
- predict_file = os.path.join(FLAGS.output_dir, "predict.tf_record")
1030
- file_based_convert_examples_to_features(
1031
- predict_examples, label_list, FLAGS.max_seq_length, tokenizer, predict_file
1032
- )
1033
-
1034
- tf.logging.info("***** Running prediction*****")
1035
- tf.logging.info(
1036
- " Num examples = %d (%d actual, %d padding)",
1037
- len(predict_examples),
1038
- num_actual_predict_examples,
1039
- len(predict_examples) - num_actual_predict_examples,
1040
- )
1041
- tf.logging.info(" Batch size = %d", FLAGS.predict_batch_size)
1042
-
1043
- predict_drop_remainder = True if FLAGS.use_tpu else False
1044
- predict_input_fn = file_based_input_fn_builder(
1045
- input_file=predict_file,
1046
- seq_length=FLAGS.max_seq_length,
1047
- is_training=False,
1048
- drop_remainder=predict_drop_remainder,
1049
- )
1050
-
1051
- result = estimator.predict(input_fn=predict_input_fn)
1052
-
1053
- output_predict_file = os.path.join(FLAGS.output_dir, "test_results.tsv")
1054
- with tf.gfile.GFile(output_predict_file, "w") as writer:
1055
- num_written_lines = 0
1056
- tf.logging.info("***** Predict results *****")
1057
- for (i, prediction) in enumerate(result):
1058
- probabilities = prediction["probabilities"]
1059
- if i >= num_actual_predict_examples:
1060
- break
1061
- output_line = (
1062
- "\t".join(
1063
- str(class_probability) for class_probability in probabilities
1064
- )
1065
- + "\n"
1066
- )
1067
- writer.write(output_line)
1068
- num_written_lines += 1
1069
- assert num_written_lines == num_actual_predict_examples
1070
-
1071
-
1072
- if __name__ == "__main__":
1073
- flags.mark_flag_as_required("data_dir")
1074
- flags.mark_flag_as_required("task_name")
1075
- flags.mark_flag_as_required("vocab_file")
1076
- flags.mark_flag_as_required("bert_config_file")
1077
- flags.mark_flag_as_required("output_dir")
1078
- tf.app.run()