Distributed execution

See Distributed TensorFlow for more information about how to configure a distributed TensorFlow program.

class tf.train.Server

An in-process TensorFlow server, for use in distributed training.

A tf.train.Server instance encapsulates a set of devices and a tf.Session target that can participate in distributed training. A server belongs to a cluster (specified by a tf.train.ClusterSpec), and corresponds to a particular task in a named job. The server can communicate with any other server in the same cluster.


tf.train.Server.__init__(server_or_cluster_def, job_name=None, task_index=None, protocol=None, config=None, start=True) {:#Server.init}

Creates a new server with the given definition.

The job_name, task_index, and protocol arguments are optional, and override any information provided in server_or_cluster_def.

Args:
  • server_or_cluster_def: A tf.train.ServerDef or tf.train.ClusterDef protocol buffer, or a tf.train.ClusterSpec object, describing the server to be created and/or the cluster of which it is a member.
  • job_name: (Optional.) Specifies the name of the job of which the server is a member. Defaults to the value in server_or_cluster_def, if specified.
  • task_index: (Optional.) Specifies the task index of the server in its job. Defaults to the value in server_or_cluster_def, if specified. Otherwise defaults to 0 if the server's job has only one task.
  • protocol: (Optional.) Specifies the protocol to be used by the server. Acceptable values include "grpc". Defaults to the value in server_or_cluster_def, if specified. Otherwise defaults to "grpc".
  • config: (Options.) A tf.ConfigProto that specifies default configuration options for all sessions that run on this server.
  • start: (Optional.) Boolean, indicating whether to start the server after creating it. Defaults to True.
Raises:

tf.errors.OpError: Or one of its subclasses if an error occurs while creating the TensorFlow server.


tf.train.Server.create_local_server(config=None, start=True)

Creates a new single-process cluster running on the local host.

This method is a convenience wrapper for creating a tf.train.Server with a tf.train.ServerDef that specifies a single-process cluster containing a single task in a job called "local".

Args:
  • config: (Options.) A tf.ConfigProto that specifies default configuration options for all sessions that run on this server.
  • start: (Optional.) Boolean, indicating whether to start the server after creating it. Defaults to True.
Returns:

A local tf.train.Server.


tf.train.Server.target

Returns the target for a tf.Session to connect to this server.

To create a tf.Session that connects to this server, use the following snippet:

server = tf.train.Server(...)
with tf.Session(server.target):
  # ...
Returns:

A string containing a session target for this server.


tf.train.Server.server_def

Returns the tf.train.ServerDef for this server.

Returns:

A tf.train.ServerDef protocol buffer that describes the configuration of this server.


tf.train.Server.start()

Starts this server.

Raises:

tf.errors.OpError: Or one of its subclasses if an error occurs while starting the TensorFlow server.


tf.train.Server.join()

Blocks until the server has shut down.

This method currently blocks forever.

Raises:

tf.errors.OpError: Or one of its subclasses if an error occurs while joining the TensorFlow server.


class tf.train.Supervisor

A training helper that checkpoints models and computes summaries.

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

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.

# 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 , 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.


tf.train.Supervisor.__init__(graph=None, ready_op=0, ready_for_local_init_op=0, is_chief=True, init_op=0, init_feed_dict=None, local_init_op=0, logdir=None, summary_op=0, saver=0, global_step=0, 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=0, init_fn=None) {:#Supervisor.init}

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.all_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 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.


tf.train.Supervisor.managed_session(master='', config=None, start_standard_services=True, close_summary_writer=True)

Returns a context manager for a managed session.

This context manager creates and automatically recovers a session. It optionally starts the standard services that handle checkpoints and summaries. It monitors exceptions raised from the with block or from the services and stops the supervisor as needed.

The context manager is typically used as follows:

def train():
  sv = tf.train.Supervisor(...)
  with sv.managed_session(<master>) as sess:
    for step in xrange(..):
      if sv.should_stop():
        break
      sess.run(<my training op>)
      ...do other things needed at each training step...

An exception raised from the with block or one of the service threads is raised again when the block exits. This is done after stopping all threads and closing the session. For example, an AbortedError exception, raised in case of preemption of one of the workers in a distributed model, is raised again when the block exits.

If you want to retry the training loop in case of preemption you can do it as follows:

def main(...):
  while True
    try:
      train()
    except tf.errors.Aborted:
      pass

As a special case, exceptions used for control flow, such as OutOfRangeError which reports that input queues are exhausted, are not raised again from the with block: they indicate a clean termination of the training loop and are considered normal termination.

Args:
  • master: name of the TensorFlow master to use. See the tf.Session constructor for how this is interpreted.
  • config: Optional ConfigProto proto used to configure the session. Passed as-is to create the session.
  • start_standard_services: Whether to start the standard services, such as checkpoint, summary and step counter.
  • close_summary_writer: Whether to close the summary writer when closing the session. Defaults to True.
Returns:

A context manager that yields a Session restored from the latest checkpoint or initialized from scratch if not checkpoint exists. The session is closed when the with block exits.


tf.train.Supervisor.prepare_or_wait_for_session(master='', config=None, wait_for_checkpoint=False, max_wait_secs=7200, start_standard_services=True)

Make sure the model is ready to be used.

Create a session on 'master', recovering or initializing the model as needed, or wait for a session to be ready. If running as the chief and start_standard_service is set to True, also call the session manager to start the standard services.

Args:
  • master: name of the TensorFlow master to use. See the tf.Session constructor for how this is interpreted.
  • config: Optional ConfigProto proto used to configure the session, which is passed as-is to create the session.
  • wait_for_checkpoint: Whether we should wait for the availability of a checkpoint before creating Session. Defaults to False.
  • max_wait_secs: Maximum time to wait for the session to become available.
  • start_standard_services: Whether to start the standard services and the queue runners.
Returns:

A Session object that can be used to drive the model.


tf.train.Supervisor.start_standard_services(sess)

Start the standard services for 'sess'.

This starts services in the background. The services started depend on the parameters to the constructor and may include:

  • A Summary thread computing summaries every save_summaries_secs.
  • A Checkpoint thread saving the model every save_model_secs.
  • A StepCounter thread measure step time.
Args:
  • sess: A Session.
Returns:

A list of threads that are running the standard services. You can use the Supervisor's Coordinator to join these threads with: sv.coord.Join()

Raises:
  • RuntimeError: If called with a non-chief Supervisor.
  • ValueError: If not logdir was passed to the constructor as the services need a log directory.

tf.train.Supervisor.start_queue_runners(sess, queue_runners=None)

Start threads for QueueRunners.

Note that the queue runners collected in the graph key QUEUE_RUNNERS are already started automatically when you create a session with the supervisor, so unless you have non-collected queue runners to start you do not need to call this explicitly.

Args:
  • sess: A Session.
  • queue_runners: A list of QueueRunners. If not specified, we'll use the list of queue runners gathered in the graph under the key GraphKeys.QUEUE_RUNNERS.
Returns:

The list of threads started for the QueueRunners.


tf.train.Supervisor.summary_computed(sess, summary, global_step=None)

Indicate that a summary was computed.

Args:
  • sess: A Session object.
  • summary: A Summary proto, or a string holding a serialized summary proto.
  • global_step: Int. global step this summary is associated with. If None, it will try to fetch the current step.
Raises:
  • TypeError: if 'summary' is not a Summary proto or a string.
  • RuntimeError: if the Supervisor was created without a logdir.

tf.train.Supervisor.stop(threads=None, close_summary_writer=True)

Stop the services and the coordinator.

This does not close the session.

Args:
  • threads: Optional list of threads to join with the coordinator. If None, defaults to the threads running the standard services, the threads started for QueueRunners, and the threads started by the loop() method. To wait on additional threads, pass the list in this parameter.
  • close_summary_writer: Whether to close the summary_writer. Defaults to True if the summary writer was created by the supervisor, False otherwise.

tf.train.Supervisor.request_stop(ex=None)

Request that the coordinator stop the threads.

See Coordinator.request_stop().

Args:
  • ex: Optional Exception, or Python exc_info tuple as returned by sys.exc_info(). If this is the first call to request_stop() the corresponding exception is recorded and re-raised from join().

tf.train.Supervisor.should_stop()

Check if the coordinator was told to stop.

See Coordinator.should_stop().

Returns:

True if the coordinator was told to stop, False otherwise.


tf.train.Supervisor.stop_on_exception()

Context handler to stop the supervisor when an exception is raised.

See Coordinator.stop_on_exception().

Returns:

A context handler.


tf.train.Supervisor.wait_for_stop()

Block waiting for the coordinator to stop.

Other Methods


tf.train.Supervisor.Loop(timer_interval_secs, target, args=None, kwargs=None)

Start a LooperThread that calls a function periodically.

If timer_interval_secs is None the thread calls target(*args, **kwargs) repeatedly. Otherwise it calls it every timer_interval_secs seconds. The thread terminates when a stop is requested.

The started thread is added to the list of threads managed by the supervisor so it does not need to be passed to the stop() method.

Args:
  • timer_interval_secs: Number. Time boundaries at which to call target.
  • target: A callable object.
  • args: Optional arguments to pass to target when calling it.
  • kwargs: Optional keyword arguments to pass to target when calling it.
Returns:

The started thread.


tf.train.Supervisor.PrepareSession(master='', config=None, wait_for_checkpoint=False, max_wait_secs=7200, start_standard_services=True)

Make sure the model is ready to be used.

Create a session on 'master', recovering or initializing the model as needed, or wait for a session to be ready. If running as the chief and start_standard_service is set to True, also call the session manager to start the standard services.

Args:
  • master: name of the TensorFlow master to use. See the tf.Session constructor for how this is interpreted.
  • config: Optional ConfigProto proto used to configure the session, which is passed as-is to create the session.
  • wait_for_checkpoint: Whether we should wait for the availability of a checkpoint before creating Session. Defaults to False.
  • max_wait_secs: Maximum time to wait for the session to become available.
  • start_standard_services: Whether to start the standard services and the queue runners.
Returns:

A Session object that can be used to drive the model.


tf.train.Supervisor.RequestStop(ex=None)

Request that the coordinator stop the threads.

See Coordinator.request_stop().

Args:
  • ex: Optional Exception, or Python exc_info tuple as returned by sys.exc_info(). If this is the first call to request_stop() the corresponding exception is recorded and re-raised from join().

tf.train.Supervisor.ShouldStop()

Check if the coordinator was told to stop.

See Coordinator.should_stop().

Returns:

True if the coordinator was told to stop, False otherwise.


tf.train.Supervisor.StartQueueRunners(sess, queue_runners=None)

Start threads for QueueRunners.

Note that the queue runners collected in the graph key QUEUE_RUNNERS are already started automatically when you create a session with the supervisor, so unless you have non-collected queue runners to start you do not need to call this explicitly.

Args:
  • sess: A Session.
  • queue_runners: A list of QueueRunners. If not specified, we'll use the list of queue runners gathered in the graph under the key GraphKeys.QUEUE_RUNNERS.
Returns:

The list of threads started for the QueueRunners.


tf.train.Supervisor.StartStandardServices(sess)

Start the standard services for 'sess'.

This starts services in the background. The services started depend on the parameters to the constructor and may include:

  • A Summary thread computing summaries every save_summaries_secs.
  • A Checkpoint thread saving the model every save_model_secs.
  • A StepCounter thread measure step time.
Args:
  • sess: A Session.
Returns:

A list of threads that are running the standard services. You can use the Supervisor's Coordinator to join these threads with: sv.coord.Join()

Raises:
  • RuntimeError: If called with a non-chief Supervisor.
  • ValueError: If not logdir was passed to the constructor as the services need a log directory.

tf.train.Supervisor.Stop(threads=None, close_summary_writer=True)

Stop the services and the coordinator.

This does not close the session.

Args:
  • threads: Optional list of threads to join with the coordinator. If None, defaults to the threads running the standard services, the threads started for QueueRunners, and the threads started by the loop() method. To wait on additional threads, pass the list in this parameter.
  • close_summary_writer: Whether to close the summary_writer. Defaults to True if the summary writer was created by the supervisor, False otherwise.

tf.train.Supervisor.StopOnException()

Context handler to stop the supervisor when an exception is raised.

See Coordinator.stop_on_exception().

Returns:

A context handler.


tf.train.Supervisor.SummaryComputed(sess, summary, global_step=None)

Indicate that a summary was computed.

Args:
  • sess: A Session object.
  • summary: A Summary proto, or a string holding a serialized summary proto.
  • global_step: Int. global step this summary is associated with. If None, it will try to fetch the current step.
Raises:
  • TypeError: if 'summary' is not a Summary proto or a string.
  • RuntimeError: if the Supervisor was created without a logdir.

tf.train.Supervisor.WaitForStop()

Block waiting for the coordinator to stop.


tf.train.Supervisor.coord

Return the Coordinator used by the Supervisor.

The Coordinator can be useful if you want to run multiple threads during your training.

Returns:

A Coordinator object.


tf.train.Supervisor.global_step

Return the global_step Tensor used by the supervisor.

Returns:

An integer Tensor for the global_step.


tf.train.Supervisor.init_feed_dict

Return the feed dictionary used when evaluating the init_op.

Returns:

A feed dictionary or None.


tf.train.Supervisor.init_op

Return the Init Op used by the supervisor.

Returns:

An Op or None.


tf.train.Supervisor.is_chief

Return True if this is a chief supervisor.

Returns:

A bool.


tf.train.Supervisor.loop(timer_interval_secs, target, args=None, kwargs=None)

Start a LooperThread that calls a function periodically.

If timer_interval_secs is None the thread calls target(*args, **kwargs) repeatedly. Otherwise it calls it every timer_interval_secs seconds. The thread terminates when a stop is requested.

The started thread is added to the list of threads managed by the supervisor so it does not need to be passed to the stop() method.

Args:
  • timer_interval_secs: Number. Time boundaries at which to call target.
  • target: A callable object.
  • args: Optional arguments to pass to target when calling it.
  • kwargs: Optional keyword arguments to pass to target when calling it.
Returns:

The started thread.


tf.train.Supervisor.ready_for_local_init_op


tf.train.Supervisor.ready_op

Return the Ready Op used by the supervisor.

Returns:

An Op or None.


tf.train.Supervisor.save_model_secs

Return the delay between checkpoints.

Returns:

A timestamp.


tf.train.Supervisor.save_path

Return the save path used by the supervisor.

Returns:

A string.


tf.train.Supervisor.save_summaries_secs

Return the delay between summary computations.

Returns:

A timestamp.


tf.train.Supervisor.saver

Return the Saver used by the supervisor.

Returns:

A Saver object.


tf.train.Supervisor.session_manager

Return the SessionManager used by the Supervisor.

Returns:

A SessionManager object.


tf.train.Supervisor.summary_op

Return the Summary Tensor used by the chief supervisor.

Returns:

A string Tensor for the summary or None.


tf.train.Supervisor.summary_writer

Return the SummaryWriter used by the chief supervisor.

Returns:

A SummaryWriter.


class tf.train.SessionManager

Training helper that restores from checkpoint and creates session.

This class is a small wrapper that takes care of session creation and checkpoint recovery. It also provides functions that to facilitate coordination among multiple training threads or processes.

  • Checkpointing trained variables as the training progresses.
  • Initializing variables on startup, restoring them from the most recent checkpoint after a crash, or wait for checkpoints to become available.

Usage:

with tf.Graph().as_default():
   ...add operations to the graph...
  # Create a SessionManager that will checkpoint the model in '/tmp/mydir'.
  sm = SessionManager()
  sess = sm.prepare_session(master, init_op, saver, checkpoint_dir)
  # Use the session to train the graph.
  while True:
    sess.run(<my_train_op>)

prepare_session() initializes or restores a model. It requires init_op and saver as an argument.

A second process could wait for the model to be ready by doing the following:

with tf.Graph().as_default():
   ...add operations to the graph...
  # Create a SessionManager that will wait for the model to become ready.
  sm = SessionManager()
  sess = sm.wait_for_session(master)
  # Use the session to train the graph.
  while True:
    sess.run(<my_train_op>)

wait_for_session() waits for a model to be initialized by other processes.


tf.train.SessionManager.__init__(local_init_op=None, ready_op=None, ready_for_local_init_op=None, graph=None, recovery_wait_secs=30) {:#SessionManager.init}

Creates a SessionManager.

The local_init_op is an Operation that is run always after a new session was created. If None, this step is skipped.

The ready_op is an Operation used to check if the model is ready. The model is considered ready if that operation returns an empty string tensor. If the operation returns non empty string tensor, the elements are concatenated and used to indicate to the user why the model is not ready.

The ready_for_local_init_op is an Operation used to check if the model is ready to run local_init_op. The model is considered ready if that operation returns an empty string tensor. If the operation returns non empty string tensor, the elements are concatenated and used to indicate to the user why the model is not ready.

If ready_op is None, the model is not checked for readiness.

recovery_wait_secs is the number of seconds between checks that the model is ready. It is used by processes to wait for a model to be initialized or restored. Defaults to 30 seconds.

Args:
  • local_init_op: An Operation run immediately after session creation. Usually used to initialize tables and local variables.
  • ready_op: An Operation to check if the model is initialized.
  • ready_for_local_init_op: An Operation to check if the model is ready to run local_init_op.
  • graph: The Graph that the model will use.
  • recovery_wait_secs: Seconds between checks for the model to be ready.
Raises:
  • ValueError: If ready_for_local_init_op is not None but local_init_op is None

tf.train.SessionManager.prepare_session(master, init_op=None, saver=None, checkpoint_dir=None, wait_for_checkpoint=False, max_wait_secs=7200, config=None, init_feed_dict=None, init_fn=None)

Creates a Session. Makes sure the model is ready to be used.

Creates a Session on 'master'. If a saver object is passed in, and checkpoint_dir points to a directory containing valid checkpoint files, then it will try to recover the model from checkpoint. If no checkpoint files are available, and wait_for_checkpoint is True, then the process would check every recovery_wait_secs, up to max_wait_secs, for recovery to succeed.

If the model cannot be recovered successfully then it is initialized by either running the provided init_op, or calling the provided init_fn. The local_init_op is also run after init_op and init_fn, regardless of whether the model was recovered successfully, but only if ready_for_local_init_op passes.

It is an error if the model cannot be recovered and no init_op or init_fn or local_init_op are passed.

Args:
  • master: String representation of the TensorFlow master to use.
  • init_op: Optional Operation used to initialize the model.
  • saver: A Saver object used to restore a model.
  • checkpoint_dir: Path to the checkpoint files.
  • wait_for_checkpoint: Whether to wait for checkpoint to become available.
  • max_wait_secs: Maximum time to wait for checkpoints to become available.
  • config: Optional ConfigProto proto used to configure the session.
  • init_feed_dict: Optional dictionary that maps Tensor objects to feed values. This feed dictionary is passed to the session run() call when running the init op.
  • 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 Session object that can be used to drive the model.

Raises:
  • RuntimeError: If the model cannot be initialized or recovered.

tf.train.SessionManager.recover_session(master, saver=None, checkpoint_dir=None, wait_for_checkpoint=False, max_wait_secs=7200, config=None)

Creates a Session, recovering if possible.

Creates a new session on 'master'. If the session is not initialized and can be recovered from a checkpoint, recover it.

Args:
  • master: String representation of the TensorFlow master to use.
  • saver: A Saver object used to restore a model.
  • checkpoint_dir: Path to the checkpoint files.
  • wait_for_checkpoint: Whether to wait for checkpoint to become available.
  • max_wait_secs: Maximum time to wait for checkpoints to become available.
  • config: Optional ConfigProto proto used to configure the session.
Returns:

A pair (sess, initialized) where 'initialized' is True if the session could be recovered and initialized, False otherwise.


tf.train.SessionManager.wait_for_session(master, config=None, max_wait_secs=inf)

Creates a new Session and waits for model to be ready.

Creates a new Session on 'master'. Waits for the model to be initialized or recovered from a checkpoint. It's expected that another thread or process will make the model ready, and that this is intended to be used by threads/processes that participate in a distributed training configuration where a different thread/process is responsible for initializing or recovering the model being trained.

NB: The amount of time this method waits for the session is bounded by max_wait_secs. By default, this function will wait indefinitely.

Args:
  • master: String representation of the TensorFlow master to use.
  • config: Optional ConfigProto proto used to configure the session.
  • max_wait_secs: Maximum time to wait for the session to become available.
Returns:

A Session. May be None if the operation exceeds the timeout specified by config.operation_timeout_in_ms.

Raises:

tf.DeadlineExceededError: if the session is not available after max_wait_secs.


class tf.train.ClusterSpec

Represents a cluster as a set of "tasks", organized into "jobs".

A tf.train.ClusterSpec represents the set of processes that participate in a distributed TensorFlow computation. Every tf.train.Server is constructed in a particular cluster.

To create a cluster with two jobs and five tasks, you specify the mapping from job names to lists of network addresses (typically hostname-port pairs).

cluster = tf.train.ClusterSpec({"worker": ["worker0.example.com:2222",
                                           "worker1.example.com:2222",
                                           "worker2.example.com:2222"],
                                "ps": ["ps0.example.com:2222",
                                       "ps1.example.com:2222"]})

Each job may also be specified as a sparse mapping from task indices to network addresses. This enables a server to be configured without needing to know the identity of (for example) all other worker tasks:

cluster = tf.train.ClusterSpec({"worker": {1: "worker1.example.com:2222"},
                                "ps": ["ps0.example.com:2222",
                                       "ps1.example.com:2222"]})

tf.train.ClusterSpec.as_cluster_def()

Returns a tf.train.ClusterDef protocol buffer based on this cluster.


tf.train.ClusterSpec.as_dict()

Returns a dictionary from job names to their tasks.

For each job, if the task index space is dense, the corresponding value will be a list of network addresses; otherwise it will be a dictionary mapping (sparse) task indices to the corresponding addresses.

Returns:

A dictionary mapping job names to lists or dictionaries describing the tasks in those jobs.

Other Methods


tf.train.ClusterSpec.__bool__() {:#ClusterSpec.bool}


tf.train.ClusterSpec.__eq__(other) {:#ClusterSpec.eq}


tf.train.ClusterSpec.__init__(cluster) {:#ClusterSpec.init}

Creates a ClusterSpec.

Args:
  • cluster: A dictionary mapping one or more job names to (i) a list of network addresses, or (ii) a dictionary mapping integer task indices to network addresses; or a tf.train.ClusterDef protocol buffer.
Raises:
  • TypeError: If cluster is not a dictionary mapping strings to lists of strings, and not a tf.train.ClusterDef protobuf.

tf.train.ClusterSpec.__ne__(other) {:#ClusterSpec.ne}


tf.train.ClusterSpec.__nonzero__() {:#ClusterSpec.nonzero}


tf.train.ClusterSpec.job_tasks(job_name)

Returns a mapping from task ID to address in the given job.

NOTE: For backwards compatibility, this method returns a list. If the given job was defined with a sparse set of task indices, the length of this list may not reflect the number of tasks defined in this job. Use the num_tasks() method to find the number of tasks defined in a particular job.

Args:
  • job_name: The string name of a job in this cluster.
Returns:

A list of task addresses, where the index in the list corresponds to the task index of each task. The list may contain None if the job was defined with a sparse set of task indices.

Raises:
  • ValueError: If job_name does not name a job in this cluster.

tf.train.ClusterSpec.jobs

Returns a list of job names in this cluster.

Returns:

A list of strings, corresponding to the names of jobs in this cluster.


tf.train.ClusterSpec.num_tasks(job_name)

Returns the number of tasks defined in the given job.

Args:
  • job_name: The string name of a job in this cluster.
Returns:

The number of tasks defined in the given job.

Raises:
  • ValueError: If job_name does not name a job in this cluster.

tf.train.ClusterSpec.task_address(job_name, task_index)

Returns the address of the given task in the given job.

Args:
  • job_name: The string name of a job in this cluster.
  • task_index: A non-negative integer.
Returns:

The address of the given task in the given job.

Raises:
  • ValueError: If job_name does not name a job in this cluster, or no task with index task_index is defined in that job.

tf.train.ClusterSpec.task_indices(job_name)

Returns a list of valid task indices in the given job.

Args:
  • job_name: The string name of a job in this cluster.
Returns:

A list of valid task indices in the given job.

Raises:
  • ValueError: If job_name does not name a job in this cluster, or no task with index task_index is defined in that job.

tf.train.replica_device_setter(ps_tasks=0, ps_device='/job:ps', worker_device='/job:worker', merge_devices=True, cluster=None, ps_ops=None, ps_strategy=None)

Return a device function to use when building a Graph for replicas.

Device Functions are used in with tf.device(device_function): statement to automatically assign devices to Operation objects as they are constructed, Device constraints are added from the inner-most context first, working outwards. The merging behavior adds constraints to fields that are yet unset by a more inner context. Currently the fields are (job, task, cpu/gpu).

If cluster is None, and ps_tasks is 0, the returned function is a no-op. Otherwise, the value of ps_tasks is derived from cluster.

By default, only Variable ops are placed on ps tasks, and the placement strategy is round-robin over all ps tasks. A custom ps_strategy may be used to do more intelligent placement, such as tf.contrib.training.GreedyLoadBalancingStrategy.

For example,

# To build a cluster with two ps jobs on hosts ps0 and ps1, and 3 worker
# jobs on hosts worker0, worker1 and worker2.
cluster_spec = {
    "ps": ["ps0:2222", "ps1:2222"],
    "worker": ["worker0:2222", "worker1:2222", "worker2:2222"]}
with tf.device(tf.replica_device_setter(cluster=cluster_spec)):
  # Build your graph
  v1 = tf.Variable(...)  # assigned to /job:ps/task:0
  v2 = tf.Variable(...)  # assigned to /job:ps/task:1
  v3 = tf.Variable(...)  # assigned to /job:ps/task:0
# Run compute
Args:
  • ps_tasks: Number of tasks in the ps job. Ignored if cluster is provided.
  • ps_device: String. Device of the ps job. If empty no ps job is used. Defaults to ps.
  • worker_device: String. Device of the worker job. If empty no worker job is used.
  • merge_devices: Boolean. If True, merges or only sets a device if the device constraint is completely unset. merges device specification rather than overriding them.
  • cluster: ClusterDef proto or ClusterSpec.
  • ps_ops: List of strings representing Operation types that need to be placed on ps devices. If None, defaults to ["Variable"].
  • ps_strategy: A callable invoked for every ps Operation (i.e. matched by ps_ops), that takes the Operation and returns the ps task index to use. If None, defaults to a round-robin strategy across all ps devices.
Returns:

A function to pass to tf.device().

Raises:

TypeError if cluster is not a dictionary or ClusterDef protocol buffer, or if ps_strategy is provided but not a callable.


class tf.train.Scaffold

Structure to create or gather pieces commonly needed to train a model.

When you build a model for training you usually need ops to initialize variables, a Saver to checkpoint them, an op to collect summaries for the visualizer, and so on.

Various libraries built on top of the core TensorFlow library take care of creating some or all of these pieces and storing them in well known collections in the graph. The Scaffold class helps pick these pieces from the graph collections, creating and adding them to the collections if needed.

If you call the scaffold constructor without any arguments, it will pick pieces from the collections, creating default ones if needed when scaffold.finalize() is called. You can pass arguments to the constructor to provide your own pieces. Pieces that you pass to the constructor are not added to the graph collections.

The following pieces are directly accessible as attributes of the Scaffold object:

  • saver: A tf.Saver object taking care of saving the variables. Picked from and stored into the SAVERS collection in the graph.
  • init_op: An op to run to initialize the variables. Picked from and stored into the INIT_OP collection in the graph.
  • ready_op: An op to verify that the variables are initialized. Picked from and stored into the READY_OP collection in the graph.
  • local_init_op: An op to initialize the local variables. Picked from and stored into the LOCAL_INIT_OP collection in the graph.
  • summary_op: An op to run and merge the summaries in the graph. Picked from and stored into the SUMMARY_OP collection in the graph.
  • global_step: A tensor containing the global step counter. Picked from and stored into the GLOBAL_STEP collection in the graph.

You can also pass the following additional pieces to the constructor:

  • init_feed_dict: A sessionn feed dictionary that should be used when running the init op.
  • init_fn: A callable to run run after the init op to perform additional initializations. The callable will be called as init_fn(scaffold, session).

tf.train.Scaffold.__init__(init_op=None, init_feed_dict=None, init_fn=None, ready_op=None, local_init_op=None, summary_op=None, saver=None) {:#Scaffold.init}

Create a scaffold.

Args:
  • init_op: Optional op for initializing variables.
  • init_feed_dict: Optional session feed dictionary to use when running the init_op.
  • init_fn: Optional function to use to initialize the model after running the init_op. Will be called as init_fn(scaffold, session).
  • ready_op: Optional op to verify that the variables are initialized. Must return an empty scalar string tensor when the variables are initialized, or a non-empty one listing the names of the non-initialized variables.
  • local_init_op: Optional op to initialize local variables.
  • summary_op: Optional op to gather all summaries. Must return a scalar string tensor containing a serialized Summary proto.
  • saver: Optional tf.Saver object to use to save and restore variables.

tf.train.Scaffold.finalize()

Creates operations if needed and finalizes the graph.


tf.train.Scaffold.get_or_default(arg_name, collection_key, default_constructor)

Get from cache or create a default operation.


tf.train.Scaffold.init_feed_dict


tf.train.Scaffold.init_fn


tf.train.Scaffold.init_op


tf.train.Scaffold.local_init_op


tf.train.Scaffold.ready_op


tf.train.Scaffold.saver


tf.train.Scaffold.summary_op


tf.train.MonitoredTrainingSession(master='', is_chief=True, checkpoint_dir=None, scaffold=None, hooks=None, chief_only_hooks=None, save_checkpoint_secs=600, save_summaries_steps=100, config=None)

Creates a MonitoredSession for training.

For a chief, this utility sets proper session initializer/restorer. It also creates hooks related to checkpoint and summary saving. For workers, this utility sets proper session creator which waits for the chief to inialize/restore.

Args:
  • master: String the TensorFlow master to use.
  • is_chief: If True, it will take care of initialization and recovery the underlying TensorFlow session. If False, it will wait on a chief to initialize or recover the TensorFlow session.
  • checkpoint_dir: A string. Optional path to a directory where to restore variables.
  • scaffold: A Scaffold used for gathering or building supportive ops. If not specified, a default one is created. It's used to finalize the graph.
  • hooks: Optional list of SessionRunHook objects.
  • chief_only_hooks: list of SessionRunHook objects. Activate these hooks if is_chief==True, ignore otherwise.
  • save_checkpoint_secs: The frequency, in seconds, that a checkpoint is saved using a default checkpoint saver. If save_checkpoint_secs is set to None, then the default checkpoint saver isn't used.
  • save_summaries_steps: The frequency, in number of global steps, that the summaries are written to disk using a default summary saver. If save_summaries_steps is set to None, then the default summary saver isn't used.
  • config: an instance of tf.ConfigProto proto used to configure the session. It's the config argument of constructor of tf.Session.
Returns:

A MonitoredSession object.


class tf.train.SessionCreator

A factory for tf.Session.


tf.train.SessionCreator.create_session()


class tf.train.ChiefSessionCreator

Creates a tf.Session for a chief.


tf.train.ChiefSessionCreator.__init__(scaffold=None, master='', config=None, checkpoint_dir=None) {:#ChiefSessionCreator.init}

Initializes a chief session creator.

Args:
  • scaffold: A Scaffold used for gathering or building supportive ops. If not specified a default one is created. It's used to finalize the graph.
  • master: String representation of the TensorFlow master to use.
  • config: ConfigProto proto used to configure the session.
  • checkpoint_dir: A string. Optional path to a directory where to restore variables.

tf.train.ChiefSessionCreator.create_session()


class tf.train.WorkerSessionCreator

Creates a tf.Session for a worker.


tf.train.WorkerSessionCreator.__init__(scaffold=None, master='', config=None) {:#WorkerSessionCreator.init}

Initializes a worker session creator.

Args:
  • scaffold: A Scaffold used for gathering or building supportive ops. If not specified a default one is created. It's used to finalize the graph.
  • master: String representation of the TensorFlow master to use.
  • config: ConfigProto proto used to configure the session.

tf.train.WorkerSessionCreator.create_session()


class tf.train.MonitoredSession

Session-like object that handles initialization, recovery and hooks.

Example usage:

saver_hook = CheckpointSaverHook(...)
summary_hook = SummaryHook(...)
with MonitoredSession(session_creator=ChiefSessionCreator(...),
                      hooks=[saver_hook, summary_hook]) as sess:
  while not sess.should_stop():
    sess.run(train_op)

Initialization: At creation time the monitored session does following things in given order:

  • calls hook.begin()
  • finalizes the graph via scaffold.finalize()
  • create session
  • initializes the model via initialization ops provided by Scaffold
  • restores variables if a checkpoint exists
  • launches queue runners

Run: When run() is called, the monitored session does following things:

  • calls hook.before_run()
  • calls TensorFlow session.run() with merged fetches and feed_dict
  • calls hook.after_run()
  • returns result of session.run() asked by user
  • if AbortedError occurs, it recovers or reinitializes the session before executing the run() call again

Exit: At the close(), the monitored session does following things in order:

  • calls hook.end()
  • closes the queue runners and the session
  • surpresses OutOfRange error which indicates that all inputs have been processed if the monitored_session is used as a context.

How to set tf.Session arguments: In most cases you can set session arguments as follows: python MonitoredSession( session_creator=ChiefSessionCreator(master=..., config=...)) In distributed setting for a non-chief worker, you can use following: python MonitoredSession( session_creator=WorkerSessionCreator(master=..., config=...)) See MonitoredTrainingSession for an example usage based on chief or worker.


tf.train.MonitoredSession.__enter__() {:#MonitoredSession.enter}


tf.train.MonitoredSession.__exit__(exception_type, exception_value, traceback) {:#MonitoredSession.exit}


tf.train.MonitoredSession.__init__(session_creator=None, hooks=None) {:#MonitoredSession.init}

Creates a MonitoredSession.

Args:
  • session_creator: A factory object to create session. Typically a ChiefSessionCreator which is the default one.
  • hooks: An iterable of `SessionRunHook' objects.

tf.train.MonitoredSession.close()


tf.train.MonitoredSession.graph

The graph that was launched in this session.


tf.train.MonitoredSession.run(fetches, feed_dict=None, options=None, run_metadata=None)

Run ops in the monitored session.

This method is completely compatible with the tf.Session.run() method.

Args:
  • fetches: Same as tf.Session.run().
  • feed_dict: Same as tf.Session.run().
  • options: Same as tf.Session.run().
  • run_metadata: Same as tf.Session.run().
Returns:

Same as tf.Session.run().


tf.train.MonitoredSession.should_stop()