(_)
| 296 | |
| 297 | |
| 298 | def main(_): |
| 299 | tf.enable_eager_execution() |
| 300 | |
| 301 | if not FLAGS.data_path: |
| 302 | raise ValueError("Must specify --data-path") |
| 303 | corpus = Datasets(FLAGS.data_path) |
| 304 | train_data = _divide_into_batches(corpus.train, FLAGS.batch_size) |
| 305 | eval_data = _divide_into_batches(corpus.valid, 10) |
| 306 | |
| 307 | have_gpu = tfe.num_gpus() > 0 |
| 308 | use_cudnn_rnn = not FLAGS.no_use_cudnn_rnn and have_gpu |
| 309 | |
| 310 | with tf.device("/device:GPU:0" if have_gpu else None): |
| 311 | # Make learning_rate a Variable so it can be included in the checkpoint |
| 312 | # and we can resume training with the last saved learning_rate. |
| 313 | learning_rate = tf.Variable(20.0, name="learning_rate") |
| 314 | model = PTBModel(corpus.vocab_size(), FLAGS.embedding_dim, |
| 315 | FLAGS.hidden_dim, FLAGS.num_layers, FLAGS.dropout, |
| 316 | use_cudnn_rnn) |
| 317 | optimizer = tf.train.GradientDescentOptimizer(learning_rate) |
| 318 | checkpoint = tf.train.Checkpoint( |
| 319 | learning_rate=learning_rate, model=model, |
| 320 | # GradientDescentOptimizer has no state to checkpoint, but noting it |
| 321 | # here lets us swap in an optimizer that does. |
| 322 | optimizer=optimizer) |
| 323 | # Restore existing variables now (learning_rate), and restore new variables |
| 324 | # on creation if a checkpoint exists. |
| 325 | checkpoint.restore(tf.train.latest_checkpoint(FLAGS.logdir)) |
| 326 | sys.stderr.write("learning_rate=%f\n" % learning_rate.numpy()) |
| 327 | |
| 328 | best_loss = None |
| 329 | for _ in range(FLAGS.epoch): |
| 330 | train(model, optimizer, train_data, FLAGS.seq_len, FLAGS.clip) |
| 331 | eval_loss = evaluate(model, eval_data) |
| 332 | if not best_loss or eval_loss < best_loss: |
| 333 | if FLAGS.logdir: |
| 334 | checkpoint.save(os.path.join(FLAGS.logdir, "ckpt")) |
| 335 | best_loss = eval_loss |
| 336 | else: |
| 337 | learning_rate.assign(learning_rate / 4.0) |
| 338 | sys.stderr.write("eval_loss did not reduce in this epoch, " |
| 339 | "changing learning rate to %f for the next epoch\n" % |
| 340 | learning_rate.numpy()) |
| 341 | |
| 342 | |
| 343 | if __name__ == "__main__": |
nothing calls this directly
no test coverage detected