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
(self,
master="",
config=None,
start_standard_services=True,
close_summary_writer=True)
| 934 | # pylint: disable=g-doc-return-or-yield,broad-except |
| 935 | @contextlib.contextmanager |
| 936 | def managed_session(self, |
| 937 | master="", |
| 938 | config=None, |
| 939 | start_standard_services=True, |
| 940 | close_summary_writer=True): |
| 941 | """Returns a context manager for a managed session. |
| 942 | |
| 943 | This context manager creates and automatically recovers a session. It |
| 944 | optionally starts the standard services that handle checkpoints and |
| 945 | summaries. It monitors exceptions raised from the `with` block or from the |
| 946 | services and stops the supervisor as needed. |
| 947 | |
| 948 | The context manager is typically used as follows: |
| 949 | |
| 950 | ```python |
| 951 | def train(): |
| 952 | sv = tf.compat.v1.train.Supervisor(...) |
| 953 | with sv.managed_session(<master>) as sess: |
| 954 | for step in xrange(..): |
| 955 | if sv.should_stop(): |
| 956 | break |
| 957 | sess.run(<my training op>) |
| 958 | ...do other things needed at each training step... |
| 959 | ``` |
| 960 | |
| 961 | An exception raised from the `with` block or one of the service threads is |
| 962 | raised again when the block exits. This is done after stopping all threads |
| 963 | and closing the session. For example, an `AbortedError` exception, raised |
| 964 | in case of preemption of one of the workers in a distributed model, is |
| 965 | raised again when the block exits. |
| 966 | |
| 967 | If you want to retry the training loop in case of preemption you can do it |
| 968 | as follows: |
| 969 | |
| 970 | ```python |
| 971 | def main(...): |
| 972 | while True |
| 973 | try: |
| 974 | train() |
| 975 | except tf.errors.Aborted: |
| 976 | pass |
| 977 | ``` |
| 978 | |
| 979 | As a special case, exceptions used for control flow, such as |
| 980 | `OutOfRangeError` which reports that input queues are exhausted, are not |
| 981 | raised again from the `with` block: they indicate a clean termination of |
| 982 | the training loop and are considered normal termination. |
| 983 | |
| 984 | Args: |
| 985 | master: name of the TensorFlow master to use. See the |
| 986 | `tf.compat.v1.Session` constructor for how this is interpreted. |
| 987 | config: Optional `ConfigProto` proto used to configure the session. Passed |
| 988 | as-is to create the session. |
| 989 | start_standard_services: Whether to start the standard services, such as |
| 990 | checkpoint, summary and step counter. |
| 991 | close_summary_writer: Whether to close the summary writer when closing the |
| 992 | session. Defaults to True. |
| 993 |