def setUp(self):
     self.model_dir = tempfile.mkdtemp()
     self.graph = tf.Graph()
     with self.graph.as_default():
         self.scaffold = monitored_session.Scaffold()
         self.global_step = tf.contrib.framework.get_or_create_global_step()
         self.train_op = tf.assign_add(self.global_step, 1)
Пример #2
0
 def test_retry_on_aborted_error(self):
     # Tests that we silently retry on abort.  Note that this does not test
     # recovery as we do not use a CheckpointSaver in this test.
     with tf.Graph().as_default():
         gstep = tf.contrib.framework.get_or_create_global_step()
         do_step = tf.assign_add(gstep, 1)
         scaffold = monitored_session.Scaffold()
         hook = RaiseOnceAtCountN(
             4, tf.errors.AbortedError(None, None, 'Abort'))
         with monitored_session.MonitoredSession('',
                                                 scaffold=scaffold,
                                                 hooks=[hook]) as session:
             self.assertEqual(0, session.run(gstep))
             self.assertEqual(1, session.run(do_step))
             self.assertEqual(2, session.run(do_step))
             self.assertFalse(session.should_stop())
             # Here at step 3, the hook triggers and raises AbortedError.  The
             # MonitoredSession automatically retries and restart from a freshly
             # initialized session, so the step is back to 0 and running do_step
             # moves it to 1.
             self.assertEqual(1, session.run(do_step))
             self.assertFalse(session.should_stop())
             self.assertTrue(hook.raised)
             self.assertEqual(2, session.run(do_step))
             self.assertFalse(session.should_stop())
Пример #3
0
 def test_raise_error_if_more_than_one_cached_item(self):
     with tf.Graph().as_default():
         tf.Variable([1])
         tf.add_to_collection(tf.GraphKeys.SAVERS, tf.train.Saver())
         tf.add_to_collection(tf.GraphKeys.SAVERS, tf.train.Saver())
         with self.assertRaisesRegexp(RuntimeError, 'More than one item'):
             monitored_session.Scaffold().finalize()
Пример #4
0
 def test_recover_and_retry_on_aborted_error(self):
     # Tests that we silently retry and recover on abort.  This test uses
     # a CheckpointSaver to have something to recover from.
     logdir = self._test_dir('test_recover_and_retry_on_aborted_error')
     with tf.Graph().as_default():
         gstep = tf.contrib.framework.get_or_create_global_step()
         do_step = tf.assign_add(gstep, 1)
         scaffold = monitored_session.Scaffold()
         abort_hook = RaiseOnceAtCountN(
             4, tf.errors.AbortedError(None, None, 'Abort'))
         # Save after each step.
         ckpt_hook = basic_session_run_hooks.CheckpointSaverHook(
             logdir, save_steps=1, scaffold=scaffold)
         hooks = [abort_hook, ckpt_hook]
         with monitored_session.MonitoredSession('',
                                                 scaffold=scaffold,
                                                 checkpoint_dir=logdir,
                                                 hooks=hooks) as session:
             self.assertEqual(0, session.run(gstep))
             self.assertEqual(1, session.run(do_step))
             self.assertEqual(2, session.run(do_step))
             self.assertFalse(session.should_stop())
             # Here at step 3, the hook triggers and raises AbortedError.  The
             # MonitoredSession automatically restores and retries.
             self.assertEqual(3, session.run(do_step))
             self.assertTrue(abort_hook.raised)
             self.assertFalse(session.should_stop())
             self.assertEqual(4, session.run(do_step))
             self.assertFalse(session.should_stop())
Пример #5
0
 def test_graph_is_finalized(self):
     with tf.Graph().as_default():
         tf.Variable([1])
         monitored_session.Scaffold().finalize()
         with self.assertRaisesRegexp(
                 RuntimeError, 'Graph is finalized and cannot be modified'):
             tf.constant([0])
 def test_nothing_created_before_finalize(self):
     with tf.Graph().as_default():
         scaffold = monitored_session.Scaffold()
         self.assertEqual(None, scaffold.init_op)
         self.assertEqual(None, scaffold.init_feed_dict)
         self.assertEqual(None, scaffold.init_fn)
         self.assertEqual(None, scaffold.ready_op)
         self.assertEqual(None, scaffold.local_init_op)
         self.assertEqual(None, scaffold.saver)
 def test_defaults_no_variables(self):
     with tf.Graph().as_default():
         scaffold = monitored_session.Scaffold()
         tf.constant(1, name='my_const')
         scaffold.finalize()
         self.assertTrue(isinstance(scaffold.init_op, tf.Operation))
         self.assertEqual(None, scaffold.init_feed_dict)
         self.assertEqual(None, scaffold.init_fn)
         self.assertTrue(isinstance(scaffold.ready_op, tf.Tensor))
         self.assertTrue(isinstance(scaffold.local_init_op, tf.Operation))
         self.assertTrue(isinstance(scaffold.saver, tf.train.Saver))
 def test_stop_cleanly_when_no_exception_in_with_body(self):
     # Tests that regular exceptions pass through
     with tf.Graph().as_default():
         gstep = tf.contrib.framework.get_or_create_global_step()
         do_step = tf.assign_add(gstep, 1)
         scaffold = monitored_session.Scaffold()
         session = monitored_session.MonitoredSession('', scaffold=scaffold)
         with session:
             self.assertEqual(1, session.run(do_step))
             self.assertEqual(2, session.run(do_step))
             self.assertFalse(session.should_stop())
         # Should have closed.
         self.assertTrue(session.should_stop())
         self.assertTrue(session._is_closed())
    def test_num_steps(self):
        logdir = self._test_dir('test_num_steps')
        with tf.Graph().as_default():
            gstep = tf.contrib.framework.get_or_create_global_step()
            do_step = tf.assign_add(gstep, 1)
            scaffold = monitored_session.Scaffold()
            # Do 3 steps and save.
            hooks = [basic_session_run_hooks.StopAtStepHook(num_steps=3)]
            with monitored_session.MonitoredSession('',
                                                    scaffold=scaffold,
                                                    hooks=hooks) as session:
                session.run(do_step)
                self.assertFalse(session.should_stop())
                session.run(do_step)
                self.assertFalse(session.should_stop())
                session.run(do_step)
                self.assertTrue(session.should_stop())
                save_path = scaffold.saver.save(session.session,
                                                os.path.join(logdir, 'step-3'))
            # Restore and do 4 steps.
            def load_ckpt(scaffold, sess):
                scaffold.saver.restore(sess, save_path)

            scaffold = monitored_session.Scaffold(init_fn=load_ckpt)
            hooks = [basic_session_run_hooks.StopAtStepHook(num_steps=4)]
            with monitored_session.MonitoredSession('',
                                                    scaffold=scaffold,
                                                    hooks=hooks) as session:
                self.assertEqual(4, session.run(do_step))
                self.assertFalse(session.should_stop())
                session.run(do_step)
                self.assertFalse(session.should_stop())
                session.run(do_step)
                self.assertFalse(session.should_stop())
                session.run(do_step)
                self.assertTrue(session.should_stop())
 def test_defaults_empty_graph(self):
     with tf.Graph().as_default():
         scaffold = monitored_session.Scaffold()
         tf.Variable(1, name='my_var')
         scaffold.finalize()
         self.assertTrue(isinstance(scaffold.init_op, tf.Operation))
         self.assertEqual(None, scaffold.init_feed_dict)
         self.assertEqual(None, scaffold.init_fn)
         self.assertTrue(isinstance(scaffold.ready_op, tf.Tensor))
         self.assertTrue(isinstance(scaffold.local_init_op, tf.Operation))
         self.assertTrue(isinstance(scaffold.saver, tf.train.Saver))
         with self.test_session() as sess:
             self.assertTrue(b'my_var' in sess.run(scaffold.ready_op))
             sess.run([scaffold.init_op, scaffold.local_init_op])
             self.assertEquals(0, len(sess.run(scaffold.ready_op)))
 def test_uses_passed_values(self):
     with tf.Graph().as_default():
         tf.Variable([1])
         saver = tf.train.Saver()
         scaffold = monitored_session.Scaffold(
             init_op=2,
             init_feed_dict=3,
             init_fn=lambda scaffold, sess: 4,
             ready_op=5,
             local_init_op=6,
             saver=saver)
         scaffold.finalize()
         self.assertEqual(2, scaffold.init_op)
         self.assertEqual(3, scaffold.init_feed_dict)
         self.assertTrue(callable(scaffold.init_fn))
         self.assertEqual(5, scaffold.ready_op)
         self.assertEqual(6, scaffold.local_init_op)
         self.assertEqual(saver, scaffold.saver)
 def test_raises_regular_exceptions_in_with_body(self):
     # Tests that regular exceptions in "with body" are seen outside.
     with tf.Graph().as_default():
         gstep = tf.contrib.framework.get_or_create_global_step()
         do_step = tf.assign_add(gstep, 1)
         scaffold = monitored_session.Scaffold()
         session = monitored_session.MonitoredSession('', scaffold=scaffold)
         # We should see that exception.
         with self.assertRaisesRegexp(RuntimeError, 'regular exception'):
             with session:
                 self.assertEqual(1, session.run(do_step))
                 self.assertEqual(2, session.run(do_step))
                 self.assertFalse(session.should_stop())
                 # Will be visible outside the "with body".
                 raise RuntimeError('regular exception')
         # Should have closed.
         self.assertTrue(session.should_stop())
         self.assertTrue(session._is_closed())
Пример #13
0
 def test_regular_exception_reported_to_coord_pass_through_return(self):
     # Tests that regular exceptions reported to the coordinator from a thread
     # passes through returning from a "with MonitoredSession" block and
     # set the session in stop mode.
     with tf.Graph().as_default():
         gstep = tf.contrib.framework.get_or_create_global_step()
         scaffold = monitored_session.Scaffold()
         session = monitored_session.MonitoredSession('', scaffold=scaffold)
         with self.assertRaisesRegexp(RuntimeError,
                                      'a thread wants to stop'):
             with session:
                 self.assertEqual(0, session.run(gstep))
                 # Report an exception through the coordinator.
                 try:
                     raise RuntimeError('a thread wants to stop')
                 except RuntimeError as e:
                     session._coord.request_stop(e)
                 self.assertTrue(session.should_stop())
 def test_exit_cleanly_on_stop_iteration_exception(self):
     # Tests that we stop cleanly when OutOfRange is raised.
     with tf.Graph().as_default():
         gstep = tf.contrib.framework.get_or_create_global_step()
         do_step = tf.assign_add(gstep, 1)
         scaffold = monitored_session.Scaffold()
         hook = RaiseOnceAtCountN(2, StopIteration)
         session = monitored_session.MonitoredSession('',
                                                      scaffold=scaffold,
                                                      hooks=[hook])
         # session should cleanly exit from the context.
         with session:
             self.assertEqual(0, session.run(gstep))
             self.assertFalse(session.should_stop())
             # Here at step 1, the hook triggers and raises StopIteration. The
             # session should go into should_stop() mode. It should raise the
             # exception. So next step should not be executed.
             session.run(do_step)
             self.assertTrue(False)
         self.assertTrue(session.should_stop())
Пример #15
0
 def test_recovery(self):
   logdir = self._test_dir('test_recovery')
   with tf.Graph().as_default():
     gstep = tf.contrib.framework.get_or_create_global_step()
     do_step = tf.assign_add(gstep, 1)
     scaffold = monitored_session.Scaffold()
     # Use a hook to save the model every 100 steps.  It also saves it at
     # the end.
     hooks = [basic_session_run_hooks.CheckpointSaverHook(
         logdir, save_steps=1, scaffold=scaffold)]
     with monitored_session.MonitoredSession(
         session_creator=monitored_session.ChiefSessionCreator(
             scaffold, checkpoint_dir=logdir),
         hooks=hooks) as session:
       self.assertEqual(0, session.run(gstep))
       self.assertEqual(1, session.run(do_step))
       self.assertEqual(2, session.run(do_step))
     # A restart will find the checkpoint and recover automatically.
     with monitored_session.MonitoredSession(
         session_creator=monitored_session.ChiefSessionCreator(
             scaffold, checkpoint_dir=logdir)) as session:
       self.assertEqual(2, session.run(gstep))
 def test_regular_exception_pass_through_run(self):
     # Tests that regular exceptions just pass through a "with
     # MonitoredSession" block and set the session in stop mode.
     with tf.Graph().as_default():
         gstep = tf.contrib.framework.get_or_create_global_step()
         do_step = tf.assign_add(gstep, 1)
         scaffold = monitored_session.Scaffold()
         hook = RaiseOnceAtCountN(4, RuntimeError('regular exception'))
         session = monitored_session.MonitoredSession('',
                                                      scaffold=scaffold,
                                                      hooks=[hook])
         with self.assertRaisesRegexp(RuntimeError, 'regular exception'):
             with session:
                 self.assertEqual(0, session.run(gstep))
                 self.assertEqual(1, session.run(do_step))
                 self.assertEqual(2, session.run(do_step))
                 self.assertFalse(session.should_stop())
                 # This triggers the hook and raises the exception
                 session.run(do_step)
                 # We should not hit this
                 self.assertFalse(True)
         self.assertTrue(hook.raised)
         self.assertTrue(session.should_stop())
Пример #17
0
def _monitored_train(graph,
                     output_dir,
                     train_op,
                     loss_op,
                     global_step_tensor=None,
                     init_op=None,
                     init_feed_dict=None,
                     init_fn=None,
                     log_every_steps=10,
                     supervisor_is_chief=True,
                     supervisor_master='',
                     supervisor_save_model_secs=600,
                     keep_checkpoint_max=5,
                     supervisor_save_summaries_steps=100,
                     feed_fn=None,
                     steps=None,
                     fail_on_nan_loss=True,
                     hooks=None,
                     max_steps=None):
  """Train a model via monitored_session.

  Given `graph`, a directory to write outputs to (`output_dir`), and some ops,
  run a training loop. The given `train_op` performs one step of training on the
  model. The `loss_op` represents the objective function of the training. It is
  expected to increment the `global_step_tensor`, a scalar integer tensor
  counting training steps. This function uses `Supervisor` to initialize the
  graph (from a checkpoint if one is available in `output_dir`), write summaries
  defined in the graph, and write regular checkpoints as defined by
  `supervisor_save_model_secs`.

  Training continues until `global_step_tensor` evaluates to `max_steps`, or, if
  `fail_on_nan_loss`, until `loss_op` evaluates to `NaN`. In that case the
  program is terminated with exit code 1.

  Args:
    graph: A graph to train. It is expected that this graph is not in use
      elsewhere.
    output_dir: A directory to write outputs to.
    train_op: An op that performs one training step when run.
    loss_op: A scalar loss tensor.
    global_step_tensor: A tensor representing the global step. If none is given,
      one is extracted from the graph using the same logic as in `Supervisor`.
    init_op: An op that initializes the graph. If `None`, use `Supervisor`'s
      default.
    init_feed_dict: A dictionary that maps `Tensor` objects to feed values.
      This feed dictionary will be used when `init_op` is evaluated.
    init_fn: Optional callable passed to Supervisor to initialize the model.
    log_every_steps: Output logs regularly. The logs contain timing data and the
      current loss.
    supervisor_is_chief: Whether the current process is the chief supervisor in
      charge of restoring the model and running standard services.
    supervisor_master: The master string to use when preparing the session.
    supervisor_save_model_secs: Save model every
      `supervisor_save_model_secs` seconds when training.
    keep_checkpoint_max: The maximum number of recent checkpoint files to
      keep. As new files are created, older files are deleted. If None or 0,
      all checkpoint files are kept. This is simply passed as the max_to_keep
      arg to tf.Saver constructor.
    supervisor_save_summaries_steps: Save summaries every
      `supervisor_save_summaries_steps` seconds when training.
    feed_fn: A function that is called every iteration to produce a `feed_dict`
      passed to `session.run` calls. Optional.
    steps: Trains for this many steps (e.g. current global step + `steps`).
    fail_on_nan_loss: If true, raise `NanLossDuringTrainingError` if `loss_op`
      evaluates to `NaN`. If false, continue training as if nothing happened.
    hooks: List of `SessionRunHook` subclass instances. Used for callbacks
      inside the training loop.
    max_steps: Number of total steps for which to train model. If `None`,
      train forever. Two calls fit(steps=100) means 200 training iterations.
      On the other hand two calls of fit(max_steps=100) means, second call
      will not do any iteration since first call did all 100 steps.

  Returns:
    The final loss value.

  Raises:
    ValueError: If `output_dir`, `train_op`, `loss_op`, or `global_step_tensor`
      is not provided. See `tf.contrib.framework.get_global_step` for how we
      look up the latter if not provided explicitly.
    NanLossDuringTrainingError: If `fail_on_nan_loss` is `True`, and loss ever
      evaluates to `NaN`.
    ValueError: If both `steps` and `max_steps` are not `None`.
  """
  if (steps is not None) and (max_steps is not None):
    raise ValueError('Can not provide both steps and max_steps.')
  if not output_dir:
    raise ValueError('Output directory should be non-empty %s.' % output_dir)
  if train_op is None:
    raise ValueError('Missing train_op.')
  if loss_op is None:
    raise ValueError('Missing loss_op.')
  if hooks is None:
    hooks = []
  if not isinstance(hooks, list):
    raise ValueError('Hooks should be a list.')
  with graph.as_default():
    global_step_tensor = contrib_variables.assert_or_get_global_step(
        graph, global_step_tensor)
  if global_step_tensor is None:
    raise ValueError('No "global_step" was provided or found in the graph.')

  if max_steps is not None:
    try:
      start_step = checkpoints.load_variable(output_dir,
                                             global_step_tensor.name)
      if max_steps <= start_step:
        logging.info('Skipping training since max_steps has already saved.')
        return None
    except:  # pylint: disable=bare-except
      pass

  # Adapted SessionRunHooks such as ExportMonitor depend on the
  # CheckpointSaverHook to be executed before they should be executed.
  # The `hooks` param comprises of deprecated monitor hooks
  # (such as ExportMonitor). Appending them after the basic_session_run_hooks.
  all_hooks = []
  with graph.as_default():
    all_hooks.extend([
        basic_session_run_hooks.NanTensorHook(
            loss_op, fail_on_nan_loss=fail_on_nan_loss),
        basic_session_run_hooks.LoggingTensorHook({
            'loss': loss_op.name,
            'step': global_step_tensor.name
        }, every_n_iter=log_every_steps),
    ])

    scaffold = monitored_session.Scaffold(
        init_op=init_op,
        init_feed_dict=init_feed_dict,
        init_fn=init_fn,
        saver=tf_saver.Saver(
            sharded=True, max_to_keep=keep_checkpoint_max, defer_build=True))

    if not supervisor_is_chief:
      session_creator = monitored_session.WorkerSessionCreator(
          scaffold=scaffold,
          master=supervisor_master)
    else:
      session_creator = monitored_session.ChiefSessionCreator(
          scaffold=scaffold,
          checkpoint_dir=output_dir,
          master=supervisor_master)
      summary_writer = summary_writer_cache.SummaryWriterCache.get(output_dir)
      all_hooks.append(
          basic_session_run_hooks.StepCounterHook(
              summary_writer=summary_writer))
      all_hooks.append(
          basic_session_run_hooks.SummarySaverHook(
              save_steps=supervisor_save_summaries_steps,
              summary_writer=summary_writer,
              scaffold=scaffold))
      if supervisor_save_model_secs > 0:
        all_hooks.append(
            basic_session_run_hooks.CheckpointSaverHook(
                output_dir,
                save_secs=supervisor_save_model_secs,
                scaffold=scaffold))

    if steps is not None or max_steps is not None:
      all_hooks.append(basic_session_run_hooks.StopAtStepHook(steps, max_steps))
    all_hooks.extend(hooks)

    with monitored_session.MonitoredSession(
        session_creator=session_creator,
        hooks=all_hooks) as super_sess:
      loss = None
      while not super_sess.should_stop():
        _, loss = super_sess.run([train_op, loss_op], feed_fn() if feed_fn else
                                 None)
      return loss