run_pretraining.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  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 time
  21. import modeling
  22. import optimization
  23. import tensorflow as tf
  24. flags = tf.flags
  25. FLAGS = flags.FLAGS
  26. ## Required parameters
  27. flags.DEFINE_string(
  28. "bert_config_file", None,
  29. "The config json file corresponding to the pre-trained BERT model. "
  30. "This specifies the model architecture.")
  31. flags.DEFINE_string(
  32. "input_file", None,
  33. "Input TF example files (can be a glob or comma separated).")
  34. flags.DEFINE_string(
  35. "output_dir", None,
  36. "The output directory where the model checkpoints will be written.")
  37. ## Other parameters
  38. flags.DEFINE_string(
  39. "init_checkpoint", None,
  40. "Initial checkpoint (usually from a pre-trained BERT model).")
  41. flags.DEFINE_integer(
  42. "max_seq_length", 512,
  43. "The maximum total input sequence length after WordPiece tokenization. "
  44. "Sequences longer than this will be truncated, and sequences shorter "
  45. "than this will be padded. Must match data generation.")
  46. flags.DEFINE_integer(
  47. "max_predictions_per_seq", 80,
  48. "Maximum number of masked LM predictions per sequence. "
  49. "Must match data generation.")
  50. flags.DEFINE_bool("do_train", False, "Whether to run training.")
  51. flags.DEFINE_bool("do_eval", False, "Whether to run eval on the dev set.")
  52. flags.DEFINE_integer("train_batch_size", 32, "Total batch size for training.")
  53. flags.DEFINE_integer("eval_batch_size", 8, "Total batch size for eval.")
  54. flags.DEFINE_float("learning_rate", 5e-5, "The initial learning rate for Adam.")
  55. flags.DEFINE_integer("num_train_steps", 100000, "Number of training steps.")
  56. flags.DEFINE_integer("num_warmup_steps", 10000, "Number of warmup steps.")
  57. flags.DEFINE_integer("save_checkpoints_steps", 1000,
  58. "How often to save the model checkpoint.")
  59. flags.DEFINE_integer("iterations_per_loop", 1000,
  60. "How many steps to make in each estimator call.")
  61. flags.DEFINE_integer("max_eval_steps", 100, "Maximum number of eval steps.")
  62. flags.DEFINE_bool("horovod", False, "Whether to use Horovod for multi-gpu runs")
  63. flags.DEFINE_bool("report_loss", False, "Whether to report total loss during training.")
  64. flags.DEFINE_bool("manual_fp16", False, "Whether to use fp32 or fp16 arithmetic on GPU. "
  65. "Manual casting is done instead of using AMP")
  66. flags.DEFINE_bool("use_xla", False, "Whether to enable XLA JIT compilation.")
  67. flags.DEFINE_bool("use_fp16", False, "Whether to enable AMP ops.")
  68. # report samples/sec, total loss and learning rate during training
  69. class _LogSessionRunHook(tf.train.SessionRunHook):
  70. def __init__(self, global_batch_size, display_every=10, hvd_rank=-1):
  71. self.global_batch_size = global_batch_size
  72. self.display_every = display_every
  73. self.hvd_rank = hvd_rank
  74. def after_create_session(self, session, coord):
  75. self.elapsed_secs = 0.
  76. self.count = 0
  77. def before_run(self, run_context):
  78. self.t0 = time.time()
  79. if FLAGS.manual_fp16 or FLAGS.use_fp16:
  80. return tf.train.SessionRunArgs(
  81. fetches=['step_update:0', 'total_loss:0',
  82. 'learning_rate:0', 'nsp_loss:0',
  83. 'mlm_loss:0', 'loss_scale:0'])
  84. else:
  85. return tf.train.SessionRunArgs(
  86. fetches=['step_update:0', 'total_loss:0',
  87. 'learning_rate:0', 'nsp_loss:0',
  88. 'mlm_loss:0'])
  89. def after_run(self, run_context, run_values):
  90. self.elapsed_secs += time.time() - self.t0
  91. self.count += 1
  92. if FLAGS.manual_fp16 or FLAGS.use_fp16:
  93. global_step, total_loss, lr, nsp_loss, mlm_loss, loss_scaler = run_values.results
  94. else:
  95. global_step, total_loss, lr, nsp_loss, mlm_loss = run_values.results
  96. print_step = global_step + 1 # One-based index for printing.
  97. if print_step == 1 or print_step % self.display_every == 0:
  98. dt = self.elapsed_secs / self.count
  99. img_per_sec = self.global_batch_size / dt
  100. if self.hvd_rank >= 0:
  101. if FLAGS.manual_fp16 or FLAGS.use_fp16:
  102. print('Rank = %2d :: Step = %6i Throughput = %11.1f MLM Loss = %10.4e NSP Loss = %10.4e Loss = %6.3f LR = %6.4e Loss scale = %6.4e' %
  103. (self.hvd_rank, print_step, img_per_sec, mlm_loss, nsp_loss, total_loss, lr, loss_scaler))
  104. else:
  105. print('Rank = %2d :: Step = %6i Throughput = %11.1f MLM Loss = %10.4e NSP Loss = %10.4e Loss = %6.3f LR = %6.4e' %
  106. (self.hvd_rank, print_step, img_per_sec, mlm_loss, nsp_loss, total_loss, lr))
  107. else:
  108. if FLAGS.manual_fp16 or FLAGS.use_fp16:
  109. print('Step = %6i Throughput = %11.1f MLM Loss = %10.4e NSP Loss = %10.4e Loss = %6.3f LR = %6.4e Loss scale = %6.4e' %
  110. (print_step, img_per_sec, mlm_loss, nsp_loss, total_loss, lr, loss_scaler))
  111. else:
  112. print('Step = %6i Throughput = %11.1f MLM Loss = %10.4e NSP Loss = %10.4e Loss = %6.3f LR = %6.4e' %
  113. (print_step, img_per_sec, mlm_loss, nsp_loss, total_loss, lr))
  114. self.elapsed_secs = 0.
  115. self.count = 0
  116. def model_fn_builder(bert_config, init_checkpoint, learning_rate,
  117. num_train_steps, num_warmup_steps,
  118. use_one_hot_embeddings, hvd=None):
  119. """Returns `model_fn` closure for TPUEstimator."""
  120. def model_fn(features, labels, mode, params): # pylint: disable=unused-argument
  121. """The `model_fn` for TPUEstimator."""
  122. tf.logging.info("*** Features ***")
  123. for name in sorted(features.keys()):
  124. tf.logging.info(" name = %s, shape = %s" % (name, features[name].shape))
  125. input_ids = features["input_ids"]
  126. input_mask = features["input_mask"]
  127. segment_ids = features["segment_ids"]
  128. masked_lm_positions = features["masked_lm_positions"]
  129. masked_lm_ids = features["masked_lm_ids"]
  130. masked_lm_weights = features["masked_lm_weights"]
  131. next_sentence_labels = features["next_sentence_labels"]
  132. is_training = (mode == tf.estimator.ModeKeys.TRAIN)
  133. model = modeling.BertModel(
  134. config=bert_config,
  135. is_training=is_training,
  136. input_ids=input_ids,
  137. input_mask=input_mask,
  138. token_type_ids=segment_ids,
  139. use_one_hot_embeddings=use_one_hot_embeddings,
  140. compute_type=tf.float16 if FLAGS.manual_fp16 else tf.float32)
  141. (masked_lm_loss,
  142. masked_lm_example_loss, masked_lm_log_probs) = get_masked_lm_output(
  143. bert_config, model.get_sequence_output(), model.get_embedding_table(),
  144. masked_lm_positions, masked_lm_ids,
  145. masked_lm_weights)
  146. (next_sentence_loss, next_sentence_example_loss,
  147. next_sentence_log_probs) = get_next_sentence_output(
  148. bert_config, model.get_pooled_output(), next_sentence_labels)
  149. masked_lm_loss = tf.identity(masked_lm_loss, name="mlm_loss")
  150. next_sentence_loss = tf.identity(next_sentence_loss, name="nsp_loss")
  151. total_loss = masked_lm_loss + next_sentence_loss
  152. total_loss = tf.identity(total_loss, name='total_loss')
  153. tvars = tf.trainable_variables()
  154. initialized_variable_names = {}
  155. if init_checkpoint and (hvd is None or hvd.rank() == 0):
  156. (assignment_map, initialized_variable_names
  157. ) = modeling.get_assignment_map_from_checkpoint(tvars, init_checkpoint)
  158. tf.train.init_from_checkpoint(init_checkpoint, assignment_map)
  159. tf.logging.info("**** Trainable Variables ****")
  160. for var in tvars:
  161. init_string = ""
  162. if var.name in initialized_variable_names:
  163. init_string = ", *INIT_FROM_CKPT*"
  164. tf.logging.info(" %d :: name = %s, shape = %s%s", 0 if hvd is None else hvd.rank(), var.name, var.shape,
  165. init_string)
  166. output_spec = None
  167. if mode == tf.estimator.ModeKeys.TRAIN:
  168. train_op = optimization.create_optimizer(
  169. total_loss, learning_rate, num_train_steps, num_warmup_steps,
  170. hvd, FLAGS.manual_fp16, FLAGS.use_fp16)
  171. output_spec = tf.estimator.EstimatorSpec(
  172. mode=mode,
  173. loss=total_loss,
  174. train_op=train_op)
  175. elif mode == tf.estimator.ModeKeys.EVAL:
  176. def metric_fn(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. """Computes the loss and accuracy of the model."""
  180. masked_lm_log_probs = tf.reshape(masked_lm_log_probs,
  181. [-1, masked_lm_log_probs.shape[-1]])
  182. masked_lm_predictions = tf.argmax(
  183. masked_lm_log_probs, axis=-1, output_type=tf.int32)
  184. masked_lm_example_loss = tf.reshape(masked_lm_example_loss, [-1])
  185. masked_lm_ids = tf.reshape(masked_lm_ids, [-1])
  186. masked_lm_weights = tf.reshape(masked_lm_weights, [-1])
  187. masked_lm_accuracy = tf.metrics.accuracy(
  188. labels=masked_lm_ids,
  189. predictions=masked_lm_predictions,
  190. weights=masked_lm_weights)
  191. masked_lm_mean_loss = tf.metrics.mean(
  192. values=masked_lm_example_loss, weights=masked_lm_weights)
  193. next_sentence_log_probs = tf.reshape(
  194. next_sentence_log_probs, [-1, next_sentence_log_probs.shape[-1]])
  195. next_sentence_predictions = tf.argmax(
  196. next_sentence_log_probs, axis=-1, output_type=tf.int32)
  197. next_sentence_labels = tf.reshape(next_sentence_labels, [-1])
  198. next_sentence_accuracy = tf.metrics.accuracy(
  199. labels=next_sentence_labels, predictions=next_sentence_predictions)
  200. next_sentence_mean_loss = tf.metrics.mean(
  201. values=next_sentence_example_loss)
  202. return {
  203. "masked_lm_accuracy": masked_lm_accuracy,
  204. "masked_lm_loss": masked_lm_mean_loss,
  205. "next_sentence_accuracy": next_sentence_accuracy,
  206. "next_sentence_loss": next_sentence_mean_loss,
  207. }
  208. eval_metric_ops = metric_fn(
  209. masked_lm_example_loss, masked_lm_log_probs, masked_lm_ids,
  210. masked_lm_weights, next_sentence_example_loss,
  211. next_sentence_log_probs, next_sentence_labels
  212. )
  213. output_spec = tf.estimator.EstimatorSpec(
  214. mode=mode,
  215. loss=total_loss,
  216. eval_metric_ops=eval_metric_ops)
  217. else:
  218. raise ValueError("Only TRAIN and EVAL modes are supported: %s" % (mode))
  219. return output_spec
  220. return model_fn
  221. def get_masked_lm_output(bert_config, input_tensor, output_weights, positions,
  222. label_ids, label_weights):
  223. """Get loss and log probs for the masked LM."""
  224. input_tensor = gather_indexes(input_tensor, positions)
  225. with tf.variable_scope("cls/predictions"):
  226. # We apply one more non-linear transformation before the output layer.
  227. # This matrix is not used after pre-training.
  228. with tf.variable_scope("transform"):
  229. input_tensor = tf.layers.dense(
  230. input_tensor,
  231. units=bert_config.hidden_size,
  232. activation=modeling.get_activation(bert_config.hidden_act),
  233. kernel_initializer=modeling.create_initializer(
  234. bert_config.initializer_range))
  235. input_tensor = modeling.layer_norm(input_tensor)
  236. # The output weights are the same as the input embeddings, but there is
  237. # an output-only bias for each token.
  238. output_bias = tf.get_variable(
  239. "output_bias",
  240. shape=[bert_config.vocab_size],
  241. initializer=tf.zeros_initializer())
  242. logits = tf.matmul(tf.cast(input_tensor, tf.float32), output_weights, transpose_b=True)
  243. logits = tf.nn.bias_add(logits, output_bias)
  244. log_probs = tf.nn.log_softmax(logits, axis=-1)
  245. label_ids = tf.reshape(label_ids, [-1])
  246. label_weights = tf.reshape(label_weights, [-1])
  247. one_hot_labels = tf.one_hot(
  248. label_ids, depth=bert_config.vocab_size, dtype=tf.float32)
  249. # The `positions` tensor might be zero-padded (if the sequence is too
  250. # short to have the maximum number of predictions). The `label_weights`
  251. # tensor has a value of 1.0 for every real prediction and 0.0 for the
  252. # padding predictions.
  253. per_example_loss = -tf.reduce_sum(log_probs * one_hot_labels, axis=[-1])
  254. numerator = tf.reduce_sum(label_weights * per_example_loss)
  255. denominator = tf.reduce_sum(label_weights) + 1e-5
  256. loss = numerator / denominator
  257. return (loss, per_example_loss, log_probs)
  258. def get_next_sentence_output(bert_config, input_tensor, labels):
  259. """Get loss and log probs for the next sentence prediction."""
  260. # Simple binary classification. Note that 0 is "next sentence" and 1 is
  261. # "random sentence". This weight matrix is not used after pre-training.
  262. with tf.variable_scope("cls/seq_relationship"):
  263. output_weights = tf.get_variable(
  264. "output_weights",
  265. shape=[2, bert_config.hidden_size],
  266. initializer=modeling.create_initializer(bert_config.initializer_range))
  267. output_bias = tf.get_variable(
  268. "output_bias", shape=[2], initializer=tf.zeros_initializer())
  269. logits = tf.matmul(tf.cast(input_tensor, tf.float32), output_weights, transpose_b=True)
  270. logits = tf.nn.bias_add(logits, output_bias)
  271. log_probs = tf.nn.log_softmax(logits, axis=-1)
  272. labels = tf.reshape(labels, [-1])
  273. one_hot_labels = tf.one_hot(labels, depth=2, dtype=tf.float32)
  274. per_example_loss = -tf.reduce_sum(one_hot_labels * log_probs, axis=-1)
  275. loss = tf.reduce_mean(per_example_loss)
  276. return (loss, per_example_loss, log_probs)
  277. def gather_indexes(sequence_tensor, positions):
  278. """Gathers the vectors at the specific positions over a minibatch."""
  279. sequence_shape = modeling.get_shape_list(sequence_tensor, expected_rank=3)
  280. batch_size = sequence_shape[0]
  281. seq_length = sequence_shape[1]
  282. width = sequence_shape[2]
  283. flat_offsets = tf.reshape(
  284. tf.range(0, batch_size, dtype=tf.int32) * seq_length, [-1, 1])
  285. flat_positions = tf.reshape(positions + flat_offsets, [-1])
  286. flat_sequence_tensor = tf.reshape(sequence_tensor,
  287. [batch_size * seq_length, width])
  288. output_tensor = tf.gather(flat_sequence_tensor, flat_positions)
  289. return output_tensor
  290. def input_fn_builder(input_files,
  291. batch_size,
  292. max_seq_length,
  293. max_predictions_per_seq,
  294. is_training,
  295. num_cpu_threads=4,
  296. hvd=None):
  297. """Creates an `input_fn` closure to be passed to Estimator."""
  298. def input_fn():
  299. """The actual input function."""
  300. name_to_features = {
  301. "input_ids":
  302. tf.FixedLenFeature([max_seq_length], tf.int64),
  303. "input_mask":
  304. tf.FixedLenFeature([max_seq_length], tf.int64),
  305. "segment_ids":
  306. tf.FixedLenFeature([max_seq_length], tf.int64),
  307. "masked_lm_positions":
  308. tf.FixedLenFeature([max_predictions_per_seq], tf.int64),
  309. "masked_lm_ids":
  310. tf.FixedLenFeature([max_predictions_per_seq], tf.int64),
  311. "masked_lm_weights":
  312. tf.FixedLenFeature([max_predictions_per_seq], tf.float32),
  313. "next_sentence_labels":
  314. tf.FixedLenFeature([1], tf.int64),
  315. }
  316. # For training, we want a lot of parallel reading and shuffling.
  317. # For eval, we want no shuffling and parallel reading doesn't matter.
  318. if is_training:
  319. d = tf.data.Dataset.from_tensor_slices(tf.constant(input_files))
  320. if hvd is not None: d = d.shard(hvd.size(), hvd.rank())
  321. d = d.repeat()
  322. d = d.shuffle(buffer_size=len(input_files))
  323. # `cycle_length` is the number of parallel files that get read.
  324. cycle_length = min(num_cpu_threads, len(input_files))
  325. # `sloppy` mode means that the interleaving is not exact. This adds
  326. # even more randomness to the training pipeline.
  327. d = d.apply(
  328. tf.contrib.data.parallel_interleave(
  329. tf.data.TFRecordDataset,
  330. sloppy=is_training,
  331. cycle_length=cycle_length))
  332. d = d.shuffle(buffer_size=100)
  333. else:
  334. d = tf.data.TFRecordDataset(input_files)
  335. # Since we evaluate for a fixed number of steps we don't want to encounter
  336. # out-of-range exceptions.
  337. d = d.repeat()
  338. # We must `drop_remainder` on training because the TPU requires fixed
  339. # size dimensions. For eval, we assume we are evaluating on the CPU or GPU
  340. # and we *don't* want to drop the remainder, otherwise we wont cover
  341. # every sample.
  342. d = d.apply(
  343. tf.contrib.data.map_and_batch(
  344. lambda record: _decode_record(record, name_to_features),
  345. batch_size=batch_size,
  346. num_parallel_batches=num_cpu_threads,
  347. drop_remainder=True))
  348. return d
  349. return input_fn
  350. def _decode_record(record, name_to_features):
  351. """Decodes a record to a TensorFlow example."""
  352. example = tf.parse_single_example(record, name_to_features)
  353. # tf.Example only supports tf.int64, but the TPU only supports tf.int32.
  354. # So cast all int64 to int32.
  355. for name in list(example.keys()):
  356. t = example[name]
  357. if t.dtype == tf.int64:
  358. t = tf.to_int32(t)
  359. example[name] = t
  360. return example
  361. def main(_):
  362. tf.logging.set_verbosity(tf.logging.INFO)
  363. if not FLAGS.do_train and not FLAGS.do_eval:
  364. raise ValueError("At least one of `do_train` or `do_eval` must be True.")
  365. if FLAGS.use_fp16:
  366. os.environ["TF_ENABLE_AUTO_MIXED_PRECISION_GRAPH_REWRITE"] = "1"
  367. if FLAGS.horovod:
  368. import horovod.tensorflow as hvd
  369. hvd.init()
  370. bert_config = modeling.BertConfig.from_json_file(FLAGS.bert_config_file)
  371. tf.gfile.MakeDirs(FLAGS.output_dir)
  372. input_files = []
  373. for input_pattern in FLAGS.input_file.split(","):
  374. input_files.extend(tf.gfile.Glob(input_pattern))
  375. tf.logging.info("*** Input Files ***")
  376. for input_file in input_files:
  377. tf.logging.info(" %s" % input_file)
  378. config = tf.ConfigProto()
  379. if FLAGS.horovod:
  380. config.gpu_options.visible_device_list = str(hvd.local_rank())
  381. if len(input_files) < hvd.size():
  382. raise ValueError("Input Files must be sharded")
  383. if FLAGS.use_xla:
  384. config.graph_options.optimizer_options.global_jit_level = tf.OptimizerOptions.ON_1
  385. is_per_host = tf.contrib.tpu.InputPipelineConfig.PER_HOST_V2
  386. config = tf.ConfigProto()
  387. if FLAGS.horovod:
  388. config.gpu_options.visible_device_list = str(hvd.local_rank())
  389. config.gpu_options.allow_growth = True
  390. # config.gpu_options.per_process_gpu_memory_fraction = 0.7
  391. if FLAGS.use_xla: config.graph_options.optimizer_options.global_jit_level = tf.OptimizerOptions.ON_1
  392. run_config = tf.estimator.RunConfig(
  393. model_dir=FLAGS.output_dir,
  394. session_config=config,
  395. save_checkpoints_steps=FLAGS.save_checkpoints_steps if not FLAGS.horovod or hvd.rank() == 0 else None,
  396. # This variable controls how often estimator reports examples/sec.
  397. # Default value is every 100 steps.
  398. # When --report_loss is True, we set to very large value to prevent
  399. # default info reporting from estimator.
  400. # Ideally we should set it to None, but that does not work.
  401. log_step_count_steps=10000 if FLAGS.report_loss else 100)
  402. model_fn = model_fn_builder(
  403. bert_config=bert_config,
  404. init_checkpoint=FLAGS.init_checkpoint,
  405. learning_rate=FLAGS.learning_rate if not FLAGS.horovod else FLAGS.learning_rate*hvd.size(),
  406. num_train_steps=FLAGS.num_train_steps,
  407. num_warmup_steps=FLAGS.num_warmup_steps,
  408. use_one_hot_embeddings=False,
  409. hvd=None if not FLAGS.horovod else hvd)
  410. training_hooks = []
  411. if FLAGS.horovod and hvd.size() > 1:
  412. training_hooks.append(hvd.BroadcastGlobalVariablesHook(0))
  413. if FLAGS.report_loss:
  414. global_batch_size = FLAGS.train_batch_size if not FLAGS.horovod else FLAGS.train_batch_size*hvd.size()
  415. training_hooks.append(_LogSessionRunHook(global_batch_size,1,-1 if not FLAGS.horovod else hvd.rank()))
  416. training_hooks = []
  417. if FLAGS.report_loss and (not FLAGS.horovod or hvd.rank() == 0):
  418. global_batch_size = FLAGS.train_batch_size if not FLAGS.horovod else FLAGS.train_batch_size*hvd.size()
  419. training_hooks.append(_LogSessionRunHook(global_batch_size,100))
  420. if FLAGS.horovod:
  421. training_hooks.append(hvd.BroadcastGlobalVariablesHook(0))
  422. estimator = tf.estimator.Estimator(
  423. model_fn=model_fn,
  424. config=run_config)
  425. if FLAGS.do_train:
  426. tf.logging.info("***** Running training *****")
  427. tf.logging.info(" Batch size = %d", FLAGS.train_batch_size)
  428. train_input_fn = input_fn_builder(
  429. input_files=input_files,
  430. batch_size=FLAGS.train_batch_size,
  431. max_seq_length=FLAGS.max_seq_length,
  432. max_predictions_per_seq=FLAGS.max_predictions_per_seq,
  433. is_training=True,
  434. hvd=None if not FLAGS.horovod else hvd)
  435. estimator.train(input_fn=train_input_fn, hooks=training_hooks, max_steps=FLAGS.num_train_steps)
  436. if FLAGS.do_eval and (not FLAGS.horovod or hvd.rank() == 0):
  437. tf.logging.info("***** Running evaluation *****")
  438. tf.logging.info(" Batch size = %d", FLAGS.eval_batch_size)
  439. eval_input_fn = input_fn_builder(
  440. input_files=input_files,
  441. batch_size=FLAGS.eval_batch_size,
  442. max_seq_length=FLAGS.max_seq_length,
  443. max_predictions_per_seq=FLAGS.max_predictions_per_seq,
  444. is_training=False,
  445. hvd=None if not FLAGS.horovod else hvd)
  446. result = estimator.evaluate(
  447. input_fn=eval_input_fn, steps=FLAGS.max_eval_steps)
  448. output_eval_file = os.path.join(FLAGS.output_dir, "eval_results.txt")
  449. with tf.gfile.GFile(output_eval_file, "w") as writer:
  450. tf.logging.info("***** Eval results *****")
  451. for key in sorted(result.keys()):
  452. tf.logging.info(" %s = %s", key, str(result[key]))
  453. writer.write("%s = %s\n" % (key, str(result[key])))
  454. if __name__ == "__main__":
  455. flags.mark_flag_as_required("input_file")
  456. flags.mark_flag_as_required("bert_config_file")
  457. flags.mark_flag_as_required("output_dir")
  458. if FLAGS.use_xla and FLAGS.manual_fp16:
  459. print('WARNING! Combining --use_xla with --manual_fp16 may prevent convergence.')
  460. print(' This warning message will be removed when the underlying')
  461. print(' issues have been fixed and you are running a TF version')
  462. print(' that has that fix.')
  463. tf.app.run()