# Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Training helper that checkpoints models and computes summaries."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import contextlib
import os
import time

from tensorflow.core.framework.summary_pb2 import Summary
from tensorflow.core.util.event_pb2 import SessionLog
from tensorflow.python.eager import context
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import meta_graph
from tensorflow.python.framework import ops
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import lookup_ops
from tensorflow.python.ops import variables
from tensorflow.python.platform import tf_logging as logging
from tensorflow.python.summary import summary as _summary
from tensorflow.python.training import coordinator
from tensorflow.python.training import saver as saver_mod
from tensorflow.python.training import session_manager as session_manager_mod
from tensorflow.python.training import training_util
from tensorflow.python.util import deprecation


class Supervisor(object):
  """A training helper that checkpoints models and computes summaries.

  This class is deprecated. Please use
  ${tf.train.MonitoredTrainingSession} instead.

  The Supervisor is a small wrapper around a `Coordinator`, a `Saver`,
  and a `SessionManager` that takes care of common needs of TensorFlow
  training programs.

  #### Use for a single program

  ```python
  with tf.Graph().as_default():
    ...add operations to the graph...
    # Create a Supervisor that will checkpoint the model in '/tmp/mydir'.
    sv = Supervisor(logdir='/tmp/mydir')
    # Get a TensorFlow session managed by the supervisor.
    with sv.managed_session(FLAGS.master) as sess:
      # Use the session to train the graph.
      while not sv.should_stop():
        sess.run(<my_train_op>)
  ```

  Within the `with sv.managed_session()` block all variables in the graph have
  been initialized.  In addition, a few services have been started to
  checkpoint the model and add summaries to the event log.

  If the program crashes and is restarted, the managed session automatically
  reinitialize variables from the most recent checkpoint.

  The supervisor is notified of any exception raised by one of the services.
  After an exception is raised, `should_stop()` returns `True`.  In that case
  the training loop should also stop.  This is why the training loop has to
  check for `sv.should_stop()`.

  Exceptions that indicate that the training inputs have been exhausted,
  `tf.errors.OutOfRangeError`, also cause `sv.should_stop()` to return `True`
  but are not re-raised from the `with` block: they indicate a normal
  termination.

  #### Use for multiple replicas

  To train with replicas you deploy the same program in a `Cluster`.
  One of the tasks must be identified as the *chief*: the task that handles
  initialization, checkpoints, summaries, and recovery.  The other tasks
  depend on the *chief* for these services.

  The only change you have to do to the single program code is to indicate
  if the program is running as the *chief*.

  ```python
  # Choose a task as the chief. This could be based on server_def.task_index,
  # or job_def.name, or job_def.tasks. It's entirely up to the end user.
  # But there can be only one *chief*.
  is_chief = (server_def.task_index == 0)
  server = tf.train.Server(server_def)

  with tf.Graph().as_default():
    ...add operations to the graph...
    # Create a Supervisor that uses log directory on a shared file system.
    # Indicate if you are the 'chief'
    sv = Supervisor(logdir='/shared_directory/...', is_chief=is_chief)
    # Get a Session in a TensorFlow server on the cluster.
    with sv.managed_session(server.target) as sess:
      # Use the session to train the graph.
      while not sv.should_stop():
        sess.run(<my_train_op>)
  ```

  In the *chief* task, the `Supervisor` works exactly as in the first example
  above.  In the other tasks `sv.managed_session()` waits for the Model to have
  been initialized before returning a session to the training code.  The
  non-chief tasks depend on the chief task for initializing the model.

  If one of the tasks crashes and restarts, `managed_session()`
  checks if the Model is initialized.  If yes, it just creates a session and
  returns it to the training code that proceeds normally.  If the model needs
  to be initialized, the chief task takes care of reinitializing it; the other
  tasks just wait for the model to have been initialized.

  NOTE: This modified program still works fine as a single program.
  The single program marks itself as the chief.

  #### What `master` string to use

  Whether you are running on your machine or in the cluster you can use the
  following values for the --master flag:

  * Specifying `''` requests an in-process session that does not use RPC.

  * Specifying `'local'` requests a session that uses the RPC-based
    "Master interface" to run TensorFlow programs. See
    @{tf.train.Server.create_local_server} for
    details.

  * Specifying `'grpc://hostname:port'` requests a session that uses
    the RPC interface to a specific host, and also allows the in-process
    master to access remote tensorflow workers. Often, it is
    appropriate to pass `server.target` (for some `tf.train.Server`
    named `server).

  #### Advanced use

  ##### Launching additional services

  `managed_session()` launches the Checkpoint and Summary services (threads).
  If you need more services to run you can simply launch them in the block
  controlled by `managed_session()`.

  Example: Start a thread to print losses.  We want this thread to run
  every 60 seconds, so we launch it with `sv.loop()`.

  ```python
  ...
  sv = Supervisor(logdir='/tmp/mydir')
  with sv.managed_session(FLAGS.master) as sess:
    sv.loop(60, print_loss, (sess, ))
    while not sv.should_stop():
      sess.run(my_train_op)
  ```

  ##### Launching fewer services

  `managed_session()` launches the "summary" and "checkpoint" threads which use
  either the optionally `summary_op` and `saver` passed to the constructor, or
  default ones created automatically by the supervisor.  If you want to run
  your own summary and checkpointing logic, disable these services by passing
  `None` to the `summary_op` and `saver` parameters.

  Example: Create summaries manually every 100 steps in the chief.

  ```python
  # Create a Supervisor with no automatic summaries.
  sv = Supervisor(logdir='/tmp/mydir', is_chief=is_chief, summary_op=None)
  # As summary_op was None, managed_session() does not start the
  # summary thread.
  with sv.managed_session(FLAGS.master) as sess:
    for step in xrange(1000000):
      if sv.should_stop():
        break
      if is_chief and step % 100 == 0:
        # Create the summary every 100 chief steps.
        sv.summary_computed(sess, sess.run(my_summary_op))
      else:
        # Train normally
        sess.run(my_train_op)
  ```

  ##### Custom model initialization

  `managed_session()` only supports initializing the model by running an
  `init_op` or restoring from the latest checkpoint.  If you have special
  initialization needs, see how to specify a `local_init_op` when creating the
  supervisor.  You can also use the `SessionManager` directly to create a
  session and check if it could be initialized automatically.
  """

  # Value to pass for the 'ready_op', 'init_op', 'summary_op', 'saver',
  # and 'global_step' parameters of Supervisor.__init__() to indicate that
  # the default behavior should be used.
  USE_DEFAULT = 0

  @deprecation.deprecated(None,
                          "Please switch to tf.train.MonitoredTrainingSession")
  def __init__(self,
               graph=None,
               ready_op=USE_DEFAULT,
               ready_for_local_init_op=USE_DEFAULT,
               is_chief=True,
               init_op=USE_DEFAULT,
               init_feed_dict=None,
               local_init_op=USE_DEFAULT,
               logdir=None,
               summary_op=USE_DEFAULT,
               saver=USE_DEFAULT,
               global_step=USE_DEFAULT,
               save_summaries_secs=120,
               save_model_secs=600,
               recovery_wait_secs=30,
               stop_grace_secs=120,
               checkpoint_basename="model.ckpt",
               session_manager=None,
               summary_writer=USE_DEFAULT,
               init_fn=None):
    """Create a `Supervisor`.

    Args:
      graph: A `Graph`.  The graph that the model will use.  Defaults to the
        default `Graph`.  The supervisor may add operations to the graph before
        creating a session, but the graph should not be modified by the caller
        after passing it to the supervisor.
      ready_op: 1-D string `Tensor`.  This tensor is evaluated by supervisors in
        `prepare_or_wait_for_session()` to check if the model is ready to use.
        The model is considered ready if it returns an empty array.  Defaults to
        the tensor returned from `tf.report_uninitialized_variables()`  If
        `None`, the model is not checked for readiness.
      ready_for_local_init_op: 1-D string `Tensor`.  This tensor is evaluated by
        supervisors in `prepare_or_wait_for_session()` to check if the model is
        ready to run the local_init_op.
        The model is considered ready if it returns an empty array.  Defaults to
        the tensor returned from
        `tf.report_uninitialized_variables(tf.global_variables())`. If `None`,
        the model is not checked for readiness before running local_init_op.
      is_chief: If True, create a chief supervisor in charge of initializing
        and restoring the model.  If False, create a supervisor that relies
        on a chief supervisor for inits and restore.
      init_op: `Operation`.  Used by chief supervisors to initialize the model
        when it can not be recovered.  Defaults to an `Operation` that
        initializes all global variables.  If `None`, no initialization is done
        automatically unless you pass a value for `init_fn`, see below.
      init_feed_dict: A dictionary that maps `Tensor` objects to feed values.
        This feed dictionary will be used when `init_op` is evaluated.
      local_init_op: `Operation`. Used by all supervisors to run initializations
        that should run for every new supervisor instance. By default these
        are table initializers and initializers for local variables.
        If `None`, no further per supervisor-instance initialization is
        done automatically.
      logdir: A string.  Optional path to a directory where to checkpoint the
        model and log events for the visualizer.  Used by chief supervisors.
        The directory will be created if it does not exist.
      summary_op: An `Operation` that returns a Summary for the event logs.
        Used by chief supervisors if a `logdir` was specified.  Defaults to the
        operation returned from summary.merge_all().  If `None`, summaries are
        not computed automatically.
      saver: A Saver object.  Used by chief supervisors if a `logdir` was
        specified.  Defaults to the saved returned by Saver().
        If `None`, the model is not saved automatically.
      global_step: An integer Tensor of size 1 that counts steps.  The value
        from 'global_step' is used in summaries and checkpoint filenames.
        Default to the op named 'global_step' in the graph if it exists, is of
        rank 1, size 1, and of type tf.int32 or tf.int64.  If `None` the global
        step is not recorded in summaries and checkpoint files.  Used by chief
        supervisors if a `logdir` was specified.
      save_summaries_secs: Number of seconds between the computation of
        summaries for the event log.  Defaults to 120 seconds.  Pass 0 to
        disable summaries.
      save_model_secs: Number of seconds between the creation of model
        checkpoints.  Defaults to 600 seconds.  Pass 0 to disable checkpoints.
      recovery_wait_secs: Number of seconds between checks that the model
        is ready.  Used by supervisors when waiting for a chief supervisor
        to initialize or restore the model.  Defaults to 30 seconds.
      stop_grace_secs: Grace period, in seconds, given to running threads to
        stop when `stop()` is called.  Defaults to 120 seconds.
      checkpoint_basename: The basename for checkpoint saving.
      session_manager: `SessionManager`, which manages Session creation and
        recovery. If it is `None`, a default `SessionManager` will be created
        with the set of arguments passed in for backwards compatibility.
      summary_writer: `SummaryWriter` to use or `USE_DEFAULT`.  Can be `None`
        to indicate that no summaries should be written.
      init_fn: Optional callable used to initialize the model. Called
        after the optional `init_op` is called.  The callable must accept one
        argument, the session being initialized.

    Returns:
      A `Supervisor`.

    Raises:
      RuntimeError: If called with eager execution enabled.

    @compatibility(eager)
    `Supervisor`s are not supported when eager execution is enabled.
    @end_compatibility
    """
    if context.in_eager_mode():
      raise RuntimeError("Supervisors are compatible with eager execution.")
    # Set default values of arguments.
    if graph is None:
      graph = ops.get_default_graph()
    with graph.as_default():
      self._init_ready_op(
          ready_op=ready_op, ready_for_local_init_op=ready_for_local_init_op)
      self._init_init_op(init_op=init_op, init_feed_dict=init_feed_dict)
      self._init_local_init_op(local_init_op=local_init_op)
      self._init_saver(saver=saver)
      self._init_summary_op(summary_op=summary_op)
      self._init_global_step(global_step=global_step)
    self._graph = graph
    self._meta_graph_def = meta_graph.create_meta_graph_def(
        graph_def=graph.as_graph_def(add_shapes=True),
        saver_def=self._saver.saver_def if self._saver else None)
    self._is_chief = is_chief
    self._coord = coordinator.Coordinator()
    self._recovery_wait_secs = recovery_wait_secs
    self._stop_grace_secs = stop_grace_secs
    self._init_fn = init_fn

    # Set all attributes related to checkpointing and writing events to None.
    # Afterwards, set them appropriately for chief supervisors, as these are
    # the only supervisors that can write checkpoints and events.
    self._logdir = None
    self._save_summaries_secs = None
    self._save_model_secs = None
    self._save_path = None
    self._summary_writer = None

    if self._is_chief:
      self._logdir = logdir
      self._save_summaries_secs = save_summaries_secs
      self._save_model_secs = save_model_secs
      if self._logdir:
        self._save_path = os.path.join(self._logdir, checkpoint_basename)
      if summary_writer is Supervisor.USE_DEFAULT:
        if self._logdir:
          self._summary_writer = _summary.FileWriter(self._logdir)
      else:
        self._summary_writer = summary_writer
      self._graph_added_to_summary = False

    self._init_session_manager(session_manager=session_manager)
    self._verify_setup()
    # The graph is not allowed to change anymore.
    graph.finalize()

  def _init_session_manager(self, session_manager=None):
    if session_manager is None:
      self._session_manager = session_manager_mod.SessionManager(
          local_init_op=self._local_init_op,
          ready_op=self._ready_op,
          ready_for_local_init_op=self._ready_for_local_init_op,
          graph=self._graph,
          recovery_wait_secs=self._recovery_wait_secs)
    else:
      self._session_manager = session_manager

  def _get_first_op_from_collection(self, key):
    """Returns the first `Operation` from a collection.

    Args:
      key: A string collection key.

    Returns:
      The first Op found in a collection, or `None` if the collection is empty.
    """
    try:
      op_list = ops.get_collection(key)
      if len(op_list) > 1:
        logging.info("Found %d %s operations. Returning the first one.",
                     len(op_list), key)
      if op_list:
        return op_list[0]
    except LookupError:
      pass

    return None

  def _init_ready_op(self,
                     ready_op=USE_DEFAULT,
                     ready_for_local_init_op=USE_DEFAULT):
    """Initializes ready_op.

    Args:
      ready_op: `Tensor` to check if the model is initialized.
        If it's set to USE_DEFAULT, creates an op that checks all
        the variables are initialized.
      ready_for_local_init_op: `Tensor` to check if the model is ready to run
        local_init_op.
        If it's set to USE_DEFAULT, creates an op that checks all
        the global variables are initialized.
    """
    if ready_op is Supervisor.USE_DEFAULT:
      ready_op = self._get_first_op_from_collection(ops.GraphKeys.READY_OP)
      if ready_op is None:
        ready_op = variables.report_uninitialized_variables()
        ops.add_to_collection(ops.GraphKeys.READY_OP, ready_op)
    self._ready_op = ready_op

    # ready_for_local_init_op defaults to None for backward compatibility
    if ready_for_local_init_op is Supervisor.USE_DEFAULT:
      ready_for_local_init_op = self._get_first_op_from_collection(
          ops.GraphKeys.READY_FOR_LOCAL_INIT_OP)
    self._ready_for_local_init_op = ready_for_local_init_op

  def _init_init_op(self, init_op=USE_DEFAULT, init_feed_dict=None):
    """Initializes init_op.

    Args:
      init_op: `Operation` to initialize the variables. If set to USE_DEFAULT,
        create an op that initializes all variables and tables.
      init_feed_dict: A dictionary that maps `Tensor` objects to feed values.
        This feed dictionary will be used when `init_op` is evaluated.
    """
    if init_op is Supervisor.USE_DEFAULT:
      init_op = self._get_first_op_from_collection(ops.GraphKeys.INIT_OP)
      if init_op is None:
        init_op = variables.global_variables_initializer()
        ops.add_to_collection(ops.GraphKeys.INIT_OP, init_op)
    self._init_op = init_op
    self._init_feed_dict = init_feed_dict

  def _init_local_init_op(self, local_init_op=USE_DEFAULT):
    """Initializes local_init_op.

    Args:
      local_init_op: `Operation` run for every new supervisor instance. If set
      to USE_DEFAULT, use the first op from the GraphKeys.LOCAL_INIT_OP
      collection. If the collection is empty, create an op that initializes
      all local variables and all tables.
    """
    if local_init_op is Supervisor.USE_DEFAULT:
      local_init_op = self._get_first_op_from_collection(
          ops.GraphKeys.LOCAL_INIT_OP)
      if local_init_op is None:
        op_list = [
            variables.local_variables_initializer(),
            lookup_ops.tables_initializer()
        ]
        if op_list:
          local_init_op = control_flow_ops.group(*op_list)
          ops.add_to_collection(ops.GraphKeys.LOCAL_INIT_OP, local_init_op)
    self._local_init_op = local_init_op

  def _init_saver(self, saver=USE_DEFAULT):
    """Initializes saver.

    Args:
      saver: A `Saver` object. If set to USE_DEFAULT, create one that
        saves all the variables.
    """
    if saver is Supervisor.USE_DEFAULT:
      saver = self._get_first_op_from_collection(ops.GraphKeys.SAVERS)
      if saver is None and variables.global_variables():
        saver = saver_mod.Saver()
        ops.add_to_collection(ops.GraphKeys.SAVERS, saver)
    self._saver = saver

  def _init_summary_op(self, summary_op=USE_DEFAULT):
    """Initializes summary_op.

    Args:
      summary_op: An Operation that returns a Summary for the event logs.
        If set to USE_DEFAULT, create an op that merges all the summaries.
    """
    if summary_op is Supervisor.USE_DEFAULT:
      summary_op = self._get_first_op_from_collection(ops.GraphKeys.SUMMARY_OP)
      if summary_op is None: