
    BVh                     (   d Z ddlZddlZddlZddlmZ ddlmZ ddlm	Z	 ddl
mZ ddl
mZ ddl
mZ dd	lmZ dd
lmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlm Z  ddl!m"Z"  e"dg       G d d             Z# G d dejH                        Z% G d dejH                        Z& G d dejH                        Z' e(e#de#jR                          e(e#de#jT                          e(e#d e#jV                          e(e#d!e#jX                          e(e#d"e#jZ                          e(e#d#e#j\                          e(e#d$e#j^                          e(e#d%e#j`                          e(e#d&e#jb                          e(e#d'e#jd                         y)(z?Training helper that checkpoints models and computes summaries.    N)Summary)
SessionLog)context)dtypes)
meta_graph)ops)control_flow_ops)
lookup_ops)	variables)
tf_logging)summary)coordinatorsaversession_manager)training_util)deprecation)	tf_exportztrain.Supervisor)v1c                   6   e Zd ZdZdZ ej                  dd      deedededeeeddddd	deddfd
       Zd/dZd Z	eefdZ
edfdZefdZefdZefdZefdZed        Zed        Zed        Zed        Zed        Zed        Zed        Zed        Zed        Zed        Zed        Zed        Zed        Zed         Zd! Zd" Z 	 	 	 	 	 d0d#Z!d/d$Z"d1d%Z#	 	 	 d2d&Z$d/d'Z%d( Z&d) Z'd* Z(d/d+Z)d, Z*d- Z+e,jZ                  	 	 	 	 d3d.       Z.y)4
Supervisora  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

  ```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.distribute.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.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()`.

  ```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 range(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.
  r   Nz2Please switch to tf.train.MonitoredTrainingSessionTx   iX     z
model.ckptc                    t        j                         rt        d      |t        j                         }|j                         5  | j                  ||       | j                  ||       | j                  |       | j                  |
       | j                  |	       | j                  |       ddd       || _        t        j                  |j                  d	
      | j                   r| j                   j"                  nd      | _        || _        t)        j*                         | _        || _        || _        || _        || _        d| _        d| _        d| _        d| _        d| _        | j&                  r|| _        || _        || _        | j6                  r/t@        jB                  jE                  | j6                  |      | _        |tF        jH                  u r1| j6                  r,tK        jL                  | j6                        | _        n|| _        d| _'        | jQ                  |       | jS                          |jU                          y# 1 sw Y   xY w)a  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.compat.v1.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 `None`. 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.
      local_init_run_options: RunOptions to be passed as the SessionManager
        local_init_run_options parameter.

    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
    z2Supervisors are incompatible with eager execution.N)ready_opready_for_local_init_op)init_opinit_feed_dict)local_init_opr   )
summary_opglobal_stepT
add_shapes)	graph_def	saver_defFr   )+r   executing_eagerlyRuntimeErrorr   get_default_graph
as_default_init_ready_op_init_init_op_init_local_init_op_init_saver_init_summary_op_init_global_step_graphr   create_meta_graph_defas_graph_def_saverr'   _meta_graph_def	_is_chiefr   Coordinator_coord_recovery_wait_secs_stop_grace_secs_init_fn_local_init_run_options_logdir_save_summaries_secs_save_model_secs
_save_path_summary_writerospathjoinr   USE_DEFAULT_summary
FileWriter_graph_added_to_summary_init_session_manager_verify_setupfinalize)selfgraphr   r   is_chiefr   r   r    logdirr!   r   r#   save_summaries_secssave_model_secsrecovery_wait_secsstop_grace_secscheckpoint_basenamer   summary_writerinit_fnlocal_init_run_optionss                        U/home/dcms/DCMS/lib/python3.12/site-packages/tensorflow/python/training/supervisor.py__init__zSupervisor.__init__   s	   J   "MNN}##%e				 6
5L  N
H
];
U#
z2
56 DK%;;$$$5+/;;$++''DBD DN))+DK1D+DDM#9D 
 DL $D DDOD~~dl"5d-d	'',,t||5HI	:11	1<<!)!4!4T\\!B$
-%*d"?	NNY6 6s   A/IIc                     |]t        j                  | j                  | j                  | j                  | j
                  | j                  | j                        | _        y || _        y )N)r    r   r   rN   rS   rX   )	session_manager_modSessionManager_local_init_op	_ready_op_ready_for_local_init_opr2   r:   r=   _session_manager)rM   r   s     rY   rJ   z Supervisor._init_session_managerc  sW    1@@++>>"&"?"?!55!%!=!=?d .d    c                     	 t        j                  |      }t        |      dkD  r t        j                  dt        |      |       |r|d   S 	 y# t
        $ r Y yw xY w)zReturns 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.
       z0Found %d %s operations. Returning the first one.r   N)r   get_collectionlenlogginginfoLookupError)rM   keyop_lists      rY   _get_first_op_from_collectionz(Supervisor._get_first_op_from_collectiono  si    ""3'g	W	G\3	(	qz 

   
s   A	A 	AAc                    |t         j                  u rm| j                  t        j                  j
                        }|Bt        j                         }t        j                  t        j                  j
                  |       || _	        |t         j                  u r)| j                  t        j                  j                        }|| _        y)a  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.
    N)r   rF   rl   r   	GraphKeysREADY_OPr   report_uninitialized_variablesadd_to_collectionr_   READY_FOR_LOCAL_INIT_OPr`   )rM   r   r   s      rY   r,   zSupervisor._init_ready_op  s     :)))33CMM4J4JKh		;;=cmm44h?DN *"8"88 $ B B
--
/
/!1$;D!rb   c                    |t         j                  u rm| j                  t        j                  j
                        }|Bt        j                         }t        j                  t        j                  j
                  |       || _	        || _
        y)aH  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.
    N)r   rF   rl   r   rn   INIT_OPr   global_variables_initializerrq   _init_op_init_feed_dict)rM   r   r   s      rY   r-   zSupervisor._init_init_op  sh     *(((223==3H3HIg	88:cmm33W=DM)Drb   c                 `   |t         j                  u r| j                  t        j                  j
                        }|jt        j                         t        j                         g}|r@t        j                  | }t        j                  t        j                  j
                  |       || _        y)a=  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.
    N)r   rF   rl   r   rn   LOCAL_INIT_OPr   local_variables_initializerr
   tables_initializerr	   grouprq   r^   )rM   r    rk   s      rY   r.   zSupervisor._init_local_init_op  s     
...88
--
%
%'m		113))+
 *00':-


 ; ;]
K'Drb   c                 8   |t         j                  u r| j                  t        j                  j
                        }|Vt        j                         rBt        j                         }t        j                  t        j                  j
                  |       || _        y)zInitializes saver.

    Args:
      saver: A `Saver` object. If set to USE_DEFAULT, create one that saves all
        the variables.
    N)r   rF   rl   r   rn   SAVERSr   global_variables	saver_modSaverrq   r5   )rM   r   s     rY   r/   zSupervisor._init_saver  si     
&&&001E1EFe	9557!cmm22E:DKrb   c                    |t         j                  u ro| j                  t        j                  j
                        }|Dt        j                         }|.t        j                  t        j                  j
                  |       || _	        y)zInitializes 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.
    N)
r   rF   rl   r   rn   
SUMMARY_OPrG   	merge_allrq   _summary_op)rM   r!   s     rY   r0   zSupervisor._init_summary_op  sh     Z+++55cmm6N6NOj		'')
!


 8 8*
E!Drb   c                    |t         j                  u rk| j                  t        j                  j
                        }|@| j                         }|.t        j                  t        j                  j
                  |       || _        y)zInitializes global_step.

    Args:
      global_step: An integer Tensor of size 1 that counts steps. If set to
        USE_DEFAULT, creates global_step tensor.
    N)	r   rF   rl   r   rn   GLOBAL_STEP_default_global_step_tensorrq   _global_step)rM   r#   s     rY   r1   zSupervisor._init_global_step  sk     j,,,66
--
#
#%k		668"


 9 9;
G#Drb   c                     | j                   S )zKReturn True if this is a chief supervisor.

    Returns:
      A bool.
    )r7   rM   s    rY   rO   zSupervisor.is_chief       >>rb   c                     | j                   S )zcReturn the SessionManager used by the Supervisor.

    Returns:
      A SessionManager object.
    )ra   r   s    rY   r   zSupervisor.session_manager          rb   c                     | j                   S )zReturn 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.
    )r9   r   s    rY   coordzSupervisor.coord  s     ;;rb   c                     | j                   S )zTReturn the Init Op used by the supervisor.

    Returns:
      An Op or `None`.
    )rv   r   s    rY   r   zSupervisor.init_op  s     ==rb   c                     | j                   S )ztReturn the feed dictionary used when evaluating the `init_op`.

    Returns:
      A feed dictionary or `None`.
    )rw   r   s    rY   r   zSupervisor.init_feed_dict       rb   c                     | j                   S )zUReturn the Ready Op used by the supervisor.

    Returns:
      An Op or `None`.
    )r_   r   s    rY   r   zSupervisor.ready_op"  r   rb   c                     | j                   S N)r`   r   s    rY   r   z"Supervisor.ready_for_local_init_op+  s    (((rb   c                     | j                   S )z`Return the SummaryWriter used by the chief supervisor.

    Returns:
      A SummaryWriter.
    )rB   r   s    rY   rV   zSupervisor.summary_writer/  r   rb   c                     | j                   S )z{Return the Summary Tensor used by the chief supervisor.

    Returns:
      A string Tensor for the summary or `None`.
    )r   r   s    rY   r!   zSupervisor.summary_op8  s     rb   c                     | j                   S )zTReturn the delay between summary computations.

    Returns:
      A timestamp.
    )r?   r   s    rY   rQ   zSupervisor.save_summaries_secsA  s     $$$rb   c                     | j                   S )zuReturn the global_step Tensor used by the supervisor.

    Returns:
      An integer Tensor for the global_step.
    )r   r   s    rY   r#   zSupervisor.global_stepJ  s     rb   c                     | j                   S )zQReturn the Saver used by the supervisor.

    Returns:
      A Saver object.
    )r5   r   s    rY   r   zSupervisor.saverS  s     ;;rb   c                     | j                   S )zKReturn the delay between checkpoints.

    Returns:
      A timestamp.
    )r@   r   s    rY   rR   zSupervisor.save_model_secs\  r   rb   c                     | j                   S )zOReturn the save path used by the supervisor.

    Returns:
      A string.
    )rA   r   s    rY   	save_pathzSupervisor.save_pathe  s     ??rb   c                    | j                   sJ | j                  r;t        j                  | j                  j                  d      | j                  d       | j                  r_| j                  sR| j                  j                  | j                         | j                  j                  | j                         d| _        yyy)zBWrites graph_def to `logdir` and adds it to summary if applicable.Tr$   zgraph.pbtxtN)r7   r>   r   write_graphr2   r4   rB   rI   	add_graphadd_meta_graphr6   r   s    rY   _write_graphzSupervisor._write_graphn  s    >>>||
++
"
"d
"
3T\\
 D$@$@
$$T[[1
))$*>*>?%)d" %Arb   c                    | j                   st        d      | j                  st        j                  d       y| j
                  `| j                  rTt        j                  || j
                        }| j                  j                  t        t        j                        |       g }| j                  rZ| j                  rN| j                  |j                  t        | |             | j
                  |j                  t!        | |             | j"                  r'| j$                  r|j                  t'        | |             |D ]  }|j)                           |S )a  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(<list of threads>)

    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.
    zcOnly chief supervisor can start standard services. Because only chief supervisors can write events.z>Standard services need a 'logdir' passed to the SessionManagerNstatus)r7   r)   r>   rg   warningr   rB   r   r#   add_session_logr   STARTr?   r   appendSVSummaryThreadSVStepCounterThreadr   r@   SVTimerCheckpointThreadstart)rM   sesscurrent_stepthreadsts        rY   start_standard_servicesz"Supervisor.start_standard_servicesz  s&   . >> L M M <<oo 5 6$)=)= #..tT5F5FGl
**
J,,
-|= G  T%9%9				%tT23				&*467zzd++nn,T489 ggiNrb   c                 H   | j                   j                          | j                  r| j                  j                          | j                  r| j
                  j                  || j                  | j                  | j                  |||| j                  | j                  	      }| j                          |rEt        j                  d       | j                  |       n| j
                  j!                  |||      }|r&t        j                  d       | j#                  |       |S )a  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.compat.v1.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.
    )r   r   checkpoint_dirwait_for_checkpointmax_wait_secsconfigr   rW   zStarting standard services.)r   r   zStarting queue runners.)r9   
clear_stoprB   reopenr7   ra   prepare_sessionr   r   r>   rw   r<   r   rg   rh   r   wait_for_sessionstart_queue_runners)rM   masterr   r   r   r   r   s          rY   prepare_or_wait_for_sessionz&Supervisor.prepare_or_wait_for_session  s    < 	KK
!!#~~""22
,,

1%---- 3 	!d 	 23$$T*""33
} 4 >dll,-
t$Krb   c           	         t        j                         rt        d      |3| j                  j	                  t
        j                  j                        }g }|D ]0  }|j                  |j                  || j                  dd             2 |S )aJ  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`.

    Raises:
      RuntimeError: If called with eager execution enabled.

    @compatibility(eager)
    Queues are not compatible with eager execution. To ingest data when eager
    execution is enabled, use the `tf.data` API.
    @end_compatibility
    z/Queues are not compatible with eager execution.T)r   daemonr   )r   r(   r)   r2   re   r   rn   QUEUE_RUNNERSextendcreate_threadsr9   )rM   r   queue_runnersr   qrs        rY   r   zSupervisor.start_queue_runners  s    2   "JKKkk001L1LMmG Onn


DD

MOO Nrb   c                 n    t        j                  | j                  ||||      }|j                          |S )a  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.
    )targetargskwargs)r   LooperThreadr9   r   )rM   timer_interval_secsr   r   r   loopers         rY   loopzSupervisor.loop
  s7    & %%F LLNMrb   c                 $   | j                   j                          	 | j                   j                  || j                  |       |rb| j                  rU| j                  j                  t        t        j                               | j                  j                          d| _	        yyy# |rb| j                  rU| j                  j                  t        t        j                               | j                  j                          d| _	        w w w xY w)a  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.
      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.
    )stop_grace_period_secsignore_live_threadsr   FN)
r9   request_stoprE   r;   rB   r   r   STOPcloserI   )rM   r   close_summary_writerr   s       rY   stopzSupervisor.stop&  s    * 	KK- kk
!%!6!61  3 
$"6"6 	,,Zz-OP""$',$ #7		$"6"6 	,,Zz-OP""$',$ #7	s   (B) )A&Dc                 <    | j                   j                  |       y)aE  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()`.
    )exN)r9   r   )rM   r   s     rY   r   zSupervisor.request_stopM  s     	KK#rb   c                 6    | j                   j                         S )zCheck if the coordinator was told to stop.

    See `Coordinator.should_stop()`.

    Returns:
      True if the coordinator was told to stop, False otherwise.
    )r9   should_stopr   s    rY   r   zSupervisor.should_stopY  s     ;;""$$rb   c                 6    | j                   j                         S )zContext handler to stop the supervisor when an exception is raised.

    See `Coordinator.stop_on_exception()`.

    Returns:
      A context handler.
    )r9   stop_on_exceptionr   s    rY   r   zSupervisor.stop_on_exceptionc  s     ;;((**rb   c                 8    | j                   j                          y)z*Block waiting for the coordinator to stop.N)r9   wait_for_stopr   s    rY   r   zSupervisor.wait_for_stopm  s    KKrb   c                     | j                   st        d      |,| j                   t        j                  || j                        }| j                   j	                  ||       y)a  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`.
    z,Writing a summary requires a summary writer.N)rB   r)   r#   r   add_summary)rM   r   r   r#   s       rY   summary_computedzSupervisor.summary_computedq  sX     GHHt//;!--dD4D4DEk$$Wk:rb   c                    	 t        j                         j                  d      }|j                  j                  t
        j                  t
        j                  fv r|S t        j                  d|j                         y# t        $ r Y yw xY w)zlReturns the global_step from the default graph.

    Returns:
      The global step `Tensor` or `None`.
    zglobal_step:0z*Found 'global_step' is not an int type: %sN)r   r*   get_tensor_by_namedtype
base_dtyper   int32int64rg   r   KeyError)rM   gss     rY   r   z&Supervisor._default_global_step_tensor  sl      "55oFb			v|| <	<	DbhhO s   AA>  A> >	B
	B
c                     | j                   sI| j                  j                         D ]+  }|j                  dv s|j                  rt        d|z         yy)zUCheck that all is good.

    Raises:
      ValueError: If something is not good.
    )Variable
VariableV2zAWhen using replicas, all Variables must have their device set: %sN)r7   r2   get_operationstypedevice
ValueError)rM   ops     rY   rK   zSupervisor._verify_setup  sY     >>**, 8"7700 2467 8 88 rb   c              #     K   	 | j                  |||      }| 	 | j                  |       	 j	                          y# t        $ r}| j                  |       Y d}~Dd}~ww xY w# t        $ r Y yw xY w# 	 j	                          w # t        $ r Y w w xY wxY w# 	 | j                  |       	 j	                          w # t        $ r Y w w xY w# 	 j	                          w # t        $ r Y w w xY wxY wxY ww)a  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:

    ```python
    def train():
      sv = tf.compat.v1.train.Supervisor(...)
      with sv.managed_session(<master>) as sess:
        for step in range(..):
          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:

    ```python
    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.compat.v1.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.
    )r   r   r   N)r   )r   	Exceptionr   r   r   )rM   r   r   r   r   r   es          rY   managed_sessionzSupervisor.managed_session  s    @--"9 . ;d j 			';	<
	
**,  
   	
		
**, 	
	 			';	<
	
**, 	
		
**, 	
	s   C9A A7 A(  C9	A%
A B  A%%B (	A41C93A44C97B9B
	B
	BBBBC9C6C1CC6	CC6CC6C3C$#C3$	C0-C3/C00C33C66C9r   ) NFi   T)NN)NTF)r   NTT)/__name__
__module____qualname____doc__rF   r   
deprecatedrZ   rJ   rl   r,   r-   r.   r/   r0   r1   propertyrO   r   r   r   r   r   r   rV   r!   rQ   r#   r   rR   r   r   r   r   r   r   r   r   r   r   r   r   r   rK   
contextlibcontextmanagerr    rb   rY   r   r   '   sc   [@ +;$NP #'2""(% &#&""$"#/#)&*)TPTl
., *-8<4 #.d *" /: (, *  )4 " +6 $    ! ! 	 	         ) )       % %     ! !  
*2j *,)-6;04:>7r!F:  $$%-N
$%+ ;& 8 !.2+/	W Wrb   r   c                   (     e Zd ZdZ fdZd Z xZS )r   z&A thread to save summaries on a timer.c                 r    t         t        |   |j                  |j                         || _        || _        y)z\Create a SVSummaryThread.

    Args:
      sv: A `Supervisor`.
      sess: A `Session`.
    N)superr   rZ   r   rQ   _sv_sessrM   svr   	__class__s      rY   rZ   zSVSummaryThread.__init__  s.     
/4)"((B4J4JKDHDJrb   c                    | j                   j                  I| j                  j                  | j                   j                  | j                   j                  g      \  }}n1| j                  j                  | j                   j                        }d }| j                   j
                  r=t        j                  d|       | j                   j
                  j                  ||       y y )NzRecording summary at step %s.)	r  r#   r  runr!   rV   rg   rh   r   )rM   summary_strsr#   s      rY   run_loopzSVSummaryThread.run_loop  s    xx'"&**..88 4 4
5#7lK ZZ^^DHH$7$78lkxxll2K@
hh)),D rb   r   r   r   r   rZ   r  __classcell__r  s   @rY   r   r      s    .		Erb   r   c                   0     e Zd ZdZd fd	Zd Zd Z xZS )r   z2Threads to count steps and measure their duration.c                    t         t        |   |j                  |j                         || _        || _        d| _        d| _        ||j                  n|}|| _
        d| j                  j                  j                  z  | _        y)zCreate a `SVStepCounterThread`.

    Args:
      sv: A `Supervisor`.
      sess: A `Session`.
      step_counter: A `Tensor` holding the step counter. By defaults, it uses
        sv.global_step.
            r   Nz%s/sec)r  r   rZ   r   rQ   r  r  
_last_time
_last_stepr#   _step_counterr   name_summary_tag)rM   r  r   step_counterr  s       rY   rZ   zSVStepCounterThread.__init__  st     

t-bhh8N8NODHDJDODO%1%92>>|L%D 4#5#5#8#8#=#==Drb   c                     t        j                          | _        t        j                  | j                  | j
                        | _        y r   )timer  r   r#   r  r  r  r   s    rY   
start_loopzSVStepCounterThread.start_loop/  s-    iikDO#//

D<N<NODOrb   c                 6   t        j                  | j                  | j                        }|| j                  z
  }|| _        t        j
                         }|| j                  z
  }|| _        |dkD  r||z  }nt        d      }t        t        j                  | j                  |      g      }| j                  j                  r&| j                  j                  j                  ||       t        j                  t        j                   dd| j                  |       y )Nr  inf)tagsimple_value)valuez%s: %g
   )r   r#   r  r  r  r  r  floatr   Valuer  r  rV   r   rg   log_first_nINFO)rM   r   added_stepscurrent_timeelapsed_timesteps_per_secr   s          rY   r  zSVStepCounterThread.run_loop3  s     ,,TZZ9K9KLL0K"DO99;L$//1L"DOb!L0mElm$++-H G xx
hh))'<@hD4E4E%'rb   r   )r   r   r   r   rZ   r  r  r  r  s   @rY   r   r     s    :>$P'rb   r   c                   (     e Zd ZdZ fdZd Z xZS )r   z"A thread to checkpoint on a timer.c                 r    t         t        |   |j                  |j                         || _        || _        y)zfCreate a `SVTimerCheckpointThread`.

    Args:
      sv: A `Supervisor`.
      sess: A `Session`.
    N)r  r   rZ   r   rR   r  r  r  s      rY   rZ   z SVTimerCheckpointThread.__init__M  s/     

!41"((B<N<NODHDJrb   c                 v   t        j                  d| j                  j                         | j                  j                  j                  | j                  | j                  j                  | j                  j                         | j                  j                  r| j                  j                  t        j                  | j                  | j                  j                        }| j                  j                  j                  t        t        j                  | j                  j                        |       y y y )NzSaving checkpoint to path %sr"   )r   checkpoint_path)rg   rh   r  r   r   saver  r#   rV   r   r   r   
CHECKPOINT)rM   r   s     rY   r  z SVTimerCheckpointThread.run_loopX  s    LL/1C1CDHHNN

DHH&&DHH4H4H  Jxx488#7#7#C"..tzz488;O;OPl
hh--
**DHH<N<NP
 $Drb   r  r  s   @rY   r   r   J  s    *		rb   r   PrepareSessionStartQueueRunnersStartStandardServicesStopRequestStopLoop
ShouldStopStopOnExceptionWaitForStopSummaryComputed)3r   r   rC   r  %tensorflow.core.framework.summary_pb2r   tensorflow.core.util.event_pb2r   tensorflow.python.eagerr   tensorflow.python.frameworkr   r   r   tensorflow.python.opsr	   r
   r   tensorflow.python.platformr   rg   tensorflow.python.summaryr   rG   tensorflow.python.trainingr   r   r   r   r\   r   tensorflow.python.utilr    tensorflow.python.util.tf_exportr   r   r   r   r   r   setattrr   r   r   r   r   r   r   r   r   r   r   rb   rY   <module>rD     s]   F  	  9 5 + . 2 + 2 , + < 9 2 9 M 4 . 6 !"#S S $SpEk.. E4-'+22 -'`k66 6 
$j&L&L M 
')G)G H 
+Z-O-O P 
FJOO , 
M:#:#: ; 
FJOO , 
L*"8"8 9 
%z'C'C D 
M:#;#; < 
%z'B'B Crb   