LostTech.TensorFlow : API Documentation

Type Supervisor

Namespace tensorflow.train

Parent PythonObjectContainer

Interfaces ISupervisor

A training helper that checkpoints models and computes summaries.

This class is deprecated. Please use `tf.compat.v1.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 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*. 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.distribute.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()`. ##### 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. ##### 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.
Show Example
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() 

Methods

Properties

Fields

Public instance methods

LooperThread loop(object timer_interval_secs, object target, IEnumerable<object> args, IDictionary<string, object> kwargs)

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.
Parameters
object timer_interval_secs
Number. Time boundaries at which to call `target`.
object target
A callable object.
IEnumerable<object> args
Optional arguments to pass to `target` when calling it.
IDictionary<string, object> kwargs
Optional keyword arguments to pass to `target` when calling it.
Returns
LooperThread
The started thread.

object loop_dyn(object timer_interval_secs, object target, object args, object kwargs)

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.
Parameters
object timer_interval_secs
Number. Time boundaries at which to call `target`.
object target
A callable object.
object args
Optional arguments to pass to `target` when calling it.
object kwargs
Optional keyword arguments to pass to `target` when calling it.
Returns
object
The started thread.

IContextManager<T> managed_session(string master, object config, bool start_standard_services, bool close_summary_writer)

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: 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: 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.
Parameters
string master
name of the TensorFlow master to use. See the `tf.compat.v1.Session` constructor for how this is interpreted.
object config
Optional `ConfigProto` proto used to configure the session. Passed as-is to create the session.
bool start_standard_services
Whether to start the standard services, such as checkpoint, summary and step counter.
bool close_summary_writer
Whether to close the summary writer when closing the session. Defaults to True.
Returns
IContextManager<T>
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.
Show Example
def train():
              sv = tf.compat.v1.train.Supervisor(...)
              with sv.managed_session() as sess:
                for step in xrange(..):
                  if sv.should_stop():
                    break
                  sess.run()
                 ...do other things needed at each training step... 

object managed_session_dyn(ImplicitContainer<T> master, object config, ImplicitContainer<T> start_standard_services, ImplicitContainer<T> close_summary_writer)

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: 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: 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.
Parameters
ImplicitContainer<T> master
name of the TensorFlow master to use. See the `tf.compat.v1.Session` constructor for how this is interpreted.
object config
Optional `ConfigProto` proto used to configure the session. Passed as-is to create the session.
ImplicitContainer<T> start_standard_services
Whether to start the standard services, such as checkpoint, summary and step counter.
ImplicitContainer<T> close_summary_writer
Whether to close the summary writer when closing the session. Defaults to True.
Returns
object
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.
Show Example
def train():
              sv = tf.compat.v1.train.Supervisor(...)
              with sv.managed_session() as sess:
                for step in xrange(..):
                  if sv.should_stop():
                    break
                  sess.run()
                 ...do other things needed at each training step... 

Session prepare_or_wait_for_session(string master, object config, bool wait_for_checkpoint, int max_wait_secs, bool start_standard_services)

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.
Parameters
string master
name of the TensorFlow master to use. See the `tf.compat.v1.Session` constructor for how this is interpreted.
object config
Optional ConfigProto proto used to configure the session, which is passed as-is to create the session.
bool wait_for_checkpoint
Whether we should wait for the availability of a checkpoint before creating Session. Defaults to False.
int max_wait_secs
Maximum time to wait for the session to become available.
bool start_standard_services
Whether to start the standard services and the queue runners.
Returns
Session
A Session object that can be used to drive the model.

object prepare_or_wait_for_session_dyn(ImplicitContainer<T> master, object config, ImplicitContainer<T> wait_for_checkpoint, ImplicitContainer<T> max_wait_secs, ImplicitContainer<T> start_standard_services)

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.
Parameters
ImplicitContainer<T> master
name of the TensorFlow master to use. See the `tf.compat.v1.Session` constructor for how this is interpreted.
object config
Optional ConfigProto proto used to configure the session, which is passed as-is to create the session.
ImplicitContainer<T> wait_for_checkpoint
Whether we should wait for the availability of a checkpoint before creating Session. Defaults to False.
ImplicitContainer<T> max_wait_secs
Maximum time to wait for the session to become available.
ImplicitContainer<T> start_standard_services
Whether to start the standard services and the queue runners.
Returns
object
A Session object that can be used to drive the model.

IList<object> start_queue_runners(Session sess, IEnumerable<object> queue_runners)

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.
Parameters
Session sess
A `Session`.
IEnumerable<object> 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
IList<object>
The list of threads started for the `QueueRunners`.

object start_queue_runners_dyn(object sess, object queue_runners)

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.
Parameters
object sess
A `Session`.
object 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
object
The list of threads started for the `QueueRunners`.

IList<object> start_standard_services(Session 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.
Parameters
Session sess
A Session.
Returns
IList<object>
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()

object start_standard_services_dyn(object 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.
Parameters
object sess
A Session.
Returns
object
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()

void stop(IEnumerable<object> threads, bool close_summary_writer, bool ignore_live_threads)

Stop the services and the coordinator.

This does not close the session.
Parameters
IEnumerable<object> 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.
bool close_summary_writer
Whether to close the `summary_writer`. Defaults to `True` if the summary writer was created by the supervisor, `False` otherwise.
bool ignore_live_threads
If `True` ignores threads that remain running after a grace period when joining threads via the coordinator, instead of raising a RuntimeError.

object stop_dyn(object threads, ImplicitContainer<T> close_summary_writer, ImplicitContainer<T> ignore_live_threads)

Stop the services and the coordinator.

This does not close the session.
Parameters
object 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.
ImplicitContainer<T> close_summary_writer
Whether to close the `summary_writer`. Defaults to `True` if the summary writer was created by the supervisor, `False` otherwise.
ImplicitContainer<T> ignore_live_threads
If `True` ignores threads that remain running after a grace period when joining threads via the coordinator, instead of raising a RuntimeError.

void summary_computed(Session sess, IEnumerable<object> summary, object global_step)

Indicate that a summary was computed.
Parameters
Session sess
A `Session` object.
IEnumerable<object> summary
A Summary proto, or a string holding a serialized summary proto.
object global_step
Int. global step this summary is associated with. If `None`, it will try to fetch the current step.

object summary_computed_dyn(object sess, object summary, object global_step)

Indicate that a summary was computed.
Parameters
object sess
A `Session` object.
object summary
A Summary proto, or a string holding a serialized summary proto.
object global_step
Int. global step this summary is associated with. If `None`, it will try to fetch the current step.

object wait_for_stop_dyn()

Block waiting for the coordinator to stop.

Public static methods

Supervisor NewDyn(object graph, ImplicitContainer<T> ready_op, ImplicitContainer<T> ready_for_local_init_op, ImplicitContainer<T> is_chief, ImplicitContainer<T> init_op, object init_feed_dict, ImplicitContainer<T> local_init_op, object logdir, ImplicitContainer<T> summary_op, ImplicitContainer<T> saver, ImplicitContainer<T> global_step, ImplicitContainer<T> save_summaries_secs, ImplicitContainer<T> save_model_secs, ImplicitContainer<T> recovery_wait_secs, ImplicitContainer<T> stop_grace_secs, ImplicitContainer<T> checkpoint_basename, object session_manager, ImplicitContainer<T> summary_writer, object init_fn, object local_init_run_options)

Create a `Supervisor`. (deprecated)

Warning: THIS FUNCTION IS DEPRECATED. It will be removed in a future version. Instructions for updating: Please switch to tf.train.MonitoredTrainingSession
Parameters
object 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.
ImplicitContainer<T> 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.compat.v1.report_uninitialized_variables()` If `None`, the model is not checked for readiness.
ImplicitContainer<T> 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 `None`. If `None`, the model is not checked for readiness before running local_init_op.
ImplicitContainer<T> 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.
ImplicitContainer<T> 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.
object init_feed_dict
A dictionary that maps `Tensor` objects to feed values. This feed dictionary will be used when `init_op` is evaluated.
ImplicitContainer<T> 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.
object 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.
ImplicitContainer<T> 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.
ImplicitContainer<T> 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.
ImplicitContainer<T> 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.
ImplicitContainer<T> save_summaries_secs
Number of seconds between the computation of summaries for the event log. Defaults to 120 seconds. Pass 0 to disable summaries.
ImplicitContainer<T> save_model_secs
Number of seconds between the creation of model checkpoints. Defaults to 600 seconds. Pass 0 to disable checkpoints.
ImplicitContainer<T> 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.
ImplicitContainer<T> stop_grace_secs
Grace period, in seconds, given to running threads to stop when `stop()` is called. Defaults to 120 seconds.
ImplicitContainer<T> checkpoint_basename
The basename for checkpoint saving.
object 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.
ImplicitContainer<T> summary_writer
`SummaryWriter` to use or `USE_DEFAULT`. Can be `None` to indicate that no summaries should be written.
object 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.
object local_init_run_options
RunOptions to be passed as the SessionManager local_init_run_options parameter.
Returns
Supervisor
A `Supervisor`.

Public properties

Coordinator coord get;

Return the Coordinator used by the Supervisor.

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

object coord_dyn get;

Return the Coordinator used by the Supervisor.

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

Nullable<int> global_step get;

Return the global_step Tensor used by the supervisor.

object global_step_dyn get;

Return the global_step Tensor used by the supervisor.

IDictionary<object, object> init_feed_dict get;

Return the feed dictionary used when evaluating the `init_op`.

object init_feed_dict_dyn get;

Return the feed dictionary used when evaluating the `init_op`.

object init_op get;

Return the Init Op used by the supervisor.

object init_op_dyn get;

Return the Init Op used by the supervisor.

bool is_chief get;

Return True if this is a chief supervisor.

object is_chief_dyn get;

Return True if this is a chief supervisor.

object PythonObject get;

Nullable<int> ready_for_local_init_op get;

object ready_for_local_init_op_dyn get;

object ready_op get;

Return the Ready Op used by the supervisor.

object ready_op_dyn get;

Return the Ready Op used by the supervisor.

Nullable<int> save_model_secs get;

Return the delay between checkpoints.

object save_model_secs_dyn get;

Return the delay between checkpoints.

object save_path get;

Return the save path used by the supervisor.

object save_path_dyn get;

Return the save path used by the supervisor.

Nullable<int> save_summaries_secs get;

Return the delay between summary computations.

object save_summaries_secs_dyn get;

Return the delay between summary computations.

object saver get;

Return the Saver used by the supervisor.

object saver_dyn get;

Return the Saver used by the supervisor.

SessionManager session_manager get;

Return the SessionManager used by the Supervisor.

object session_manager_dyn get;

Return the SessionManager used by the Supervisor.

object summary_op get;

Return the Summary Tensor used by the chief supervisor.

object summary_op_dyn get;

Return the Summary Tensor used by the chief supervisor.

object summary_writer get;

Return the SummaryWriter used by the chief supervisor.

object summary_writer_dyn get;

Return the SummaryWriter used by the chief supervisor.

object USE_DEFAULT_dyn get; set;

Public fields

int USE_DEFAULT

return int