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_pretraining.py 18 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
  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 masked LM/next sentence masked_lm pre-training for BERT."""
  16. from __future__ import absolute_import
  17. from __future__ import division
  18. from __future__ import print_function
  19. import os
  20. import modeling
  21. import optimization
  22. import tensorflow as tf
  23. flags = tf.flags
  24. FLAGS = flags.FLAGS
  25. ## Required parameters
  26. flags.DEFINE_string(
  27. "bert_config_file", None,
  28. "The config json file corresponding to the pre-trained BERT model. "
  29. "This specifies the model architecture.")
  30. flags.DEFINE_string(
  31. "input_file", None,
  32. "Input TF example files (can be a glob or comma separated).")
  33. flags.DEFINE_string(
  34. "output_dir", None,
  35. "The output directory where the model checkpoints will be written.")
  36. ## Other parameters
  37. flags.DEFINE_string(
  38. "init_checkpoint", None,
  39. "Initial checkpoint (usually from a pre-trained BERT model).")
  40. flags.DEFINE_integer(
  41. "max_seq_length", 128,
  42. "The maximum total input sequence length after WordPiece tokenization. "
  43. "Sequences longer than this will be truncated, and sequences shorter "
  44. "than this will be padded. Must match data generation.")
  45. flags.DEFINE_integer(
  46. "max_predictions_per_seq", 20,
  47. "Maximum number of masked LM predictions per sequence. "
  48. "Must match data generation.")
  49. flags.DEFINE_bool("do_train", False, "Whether to run training.")
  50. flags.DEFINE_bool("do_eval", False, "Whether to run eval on the dev set.")
  51. flags.DEFINE_integer("train_batch_size", 32, "Total batch size for training.")
  52. flags.DEFINE_integer("eval_batch_size", 8, "Total batch size for eval.")
  53. flags.DEFINE_float("learning_rate", 5e-5, "The initial learning rate for Adam.")
  54. flags.DEFINE_integer("num_train_steps", 100000, "Number of training steps.")
  55. flags.DEFINE_integer("num_warmup_steps", 10000, "Number of warmup steps.")
  56. flags.DEFINE_integer("save_checkpoints_steps", 1000,
  57. "How often to save the model checkpoint.")
  58. flags.DEFINE_integer("iterations_per_loop", 1000,
  59. "How many steps to make in each estimator call.")
  60. flags.DEFINE_integer("max_eval_steps", 100, "Maximum number of eval steps.")
  61. flags.DEFINE_bool("use_tpu", False, "Whether to use TPU or GPU/CPU.")
  62. tf.flags.DEFINE_string(
  63. "tpu_name", None,
  64. "The Cloud TPU to use for training. This should be either the name "
  65. "used when creating the Cloud TPU, or a grpc://ip.address.of.tpu:8470 "
  66. "url.")
  67. tf.flags.DEFINE_string(
  68. "tpu_zone", None,
  69. "[Optional] GCE zone where the Cloud TPU is located in. If not "
  70. "specified, we will attempt to automatically detect the GCE project from "
  71. "metadata.")
  72. tf.flags.DEFINE_string(
  73. "gcp_project", None,
  74. "[Optional] Project name for the Cloud TPU-enabled project. If not "
  75. "specified, we will attempt to automatically detect the GCE project from "
  76. "metadata.")
  77. tf.flags.DEFINE_string("master", None, "[Optional] TensorFlow master URL.")
  78. flags.DEFINE_integer(
  79. "num_tpu_cores", 8,
  80. "Only used if `use_tpu` is True. Total number of TPU cores to use.")
  81. def model_fn_builder(bert_config, init_checkpoint, learning_rate,
  82. num_train_steps, num_warmup_steps, use_tpu,
  83. use_one_hot_embeddings):
  84. """Returns `model_fn` closure for TPUEstimator."""
  85. def model_fn(features, labels, mode, params): # pylint: disable=unused-argument
  86. """The `model_fn` for TPUEstimator."""
  87. tf.logging.info("*** Features ***")
  88. for name in sorted(features.keys()):
  89. tf.logging.info(" name = %s, shape = %s" % (name, features[name].shape))
  90. input_ids = features["input_ids"]
  91. input_mask = features["input_mask"]
  92. segment_ids = features["segment_ids"]
  93. masked_lm_positions = features["masked_lm_positions"]
  94. masked_lm_ids = features["masked_lm_ids"]
  95. masked_lm_weights = features["masked_lm_weights"]
  96. next_sentence_labels = features["next_sentence_labels"]
  97. is_training = (mode == tf.estimator.ModeKeys.TRAIN)
  98. model = modeling.BertModel(
  99. config=bert_config,
  100. is_training=is_training,
  101. input_ids=input_ids,
  102. input_mask=input_mask,
  103. token_type_ids=segment_ids,
  104. use_one_hot_embeddings=use_one_hot_embeddings)
  105. (masked_lm_loss,
  106. masked_lm_example_loss, masked_lm_log_probs) = get_masked_lm_output(
  107. bert_config, model.get_sequence_output(), model.get_embedding_table(),
  108. masked_lm_positions, masked_lm_ids, masked_lm_weights)
  109. (next_sentence_loss, next_sentence_example_loss,
  110. next_sentence_log_probs) = get_next_sentence_output(
  111. bert_config, model.get_pooled_output(), next_sentence_labels)
  112. total_loss = masked_lm_loss + next_sentence_loss
  113. tvars = tf.trainable_variables()
  114. initialized_variable_names = {}
  115. scaffold_fn = None
  116. if init_checkpoint:
  117. (assignment_map, initialized_variable_names
  118. ) = modeling.get_assignment_map_from_checkpoint(tvars, init_checkpoint)
  119. if use_tpu:
  120. def tpu_scaffold():
  121. tf.train.init_from_checkpoint(init_checkpoint, assignment_map)
  122. return tf.train.Scaffold()
  123. scaffold_fn = tpu_scaffold
  124. else:
  125. tf.train.init_from_checkpoint(init_checkpoint, assignment_map)
  126. tf.logging.info("**** Trainable Variables ****")
  127. for var in tvars:
  128. init_string = ""
  129. if var.name in initialized_variable_names:
  130. init_string = ", *INIT_FROM_CKPT*"
  131. tf.logging.info(" name = %s, shape = %s%s", var.name, var.shape,
  132. init_string)
  133. output_spec = None
  134. if mode == tf.estimator.ModeKeys.TRAIN:
  135. train_op = optimization.create_optimizer(
  136. total_loss, learning_rate, num_train_steps, num_warmup_steps, use_tpu)
  137. output_spec = tf.contrib.tpu.TPUEstimatorSpec(
  138. mode=mode,
  139. loss=total_loss,
  140. train_op=train_op,
  141. scaffold_fn=scaffold_fn)
  142. elif mode == tf.estimator.ModeKeys.EVAL:
  143. def metric_fn(masked_lm_example_loss, masked_lm_log_probs, masked_lm_ids,
  144. masked_lm_weights, next_sentence_example_loss,
  145. next_sentence_log_probs, next_sentence_labels):
  146. """Computes the loss and accuracy of the model."""
  147. masked_lm_log_probs = tf.reshape(masked_lm_log_probs,
  148. [-1, masked_lm_log_probs.shape[-1]])
  149. masked_lm_predictions = tf.argmax(
  150. masked_lm_log_probs, axis=-1, output_type=tf.int32)
  151. masked_lm_example_loss = tf.reshape(masked_lm_example_loss, [-1])
  152. masked_lm_ids = tf.reshape(masked_lm_ids, [-1])
  153. masked_lm_weights = tf.reshape(masked_lm_weights, [-1])
  154. masked_lm_accuracy = tf.metrics.accuracy(
  155. labels=masked_lm_ids,
  156. predictions=masked_lm_predictions,
  157. weights=masked_lm_weights)
  158. masked_lm_mean_loss = tf.metrics.mean(
  159. values=masked_lm_example_loss, weights=masked_lm_weights)
  160. next_sentence_log_probs = tf.reshape(
  161. next_sentence_log_probs, [-1, next_sentence_log_probs.shape[-1]])
  162. next_sentence_predictions = tf.argmax(
  163. next_sentence_log_probs, axis=-1, output_type=tf.int32)
  164. next_sentence_labels = tf.reshape(next_sentence_labels, [-1])
  165. next_sentence_accuracy = tf.metrics.accuracy(
  166. labels=next_sentence_labels, predictions=next_sentence_predictions)
  167. next_sentence_mean_loss = tf.metrics.mean(
  168. values=next_sentence_example_loss)
  169. return {
  170. "masked_lm_accuracy": masked_lm_accuracy,
  171. "masked_lm_loss": masked_lm_mean_loss,
  172. "next_sentence_accuracy": next_sentence_accuracy,
  173. "next_sentence_loss": next_sentence_mean_loss,
  174. }
  175. eval_metrics = (metric_fn, [
  176. masked_lm_example_loss, masked_lm_log_probs, masked_lm_ids,
  177. masked_lm_weights, next_sentence_example_loss,
  178. next_sentence_log_probs, next_sentence_labels
  179. ])
  180. output_spec = tf.contrib.tpu.TPUEstimatorSpec(
  181. mode=mode,
  182. loss=total_loss,
  183. eval_metrics=eval_metrics,
  184. scaffold_fn=scaffold_fn)
  185. else:
  186. raise ValueError("Only TRAIN and EVAL modes are supported: %s" % (mode))
  187. return output_spec
  188. return model_fn
  189. def get_masked_lm_output(bert_config, input_tensor, output_weights, positions,
  190. label_ids, label_weights):
  191. """Get loss and log probs for the masked LM."""
  192. input_tensor = gather_indexes(input_tensor, positions)
  193. with tf.variable_scope("cls/predictions"):
  194. # We apply one more non-linear transformation before the output layer.
  195. # This matrix is not used after pre-training.
  196. with tf.variable_scope("transform"):
  197. input_tensor = tf.layers.dense(
  198. input_tensor,
  199. units=bert_config.hidden_size,
  200. activation=modeling.get_activation(bert_config.hidden_act),
  201. kernel_initializer=modeling.create_initializer(
  202. bert_config.initializer_range))
  203. input_tensor = modeling.layer_norm(input_tensor)
  204. # The output weights are the same as the input embeddings, but there is
  205. # an output-only bias for each token.
  206. output_bias = tf.get_variable(
  207. "output_bias",
  208. shape=[bert_config.vocab_size],
  209. initializer=tf.zeros_initializer())
  210. logits = tf.matmul(input_tensor, output_weights, transpose_b=True)
  211. logits = tf.nn.bias_add(logits, output_bias)
  212. log_probs = tf.nn.log_softmax(logits, axis=-1)
  213. label_ids = tf.reshape(label_ids, [-1])
  214. label_weights = tf.reshape(label_weights, [-1])
  215. one_hot_labels = tf.one_hot(
  216. label_ids, depth=bert_config.vocab_size, dtype=tf.float32)
  217. # The `positions` tensor might be zero-padded (if the sequence is too
  218. # short to have the maximum number of predictions). The `label_weights`
  219. # tensor has a value of 1.0 for every real prediction and 0.0 for the
  220. # padding predictions.
  221. per_example_loss = -tf.reduce_sum(log_probs * one_hot_labels, axis=[-1])
  222. numerator = tf.reduce_sum(label_weights * per_example_loss)
  223. denominator = tf.reduce_sum(label_weights) + 1e-5
  224. loss = numerator / denominator
  225. return (loss, per_example_loss, log_probs)
  226. def get_next_sentence_output(bert_config, input_tensor, labels):
  227. """Get loss and log probs for the next sentence prediction."""
  228. # Simple binary classification. Note that 0 is "next sentence" and 1 is
  229. # "random sentence". This weight matrix is not used after pre-training.
  230. with tf.variable_scope("cls/seq_relationship"):
  231. output_weights = tf.get_variable(
  232. "output_weights",
  233. shape=[2, bert_config.hidden_size],
  234. initializer=modeling.create_initializer(bert_config.initializer_range))
  235. output_bias = tf.get_variable(
  236. "output_bias", shape=[2], initializer=tf.zeros_initializer())
  237. logits = tf.matmul(input_tensor, output_weights, transpose_b=True)
  238. logits = tf.nn.bias_add(logits, output_bias)
  239. log_probs = tf.nn.log_softmax(logits, axis=-1)
  240. labels = tf.reshape(labels, [-1])
  241. one_hot_labels = tf.one_hot(labels, depth=2, dtype=tf.float32)
  242. per_example_loss = -tf.reduce_sum(one_hot_labels * log_probs, axis=-1)
  243. loss = tf.reduce_mean(per_example_loss)
  244. return (loss, per_example_loss, log_probs)
  245. def gather_indexes(sequence_tensor, positions):
  246. """Gathers the vectors at the specific positions over a minibatch."""
  247. sequence_shape = modeling.get_shape_list(sequence_tensor, expected_rank=3)
  248. batch_size = sequence_shape[0]
  249. seq_length = sequence_shape[1]
  250. width = sequence_shape[2]
  251. flat_offsets = tf.reshape(
  252. tf.range(0, batch_size, dtype=tf.int32) * seq_length, [-1, 1])
  253. flat_positions = tf.reshape(positions + flat_offsets, [-1])
  254. flat_sequence_tensor = tf.reshape(sequence_tensor,
  255. [batch_size * seq_length, width])
  256. output_tensor = tf.gather(flat_sequence_tensor, flat_positions)
  257. return output_tensor
  258. def input_fn_builder(input_files,
  259. max_seq_length,
  260. max_predictions_per_seq,
  261. is_training,
  262. num_cpu_threads=4):
  263. """Creates an `input_fn` closure to be passed to TPUEstimator."""
  264. def input_fn(params):
  265. """The actual input function."""
  266. batch_size = params["batch_size"]
  267. name_to_features = {
  268. "input_ids":
  269. tf.FixedLenFeature([max_seq_length], tf.int64),
  270. "input_mask":
  271. tf.FixedLenFeature([max_seq_length], tf.int64),
  272. "segment_ids":
  273. tf.FixedLenFeature([max_seq_length], tf.int64),
  274. "masked_lm_positions":
  275. tf.FixedLenFeature([max_predictions_per_seq], tf.int64),
  276. "masked_lm_ids":
  277. tf.FixedLenFeature([max_predictions_per_seq], tf.int64),
  278. "masked_lm_weights":
  279. tf.FixedLenFeature([max_predictions_per_seq], tf.float32),
  280. "next_sentence_labels":
  281. tf.FixedLenFeature([1], tf.int64),
  282. }
  283. # For training, we want a lot of parallel reading and shuffling.
  284. # For eval, we want no shuffling and parallel reading doesn't matter.
  285. if is_training:
  286. d = tf.data.Dataset.from_tensor_slices(tf.constant(input_files))
  287. d = d.repeat()
  288. d = d.shuffle(buffer_size=len(input_files))
  289. # `cycle_length` is the number of parallel files that get read.
  290. cycle_length = min(num_cpu_threads, len(input_files))
  291. # `sloppy` mode means that the interleaving is not exact. This adds
  292. # even more randomness to the training pipeline.
  293. d = d.apply(
  294. tf.contrib.data.parallel_interleave(
  295. tf.data.TFRecordDataset,
  296. sloppy=is_training,
  297. cycle_length=cycle_length))
  298. d = d.shuffle(buffer_size=100)
  299. else:
  300. d = tf.data.TFRecordDataset(input_files)
  301. # Since we evaluate for a fixed number of steps we don't want to encounter
  302. # out-of-range exceptions.
  303. d = d.repeat()
  304. # We must `drop_remainder` on training because the TPU requires fixed
  305. # size dimensions. For eval, we assume we are evaluating on the CPU or GPU
  306. # and we *don't* want to drop the remainder, otherwise we wont cover
  307. # every sample.
  308. d = d.apply(
  309. tf.contrib.data.map_and_batch(
  310. lambda record: _decode_record(record, name_to_features),
  311. batch_size=batch_size,
  312. num_parallel_batches=num_cpu_threads,
  313. drop_remainder=True))
  314. return d
  315. return input_fn
  316. def _decode_record(record, name_to_features):
  317. """Decodes a record to a TensorFlow example."""
  318. example = tf.parse_single_example(record, name_to_features)
  319. # tf.Example only supports tf.int64, but the TPU only supports tf.int32.
  320. # So cast all int64 to int32.
  321. for name in list(example.keys()):
  322. t = example[name]
  323. if t.dtype == tf.int64:
  324. t = tf.to_int32(t)
  325. example[name] = t
  326. return example
  327. def main(_):
  328. tf.logging.set_verbosity(tf.logging.INFO)
  329. if not FLAGS.do_train and not FLAGS.do_eval:
  330. raise ValueError("At least one of `do_train` or `do_eval` must be True.")
  331. bert_config = modeling.BertConfig.from_json_file(FLAGS.bert_config_file)
  332. tf.gfile.MakeDirs(FLAGS.output_dir)
  333. input_files = []
  334. for input_pattern in FLAGS.input_file.split(","):
  335. input_files.extend(tf.gfile.Glob(input_pattern))
  336. tf.logging.info("*** Input Files ***")
  337. for input_file in input_files:
  338. tf.logging.info(" %s" % input_file)
  339. tpu_cluster_resolver = None
  340. if FLAGS.use_tpu and FLAGS.tpu_name:
  341. tpu_cluster_resolver = tf.contrib.cluster_resolver.TPUClusterResolver(
  342. FLAGS.tpu_name, zone=FLAGS.tpu_zone, project=FLAGS.gcp_project)
  343. is_per_host = tf.contrib.tpu.InputPipelineConfig.PER_HOST_V2
  344. run_config = tf.contrib.tpu.RunConfig(
  345. cluster=tpu_cluster_resolver,
  346. master=FLAGS.master,
  347. model_dir=FLAGS.output_dir,
  348. save_checkpoints_steps=FLAGS.save_checkpoints_steps,
  349. tpu_config=tf.contrib.tpu.TPUConfig(
  350. iterations_per_loop=FLAGS.iterations_per_loop,
  351. num_shards=FLAGS.num_tpu_cores,
  352. per_host_input_for_training=is_per_host))
  353. model_fn = model_fn_builder(
  354. bert_config=bert_config,
  355. init_checkpoint=FLAGS.init_checkpoint,
  356. learning_rate=FLAGS.learning_rate,
  357. num_train_steps=FLAGS.num_train_steps,
  358. num_warmup_steps=FLAGS.num_warmup_steps,
  359. use_tpu=FLAGS.use_tpu,
  360. use_one_hot_embeddings=FLAGS.use_tpu)
  361. # If TPU is not available, this will fall back to normal Estimator on CPU
  362. # or GPU.
  363. estimator = tf.contrib.tpu.TPUEstimator(
  364. use_tpu=FLAGS.use_tpu,
  365. model_fn=model_fn,
  366. config=run_config,
  367. train_batch_size=FLAGS.train_batch_size,
  368. eval_batch_size=FLAGS.eval_batch_size)
  369. if FLAGS.do_train:
  370. tf.logging.info("***** Running training *****")
  371. tf.logging.info(" Batch size = %d", FLAGS.train_batch_size)
  372. train_input_fn = input_fn_builder(
  373. input_files=input_files,
  374. max_seq_length=FLAGS.max_seq_length,
  375. max_predictions_per_seq=FLAGS.max_predictions_per_seq,
  376. is_training=True)
  377. estimator.train(input_fn=train_input_fn, max_steps=FLAGS.num_train_steps)
  378. if FLAGS.do_eval:
  379. tf.logging.info("***** Running evaluation *****")
  380. tf.logging.info(" Batch size = %d", FLAGS.eval_batch_size)
  381. eval_input_fn = input_fn_builder(
  382. input_files=input_files,
  383. max_seq_length=FLAGS.max_seq_length,
  384. max_predictions_per_seq=FLAGS.max_predictions_per_seq,
  385. is_training=False)
  386. result = estimator.evaluate(
  387. input_fn=eval_input_fn, steps=FLAGS.max_eval_steps)
  388. output_eval_file = os.path.join(FLAGS.output_dir, "eval_results.txt")
  389. with tf.gfile.GFile(output_eval_file, "w") as writer:
  390. tf.logging.info("***** Eval results *****")
  391. for key in sorted(result.keys()):
  392. tf.logging.info(" %s = %s", key, str(result[key]))
  393. writer.write("%s = %s\n" % (key, str(result[key])))
  394. if __name__ == "__main__":
  395. flags.mark_flag_as_required("input_file")
  396. flags.mark_flag_as_required("bert_config_file")
  397. flags.mark_flag_as_required("output_dir")
  398. tf.app.run()
Tip!

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

Comments

Loading...