
    BVhC                     T   d 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 ddlmZ  ddlm!Z! ddl"m#Z# ddl$m%Z% ejL                  ejN                  fZ( e)       Z* e%dg       G d d             Z+	 	 	 	 	 	 	 	 	 	 	 	 	 d>d Z, e%d!g      d"ddddde*e*e*dddde*ddfd#       Z- e%d$g       G d% d&ej\                  '             Z/ e%d(g       G d) d*e/             Z0 e%d+g       G d, d-e/             Z1 G d. d/      Z2 e%d0g       G d1 d2e2             Z3 e%d3g       G d4 d5e2             Z4 G d6 d7      Z5 G d8 d9e5      Z6 G d: d;e5      Z7 G d< d=e5      Z8y)?z*A wrapper of Session API which runs hooks.    N)
config_pb2)
checkpoint)
graph_view)distribute_coordinator_context)errors)ops)	array_ops)control_flow_ops)
lookup_ops)	resources)	variables)
tf_logging)summary)basic_session_run_hooks)coordinator)queue_runner)saver)session_manager)session_run_hook)function_utils)	tf_exportztrain.Scaffold)v1c                       e Zd ZdZ	 	 	 	 	 	 	 	 	 	 ddZ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y)Scaffoldax	  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.compat.v1.train.Saver` object taking care of saving the
  variables.
    Picked from and stored into the `SAVERS` collection in the graph by default.
  * `init_op`: An op to run to initialize the variables.  Picked from and
    stored into the `INIT_OP` collection in the graph by default.
  * `ready_op`: An op to verify that the variables are initialized.  Picked
    from and stored into the `READY_OP` collection in the graph by default.
  * `ready_for_local_init_op`: An op to verify that global state has been
    initialized and it is alright to run `local_init_op`.  Picked from and
    stored into the `READY_FOR_LOCAL_INIT_OP` collection in the graph by
    default. This is needed when the initialization of local variables depends
    on the values of global variables.
  * `local_init_op`: An op to initialize the local variables.  Picked
    from and stored into the `LOCAL_INIT_OP` collection in the graph by default.
  * `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 by default.

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

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

  Nc                 F    |	t        |	t              st        d      d } |||	j                        } |||	j                        } ||	j
                         |||	j                        } |||	j                        } |||	j                        } ||
|	j                        }
 |||	j                        } |||	j                        } _        r fd _        nd _        | _        | _        | _        | _        | _        |
 _        | _        | _        y)aP  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 1D string tensor when the variables are initialized, or
        a non-empty 1D string tensor listing the names of the non-initialized
        variables.
      ready_for_local_init_op: Optional op to verify that the global variables
        are initialized and `local_init_op` can be run. Must return an empty 1D
        string tensor when the global variables are initialized, or a non-empty
        1D string tensor listing the names of the non-initialized global
        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.compat.v1.train.Saver` object to use to save and
        restore variables.  May also be a `tf.train.Checkpoint` object, in which
        case object-based checkpoints are saved. This will also load some
        object-based checkpoints saved from elsewhere, but that loading may be
        fragile since it uses fixed keys rather than performing a full
        graph-based match. For example if a variable has two paths from the
        `Checkpoint` object because two `Model` objects share the `Layer` object
        that owns it, removing one `Model` may change the keys and break
        checkpoint loading through this API, whereas a graph-based match would
        match the variable through the other `Model`.
      copy_from_scaffold: Optional scaffold object to copy fields from. Its
        fields will be overwritten by the provided fields in this function.
      local_init_feed_dict: Optional session feed dictionary to use when running
        the local_init_op.
    Nz.copy_from_scaffold is not a Scaffold instance.c                     | | S |S N )abs     \/home/dcms/DCMS/lib/python3.12/site-packages/tensorflow/python/training/monitored_session.py<lambda>z#Scaffold.__init__.<locals>.<lambda>   s    1=a a     c                      |       S r   r   )sessinit_fnselfs    r!   r"   z#Scaffold.__init__.<locals>.<lambda>   s    74#6 r#   )
isinstancer   	TypeErrorinit_opinit_feed_dict_user_init_fnready_opready_for_local_init_oplocal_init_oplocal_init_feed_dict
summary_opr   _init_fn_init_op_init_feed_dict	_ready_op_ready_for_local_init_op_local_init_op_local_init_feed_dict_summary_op_saver)r'   r*   r+   r&   r-   r.   r/   r1   r   copy_from_scaffoldr0   coalesces   `  `        r!   __init__zScaffold.__init__d   s<   \ %*H5HII 8h"4"<"<=g 2 A ACn "4"B"BCg($6$?$?@h (
!#5#M#M!O}.@.N.NOm%&:&8&M&MOJ(:(E(EFju0667e !D6dmdmDM)DDN$;D!'D!5D!DDKr#   c                    | j                   7d }t        j                  dt        j                  j
                  |      | _         | j                  7d }t        j                  dt        j                  j                  |      | _        | j                  7d }t        j                  dt        j                  j                  |      | _        | j                  Bt        j                  dt        j                  j                  t        j                        | _
        | j                  Bt        j                  dt        j                  j                  t        j                         | _        | j"                  t%        j&                         | _        t)        | j"                  t*        j,                        rHt%        j.                  t1        j2                  | j"                        j5                         d	
      | _        n| j"                  j7                          t        j8                         j;                          t=        j>                  d       | S )z5Creates operations if needed and finalizes the graph.c                      t        j                  t        j                         t	        j
                  t	        j                               t        j                  d            S )Nsaved_model_initializers)	r
   groupr   global_variables_initializerr   initialize_resourcesshared_resourcesr   get_collectionr   r#   r!   default_init_opz*Scaffold.finalize.<locals>.default_init_op   sG    %%224**9+E+E+GH9:< 	<r#   r*   c                  z    t        j                  t        j                         t	        j
                         gd      S Nr   )r	   concatr   report_uninitialized_variablesr   report_uninitialized_resourcesr   r#   r!   default_ready_opz+Scaffold.finalize.<locals>.default_ready_op   s7    446446!
  	r#   r-   c                      t        j                  t        j                  t        j                               t        j                  t        j                               gd      S rH   )r	   rI   r   rJ   global_variablesr   rK   rD   r   r#   r!   default_ready_for_local_init_opz:Scaffold.finalize.<locals>.default_ready_for_local_init_op   sS    44**,.44**,.!

  	r#   r.   r/   r1   T)var_listshardedzGraph was finalized.) r3   r   get_or_defaultr   	GraphKeysINIT_OPr5   READY_OPr6   READY_FOR_LOCAL_INIT_OPr7   LOCAL_INIT_OPdefault_local_init_opr9   
SUMMARY_OPr   	merge_allr:   training_saver_get_saver_or_defaultr(   trackable_util
CheckpointSaverr   ObjectGraphViewfrozen_saveable_objectsbuildget_default_graphfinalizelogginginfo)r'   rF   rL   rO   s       r!   rd   zScaffold.finalize   s   }}< --i9N9N.=?dm~~  ..z/2}}/E/E/?Adn $$, '/&=&=
#S]]%J%J
)'+d# "$33
3==66

(
(*d !00141I1I181B1BDd {{"88:dk$++~889"((--kk224dk
 kk$$&LL'(Kr#   c                     | j                   S r   )r2   r'   s    r!   r&   zScaffold.init_fn       ==r#   c                     | j                   S r   )r3   rh   s    r!   r*   zScaffold.init_op   ri   r#   c                     | j                   S r   )r5   rh   s    r!   r-   zScaffold.ready_op   s    >>r#   c                     | j                   S r   )r6   rh   s    r!   r.   z Scaffold.ready_for_local_init_op   s    (((r#   c                     | j                   S r   )r7   rh   s    r!   r/   zScaffold.local_init_op  s    r#   c                     | j                   S r   )r8   rh   s    r!   r0   zScaffold.local_init_feed_dict  s    %%%r#   c                     | j                   S r   )r9   rh   s    r!   r1   zScaffold.summary_op  s    r#   c                     | j                   S r   )r:   rh   s    r!   r   zScaffold.saver  s    ;;r#   c                     | j                   S r   )r4   rh   s    r!   r+   zScaffold.init_feed_dict  s    r#   c                     t        j                  |      }|r t        |      dkD  rt        d||       |d   S  |       }|t        j                  ||       |S )z-Get from cache or create a default operation.   zMore than one item in the collection "%s". Please indicate which one to use by passing it to the tf.Scaffold constructor as:  tf.Scaffold(%s=item to use)r   )r   rE   lenRuntimeErroradd_to_collection)arg_namecollection_keydefault_constructorelementsops        r!   rR   zScaffold.get_or_default  sl     !!.1H	X	* ,:8	E 	E
 a[		B	~	NB/Ir#   c                      t        j                  t        j                         t	        j
                         t        j                  t        j                                     S )a  Returns an op that groups the default local init ops.

    This op is used during session initialization when a Scaffold is
    initialized without specifying the local_init_op arg. It includes
    `tf.compat.v1.local_variables_initializer`,
    `tf.compat.v1.tables_initializer`, and also
    initializes local session resources.

    Returns:
      The default Scaffold local init op.
    )	r
   rA   r   local_variables_initializerr   tables_initializerr   rC   local_resourcesr   r#   r!   rX   zScaffold.default_local_init_op(  sH     !!--/%%'&&y'@'@'BCE Er#   )
NNNNNNNNNN)__name__
__module____qualname____doc__r=   rd   propertyr&   r*   r-   r.   r/   r0   r1   r   r+   staticmethodrR   rX   r   r#   r!   r   r   3   s   -` "'+!"&$(Qf:x       ) )   & &            E Er#   r   x   d      Tc                 *   g }|r|j                  |       |r| j                  r|j                  |       t        | j                        j                  dv r]| j
                  rd| j
                  | j                  fz  }nd}|rt        j                  d       d }d}|rt        j                  d       nd }|xs |}|r|
r~|
dkD  ry| j                  r'|j                  t        j                  ||
             nF|rD|j                  t        j                  t        j                  j                  ||      |
             |r|dkD  s	|r|dkD  r|r| j                  r)|j                  t        j                   ||||	             nH|rF|j                  t        j                   |||t        j                  j                  ||      	             |r|dkD  s|r|dkD  r|r| j"                  r*|j                  t        j$                  |||||
             nI|rG|j                  t        j$                  t        j                  j                  ||      ||||
             t        j&                  d|       | j)                  ||||      }t+        |||	      S )N)CollectiveAllReduceStrategyCollectiveAllReduceStrategyV1MultiWorkerMirroredStrategyz	tmp_%s_%dtmpzCollective ops may deadlock with `save_checkpoints_secs` please use `save_checkpoint_steps` instead. Clearing `save_checkpoint_secs` and setting `save_checkpoint_steps` to 1000 now.i  zhCollective ops may run out of sync with`save_summaries_secs`, please use `save_summaries_steps` instead.r   
output_direvery_n_stepsscaffold
save_steps	save_secsr   r   r   r   save_graph_defzall_hooks %r)configcheckpoint_dirmax_wait_secssession_creatorhooksstop_grace_period_secs)extendis_chieftype	_strategyr   	task_typetask_idre   warningshould_save_summaryappendr   StepCounterHookospathjoinSummarySaverHookshould_checkpointCheckpointSaverHookrf   r   MonitoredSession)worker_contextr   r   r   chief_only_hookssave_checkpoint_secssave_summaries_stepssave_summaries_secsr   r   log_step_count_stepsr   save_checkpoint_stepssummary_dirr   	all_hookstmpdirr   s                     r!   -_create_monitored_session_with_worker_contextr   ;  s     )
U.11%& 
  ( -LL n668N8NOOffoo = >
 ""oo 8 9 F-~+).BQ.F))
!
1
1$4HJK 

!
1
1k6:023
 	!5!9 3a 7k))
!
2
2-+$	&' 

!
2
2-+k6:	<= #7!#;
$9A$=		)	)#770.!-/	0 #77^V40.!-/	0 
,,~y)"22#!	 3 #/
 
%3
5 5r#   ztrain.MonitoredTrainingSession c                 N   |t         k(  r|t         k(  rd}d}n|t         k(  rd}n|t         k(  rd}|t         k(  r|t         k(  rd}d}n|t         k(  rd}n|t         k(  rd}|xs
 t               }t        j                         }|rt	        |||||||||	|
|||||      S |s!t        || |	|      }t        ||xs g |
      S g }|r|j                  |       t        ||| |	      }|xs |}|rc|r+|dkD  r&|j                  t        j                  ||	             |r|dkD  s|r-|dkD  r(|j                  t        j                  ||||
             |r7|r|dkD  s|r.|dkD  r)|j                  t        j                  |||||             |r|j                  |       t        |||
      S )a  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
  initialize/restore. Please check `tf.compat.v1.train.MonitoredSession` for
  more
  information.

  @compatibility(TF2)
  This API is not compatible with eager execution and `tf.function`. To migrate
  to TF2, rewrite the code to be compatible with eager execution. Check the
  [migration
  guide](https://www.tensorflow.org/guide/migrate#1_replace_v1sessionrun_calls)
  on replacing `Session.run` calls. In Keras, session hooks can be replaced by
  Callbacks e.g. [logging hook notebook](
  https://github.com/tensorflow/docs/blob/master/site/en/guide/migrate/logging_stop_hook.ipynb)
  For more details please read [Better
  performance with tf.function](https://www.tensorflow.org/guide/function).
  @end_compatibility

  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 both `save_checkpoint_steps` and
      `save_checkpoint_secs` are set to `None`, then the default checkpoint
      saver isn't used. If both are provided, then only `save_checkpoint_secs`
      is used. Default 600.
    save_summaries_steps: The frequency, in number of global steps, that the
      summaries are written to disk using a default summary saver. If both
      `save_summaries_steps` and `save_summaries_secs` are set to `None`, then
      the default summary saver isn't used. Default 100.
    save_summaries_secs: The frequency, in secs, that the summaries are written
      to disk using a default summary saver.  If both `save_summaries_steps` and
      `save_summaries_secs` are set to `None`, then the default summary saver
      isn't used. Default not enabled.
    config: an instance of `tf.compat.v1.ConfigProto` proto used to configure
      the session. It's the `config` argument of constructor of
      `tf.compat.v1.Session`.
    stop_grace_period_secs: Number of seconds given to threads to stop after
      `close()` has been called.
    log_step_count_steps: The frequency, in number of global steps, that the
      global step/sec is logged.
    max_wait_secs: Maximum time workers should wait for the session to become
      available. This should be kept relatively short to help detect incorrect
      code, but sometimes may need to be increased if the chief takes a while to
      start up.
    save_checkpoint_steps: The frequency, in number of global steps, that a
      checkpoint is saved using a default checkpoint saver. If both
      `save_checkpoint_steps` and `save_checkpoint_secs` are set to `None`, then
      the default checkpoint saver isn't used. If both are provided, then only
      `save_checkpoint_secs` is used. Default not enabled.
    summary_dir: A string.  Optional path to a directory where to save
      summaries. If None, checkpoint_dir is used instead.
    save_graph_def: Whether to save the GraphDef and MetaGraphDef to
      `checkpoint_dir`. The GraphDef is saved after the session is created as
      `graph.pbtxt`. MetaGraphDefs are saved out for every checkpoint as
      `model.ckpt-*.meta`.

  Returns:
    A `MonitoredSession` object.
  r   NiX  )r   r   r   r   r   r   r   r   r   r   r   r   r   )r   masterr   r   r   )r   r   r   r   r   r   r   r   )USE_DEFAULTr   r   get_current_worker_contextr   WorkerSessionCreatorr   r   ChiefSessionCreatorr   r   r   r   r   )r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   s                      r!   MonitoredTrainingSessionr     s   t [(-@K-Ok){*{*k) {*+ #(1LLN.8%)11/51#3%' '" 
*#	%O
 'kr57 7
 )%&'#	/ -~+ 4q 8
!
1
1$4HJK 	q &9&9A&=
!
2
2-+$	&' q &;&;a&?
!
5
5.,+-. U	%3
5 5r#   ztrain.SessionCreatorc                   4    e Zd ZdZej
                  d        Zy)SessionCreatorzA factory for tf.Session.c                 6    t        dj                  |             )Nz)create_session is not implemented for {}.)NotImplementedErrorformatrh   s    r!   create_sessionzSessionCreator.create_sessionh  s    
3::4@B Br#   N)r   r   r   r   abcabstractmethodr   r   r#   r!   r   r   d  s    !B Br#   r   )	metaclassztrain.ChiefSessionCreatorc                   .    e Zd ZdZ	 	 	 	 	 ddZd Zd Zy)r   z+Creates a tf.compat.v1.Session for a chief.Nc                 p    || _         || _        |xs
 t               | _        d| _        || _        || _        y)a  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.
      checkpoint_filename_with_path: Full file name path to the checkpoint file.
    N)_checkpoint_dir_checkpoint_filename_with_pathr   	_scaffold_session_manager_master_config)r'   r   r   r   r   checkpoint_filename_with_paths         r!   r=   zChiefSessionCreator.__init__r  s8    " *D*GD'+DN DDLDLr#   c                 L   | j                   r| j                   S t        j                  | j                  j                  | j                  j
                  | j                  j                  | j                  j                  t        j                               | _         | j                   S z!Gets or creates a SessionManager.)r/   r0   r-   r.   graph
r   smSessionManagerr   r/   r0   r-   r.   r   rc   rh   s    r!   _get_session_managerz(ChiefSessionCreator._get_session_manager  x    """--nn22!^^@@(( $ F F##%'D    r#   c           
      t   | j                   j                          | j                         j                  | j                  | j                   j
                  | j                  | j                  | j                  | j                   j                  | j                   j                  | j                   j                        S )N)r   r   r   r   r*   r+   r&   )r   rd   r   prepare_sessionr   r   r   r   r   r*   r+   r&   rh   s    r!   r   z"ChiefSessionCreator.create_session  s    NN$$&66nn""++&*&I&I||&&~~44&& 7 ( (r#   )Nr   NNNr   r   r   r   r=   r   r   r   r#   r!   r   r   n  s%    3 "-10!
(r#   r   ztrain.WorkerSessionCreatorc                   ,    e Zd ZdZ	 	 	 	 ddZd Zd Zy)r   z,Creates a tf.compat.v1.Session for a worker.Nc                 b    |xs
 t               | _        d| _        || _        || _        || _        y)a  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.
      max_wait_secs: Maximum time to wait for the session to become available.
    N)r   r   r   r   r   _max_wait_secs)r'   r   r   r   r   s        r!   r=   zWorkerSessionCreator.__init__  s0     +DN DDLDL'Dr#   c                 L   | j                   r| j                   S t        j                  | j                  j                  | j                  j
                  | j                  j                  | j                  j                  t        j                               | _         | j                   S r   r   rh   s    r!   r   z)WorkerSessionCreator._get_session_manager  r   r#   c                     | j                   j                          | j                         j                  | j                  | j
                  | j                        S )N)r   r   )r   rd   r   wait_for_sessionr   r   r   rh   s    r!   r   z#WorkerSessionCreator.create_session  sJ    NN$$&77T\\9L9L 8 N Nr#   )Nr   Ni  r   r   r#   r!   r   r     s#    4 $	((!Nr#   r   c                       e Zd ZdZ	 ddZed        ZddZd Z G d d      Z	d	 Z
d
 Zd Zd Z G d de      ZddZd Zd Zy)_MonitoredSessionz5See `MonitoredSession` or `SingularMonitoredSession`.c                    t        j                         j                  | _        |xs g | _        | j                  D ]  }|j                           t        j                         }|s|r|j                         }| j                  |xs
 t               | j                  |      | _        |rt        | j                        | _        y| j                  j                         | _        y)a  Sets up a Monitored or Hooked Session.

    Args:
      session_creator: A factory object to create session. Typically a
        `ChiefSessionCreator` or a `WorkerSessionCreator`.
      hooks: An iterable of `SessionRunHook' objects.
      should_recover: A bool. Indicates whether to recover from `AbortedError`
        and `UnavailableError` or not.
      stop_grace_period_secs: Number of seconds given to threads to stop after
        `close()` has been called.
    r   N)r   rc   	finalized_graph_was_finalized_hooksbeginr   r   r   _CoordinatedSessionCreatorr   _coordinated_creator_RecoverableSession_sessr   )r'   r   r   should_recoverr   hr   s          r!   r=   z_MonitoredSession.__init__  s      !$ 5 5 7 A AD+2DK[[ ggi 4NNPN~&668o !% ? ?'@+>+@kk5 !@ !7D &t'@'@Adj,,;;=djr#   c                 X    | j                         y| j                         j                  S )z,The graph that was launched in this session.N)_tf_sessr   rh   s    r!   r   z_MonitoredSession.graph  s%     }}==?   r#   Nc                 @    | j                   j                  ||||      S )ab  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()`.
    	feed_dictoptionsrun_metadatar   run)r'   fetchesr   r   r   s        r!   r   z_MonitoredSession.run  s*     ::>>!	  # #r#   c                     t        j                  |      }|dk7  r|dk7  rt        dj                  |            | j                  j                  || j                         d      S )a  Run ops using a step function.

    Args:
      step_fn: A function or a method with a single argument of type
        `StepContext`.  The function may use methods of the argument to perform
        computations with access to a raw session.  The returned value of the
        `step_fn` will be returned from `run_step_fn`, unless a stop is
        requested.  In that case, the next `should_stop` call will return True.
        Example usage:
            ```python
            with tf.Graph().as_default():
              c = tf.compat.v1.placeholder(dtypes.float32)
              v = tf.add(c, 4.0)
              w = tf.add(c, 0.5)
              def step_fn(step_context):
                a = step_context.session.run(fetches=v, feed_dict={c: 0.5})
                if a <= 4.5:
                  step_context.request_stop()
                  return step_context.run_with_hooks(fetches=w,
                                                     feed_dict={c: 0.1})

              with tf.MonitoredSession() as session:
                while not session.should_stop():
                  a = session.run_step_fn(step_fn)
            ```
            Hooks interact with the `run_with_hooks()` call inside the
                 `step_fn` as they do with a `MonitoredSession.run` call.

    Returns:
      Returns the returned value of `step_fn`.

    Raises:
      StopIteration: if `step_fn` has called `request_stop()`.  It may be
        caught by `with tf.MonitoredSession()` to close the session.
      ValueError: if `step_fn` doesn't have a single argument called
        `step_context`. It may also optionally have `self` for cases when it
        belongs to an object.
    )step_context)r'   r   z`step_fn` may either have one `step_context` argument, or `self` and `step_context` arguments if it's an instance method. Got {} instead.N)run_with_hooks)r   fn_args
ValueErrorr   r   run_step_fnr   )r'   step_fnstep_fn_argumentss      r!   r  z_MonitoredSession.run_step_fn  sr    N '..w7--2C H 3 %%+V,=%>@ @ ::!!'4==?4!PPr#   c                   2    e Zd ZdZd Zed        Zd Zd Zy)_MonitoredSession.StepContextaC  Control flow instrument for the `step_fn` from `run_step_fn()`.

       Users of `step_fn` may perform `run()` calls without running hooks
       by accessing the `session`.  A `run()` call with hooks may be performed
       using `run_with_hooks()`.  Computation flow can be interrupted using
       `request_stop()`.
    c                      || _         || _        y)zInitializes the `step_context` argument for a `step_fn` invocation.

      Args:
        session: An instance of `tf.compat.v1.Session`.
        run_with_hooks_fn: A function for running fetches and hooks.
      N)_session_run_with_hooks_fn)r'   sessionrun_with_hooks_fns      r!   r=   z&_MonitoredSession.StepContext.__init__Q  s     dm 1dr#   c                     | j                   S r   )r  rh   s    r!   r	  z%_MonitoredSession.StepContext.session[  s    ]]r#   c                 &     | j                   |i |S )z;Same as `MonitoredSession.run`. Accepts the same arguments.)r  r'   argskwargss      r!   r   z,_MonitoredSession.StepContext.run_with_hooks_  s    $T$$d5f55r#   c                     t        d      )zExit the training loop by causing `should_stop()` to return `True`.

         Causes `step_fn` to exit by raising an exception.

      Raises:
        StopIteration
      z-step_fn has requested the iterations to stop.)StopIterationrh   s    r!   request_stopz*_MonitoredSession.StepContext.request_stopc  s     IJJr#   N)	r   r   r   r   r=   r   r	  r   r  r   r#   r!   StepContextr  H  s+    2  6Kr#   r  c                 V    | j                   d u xs | j                   j                         S r   )r   should_stoprh   s    r!   r  z_MonitoredSession.should_stopm  s#    ::9!7!7!99r#   c                 $    | j                          y r   )_close_internalrh   s    r!   closez_MonitoredSession.closep  s    r#   c                     | S r   r   rh   s    r!   	__enter__z_MonitoredSession.__enter__s  s    Kr#   c                 `    |t         j                  t        fv rd }| j                  |       |d u S r   )r   OutOfRangeErrorr  r  )r'   exception_typeexception_value	tracebacks       r!   __exit__z_MonitoredSession.__exit__v  s3    &00-@@n(T!!r#   c                       e Zd ZdZd Zd Zy),_MonitoredSession._CoordinatedSessionCreatorz Factory for _CoordinatedSession.c                 J    || _         || _        d | _        d | _        || _        y r   )_session_creatorr   coordtf_sess_stop_grace_period_secs)r'   r   r   r   s       r!   r=   z5_MonitoredSession._CoordinatedSessionCreator.__init__  s'    -ddkdjdl%;d"r#   c                    | j                   j                         | _        t        j                  g       | _        t        j                  t        j                  j                        r+t        j                  | j                  | j
                         | j                  D ](  }|j                  | j                  | j
                         * t        t        | j                  | j                        | j
                  | j                         S )zCreates a coordinated session.)clean_stop_exception_types)r%   r%  )r$  r   r&  r   Coordinatorr%  r   rE   rS   QUEUE_RUNNERSr   start_queue_runnersr   after_create_session_CoordinatedSession_HookedSessionr'  )r'   hooks     r!   r   z;_MonitoredSession._CoordinatedSessionCreator.create_session  s     **99;dl**bIdj			CMM77	8((dll$**M++ <$!!$,,

;< 
t{{
3TZZ

&
&( (r#   N)r   r   r   r   r=   r   r   r#   r!   r   r"  }  s    *<(r#   r   c                    	 |s6| j                   D ]'  }|j                  | j                  j                         ) 	 | j                  t        d      | j                  j                          d | _        d | j                  _        d | j                  _        | j                  s#t        j                         j                          y y # d | _        d | j                  _        d | j                  _        | j                  s#t        j                         j                          w w xY w# 	 | j                  t        d      | j                  j                          d | _        d | j                  _        d | j                  _        | j                  s#t        j                         j                          w w # d | _        d | j                  _        d | j                  _        | j                  s#t        j                         j                          w w xY wxY w)NzSession is already closed.)r   endr   r&  r   ru   r  r%  r   r   rc   _unsafe_unfinalize)r'   r  r   s      r!   r  z!_MonitoredSession._close_internal  s   7 	3A
%%))11
2	3	7::9:
:


,0!!)*.!!'((



!
4
4
6 ) 
,0!!)*.!!'((



!
4
4
6 )	7::9:
:


,0!!)*.!!'((



!
4
4
6 ) 
,0!!)*.!!'((



!
4
4
6 )s1   8D" 1C AD"H$1F.AH.AHHc                 2    | j                   j                  du S )zhReturn True if the monitored session is closed.

    For tests only.

    Returns:
      A boolean.
    Nr   r&  rh   s    r!   
_is_closedz_MonitoredSession._is_closed  s     $$,,44r#   c                 .    | j                   j                  S )zReturn underlying tf.compat.v1.Session object.

    Warning: accessing the returned object in user code is likely to cause races
    or "flaky tests".

    Returns:
      A tf.compat.v1.Session object.
    r5  rh   s    r!   r   z_MonitoredSession._tf_sess  s     $$,,,r#   r   NNNr   )r   r   r   r   r=   r   r   r   r  r  r  r  r  r   r   r   r  r6  r   r   r#   r!   r   r     sl    = '*	!>F ! !#(6Qp#K #KJ:"(> (27"5	-r#   r   ztrain.MonitoredSessionc                   *     e Zd ZdZ	 	 	 d fd	Z xZS )r   a  Session-like object that handles initialization, recovery and hooks.

  Example usage:

  ```python
  saver_hook = CheckpointSaverHook(...)
  summary_hook = SummarySaverHook(...)
  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()` for each given hook
  * 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
  * calls `hook.after_create_session()`

  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` or `UnavailableError` 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
  * suppresses `OutOfRange` error which indicates that all inputs have been
    processed if the monitored_session is used as a context

  How to set `tf.compat.v1.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.

  Note: This is not a `tf.compat.v1.Session`. For example, it cannot do
  following:

  * it cannot be set as default session.
  * it cannot be sent to saver.save.
  * it cannot be sent to tf.train.start_queue_runners.

  @compatibility(TF2)
  This API is not compatible with eager execution and `tf.function`. To migrate
  to TF2, rewrite the code to be compatible with eager execution. Check the
  [migration
  guide](https://www.tensorflow.org/guide/migrate#1_replace_v1sessionrun_calls)
  on replacing `Session.run` calls. In Keras, session hooks can be replaced by
  Callbacks e.g. [logging hook notebook](
  https://github.com/tensorflow/docs/blob/master/site/en/guide/migrate/logging_stop_hook.ipynb)
  For more details please read [Better
  performance with tf.function](https://www.tensorflow.org/guide/function).
  @end_compatibility

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

  Returns:
    A MonitoredSession object.
  c                 4    t         t        |   ||d|       y )NTr   r   )superr   r=   )r'   r   r   r   	__class__s       r!   r=   zMonitoredSession.__init__  s&     

D*5	 + 7r#   )NNr   )r   r   r   r   r=   __classcell__r>  s   @r!   r   r     s    Up  $&)7 7r#   r   ztrain.SingularMonitoredSessionc                   8     e Zd ZdZ	 	 	 	 	 	 	 d fd	Zd Z xZS )SingularMonitoredSessionaO
  Session-like object that handles initialization, restoring, and hooks.

  Please note that this utility is not recommended for distributed settings.
  For distributed settings, please use `tf.compat.v1.train.MonitoredSession`.
  The
  differences between `MonitoredSession` and `SingularMonitoredSession` are:

  * `MonitoredSession` handles `AbortedError` and `UnavailableError` for
    distributed settings, but `SingularMonitoredSession` does not.
  * `MonitoredSession` can be created in `chief` or `worker` modes.
    `SingularMonitoredSession` is always created as `chief`.
  * You can access the raw `tf.compat.v1.Session` object used by
    `SingularMonitoredSession`, whereas in MonitoredSession the raw session is
    private. This can be used:
      - To `run` without hooks.
      - To save and restore.
  * All other functionality is identical.

  Example usage:
  ```python
  saver_hook = CheckpointSaverHook(...)
  summary_hook = SummarySaverHook(...)
  with SingularMonitoredSession(hooks=[saver_hook, summary_hook]) as sess:
    while not sess.should_stop():
      sess.run(train_op)
  ```

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

  * calls `hook.begin()` for each given hook
  * 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 hooked 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

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

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

  @compatibility(TF2)
  This API is not compatible with eager execution and `tf.function`. To migrate
  to TF2, rewrite the code to be compatible with eager execution. Check the
  [migration
  guide](https://www.tensorflow.org/guide/migrate#1_replace_v1sessionrun_calls)
  on replacing `Session.run` calls. In Keras, session hooks can be replaced by
  Callbacks e.g. [logging hook notebook](
  https://github.com/tensorflow/docs/blob/master/site/en/guide/migrate/logging_stop_hook.ipynb)
  For more details please read [Better
  performance with tf.function](https://www.tensorflow.org/guide/function).
  @end_compatibility
  c                 T    t        |||||      }t        t        |   ||d|       y)a  Creates a SingularMonitoredSession.

    Args:
      hooks: An iterable of `SessionRunHook' objects.
      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.
      stop_grace_period_secs: Number of seconds given to threads to stop after
        `close()` has been called.
      checkpoint_filename_with_path: A string. Optional path to a checkpoint
        file from which to restore variables.
    )r   r   r   r   r   Fr<  N)r   r=  rB  r=   )
r'   r   r   r   r   r   r   r   r   r>  s
            r!   r=   z!SingularMonitoredSession.__init__c  sB    . *%&CEO 

"D25	 3 7r#   c                 "    | j                         S )z/Returns underlying `TensorFlow.Session` object.)r   rh   s    r!   raw_sessionz$SingularMonitoredSession.raw_session  s    ==?r#   )NNr   NNr   N)r   r   r   r   r=   rE  r?  r@  s   @r!   rB  rB  !  s+    >B "&)-1!7Fr#   rB  c                   T    e Zd ZdZd Zed        Zed        Zd Zd Z	d Z
d Zd	 Zy
)_WrappedSessionap  Wrapper around a `tf.compat.v1.Session`.

  This wrapper is used as a base class for various session wrappers
  that provide additional functionality such as monitoring, coordination,
  and recovery.

  In addition to the methods exported by `SessionInterface` the wrapper
  provides a method to check for stop and never raises exceptions from
  calls to `close()`.
  c                 P    || _         t        | j                   t              | _        y)zCreates a `_WrappedSession`.

    Args:
      sess: A `tf.compat.v1.Session` or `_WrappedSession` object.  The wrapped
        session.
    N)r   r(   rG  _wrapped_is_stoppable)r'   r%   s     r!   r=   z_WrappedSession.__init__  s     DJ!+DJJ!HDr#   c                 .    | j                   j                  S r   )r   r   rh   s    r!   r   z_WrappedSession.graph  s    ::r#   c                 .    | j                   j                  S r   )r   sess_strrh   s    r!   rL  z_WrappedSession.sess_str  s    ::r#   c                     | j                         ry| j                  r(| j                  xr | j                  j                         S y)zReturn true if this session should not be used anymore.

    Always return True if the session was closed.

    Returns:
      True if the session should stop, False otherwise.
    T)_check_stopr   rI  r  rh   s    r!   r  z_WrappedSession.should_stop  s;     zz''DDJJ,B,B,DDr#   c                      y)zHook for subclasses to provide their own stop condition.

    Returns:
      True if the session should stop, False otherwise.
    Fr   rh   s    r!   rN  z_WrappedSession._check_stop  s     r#   c                     | j                   r#	 | j                   j                          d | _         y y # t        $ r }t        j                  d|       Y d }~-d }~ww xY w# d | _         w xY w)NzAn error occurred when attempting to close the session. This may be due to a preemption in a connected worker or parameter server. Error: %s)r   r  _PREEMPTION_ERRORSre   errorr'   es     r!   r  z_WrappedSession.close  se    zz

 
    B>?@	B 	BB 
s&   1 	AAA AA 	A&c                 :     | j                   j                  |i |S r   r   r  s      r!   r   z_WrappedSession.run  s    4::>>4*6**r#   c                 Z    |xs | j                   } |t        j                  ||            S r   )r   r   r  )r'   r  rE  r   s       r!   r  z_WrappedSession.run_step_fn  s+     $/txxN$00nMNNr#   N)r   r   r   r   r=   r   r   rL  r  rN  r  r   r  r   r#   r!   rG  rG    sO    	I    
+Or#   rG  c                   0    e Zd ZdZd Zd Zd ZddZd Zy)	r   a  A wrapped session that recreates a session upon certain kinds of errors.

  The constructor is passed a SessionCreator object, not a session.

  Calls to `run()` are delegated to the wrapped session.  If a call raises the
  exception `tf.errors.AbortedError` or `tf.errors.UnavailableError`, the
  wrapped session is closed, and a new one is created by calling the factory
  again.
  c                 Z    || _         t        j                  | | j                                y)zCreate a new `_RecoverableSession`.

    The value returned by calling `sess_creator.create_session()` will be the
    session wrapped by this recoverable session.

    Args:
      sess_creator: A 'SessionCreator' to be wrapped by recoverable.
    N)_sess_creatorrG  r=   _create_session)r'   sess_creators     r!   r=   z_RecoverableSession.__init__  s%     &DT4#7#7#9:r#   c                     	 	 | j                   j                         S # t        $ r }t        j                  d|       Y d }~nd }~ww xY wH)Na  An error was raised while a session was being created. This may be due to a preemption of a connected worker or parameter server. A new session will be created. This error may also occur due to a gRPC failure caused by high memory or network bandwidth usage in the parameter servers. If this error occurs repeatedly, try increasing the number of parameter servers assigned to the job. Error: %s)rY  r   rQ  re   rf   rS  s     r!   rZ  z#_RecoverableSession._create_session  sO    
%!!0022 	%! #$	% 	%	% s    	AAAc                    	 | j                   r| j                   j                         S y# t        $ rE}t        j                  d|       | j                          | j                         | _         Y d }~yd }~wt        $ r Y yw xY w)NTa  An error was raised while considering whether the session is complete. This may be due to a preemption in a connected worker or parameter server. The current session will be closed and a new session will be created. This error may also occur due to a gRPC failure caused by high memory or network bandwidth usage in the parameter servers. If this error occurs repeatedly, try increasing the number of parameter servers assigned to the job. Error: %sF)r   rN  rQ  re   rf   r  rZ  	ExceptionrS  s     r!   rN  z_RecoverableSession._check_stop  su    	zz%%'' ll !"	# jjl'')dj  s   %) 	B;A22B BNc                    	 	 | j                   s| j                         | _         | j                   j                  ||||      S # t        $ r7}t	        j
                  d|       | j                          d | _         Y d }~nd }~ww xY w)Nr     An error was raised. This may be due to a preemption in a connected worker or parameter server. The current session will be closed and a new session will be created. This error may also occur due to a gRPC failure caused by high memory or network bandwidth usage in the parameter servers. If this error occurs repeatedly, try increasing the number of parameter servers assigned to the job. Error: %s)r   rZ  r   rQ  re   rf   r  )r'   r   r   r   r   rT  s         r!   r   z_RecoverableSession.run  s    
zz++-$*zz~~%	  ' 	'
   ! #$	% 	



 s   ?A 	B-A>>Bc                 6   	 	 | j                   s| j                         | _         | j                   j                  }| j                   j                  |||      S # t        $ r7}t        j                  d|       | j                          d | _         Y d }~nd }~ww xY w)Nr`  )r   rZ  r   r  rQ  re   rf   r  )r'   r  rE  r   rT  s        r!   r  z_RecoverableSession.run_step_fn-  s    
zz++-$*zz%%g{NKK ! #$	% 	



 s   AA 	B -BBr9  )	r   r   r   r   r=   rZ  rN  r   r  r   r#   r!   r   r     s     
;%4.r#   r   c                   *    e Zd ZdZddZd Zd Zd Zy)r.  a  A wrapped session that works with a `tf.Coordinator`.

  Calls to `run()` are delegated to the wrapped session.  If a call
  raises an exception, the exception is reported to the coordinator.

  In addition, after each call to `run()` this session ask the coordinator if
  the session should stop.  In that case it will join all the threads
  registered with the coordinator before returning.

  If the coordinator was requested to stop with an exception, that exception
  will be re-raised from the call to `run()`.
  c                 L    t         j                  | |       || _        || _        y)a  Create a new `_CoordinatedSession`.

    Args:
      sess: A `tf.compat.v1.Session` object.  The wrapped session.
      coord: A `tf.train.Coordinator` object.
      stop_grace_period_secs: Number of seconds given to threads to stop after
        `close()` has been called.
    N)rG  r=   _coordr'  )r'   r%   r%  r   s       r!   r=   z_CoordinatedSession.__init__Q  s#     T4(DK#9D r#   c                 j    | j                   j                          | j                   j                         S r   )rd  raise_requested_exceptionr  rh   s    r!   rN  z_CoordinatedSession._check_stop^  s'     	KK))+;;""$$r#   c                 &   | j                   j                          	 | j                   j                  | j                  d       	 t        j                  |        y # t        $ r Y y w xY w# 	 t        j                  |        w # t        $ r Y w w xY wxY w)NT)r   ignore_live_threads)rd  r  r   r'  rG  r  r^  rh   s    r!   r  z_CoordinatedSession.closee  s    KK

kk!%!=!="  $d#  	d#  	sA   'A) A 	A&%A&)B+B B	B
BBBc                     	  | j                   j                  |i |S # t        $ r  t        $ r:}	 | j                  j                           # t        $ r  t        $ r |d w xY wd }~ww xY wr   )r   r   rQ  r^  rd  rf  )r'   r  r  original_exceptions       r!   r   z_CoordinatedSession.runs  sy    TZZ^^T,V,,  --/ 	    + d*+s&    A*AA%A""A%%A*Nr8  )r   r   r   r   r=   rN  r  r   r   r#   r!   r.  r.  C  s    :%r#   r.  c                   6    e Zd ZdZd Zd Zd	dZd Zd Zd Z	y)
r/  a  A _WrappedSession that calls hooks during calls to run().

  The list of hooks to call is passed in the constructor.  Before each call
  to `run()` the session calls the `before_run()` method of the hooks, which
  can return additional ops or tensors to run.  These are added to the arguments
  of the call to `run()`.

  When the `run()` call finishes, the session calls the `after_run()` methods of
  the hooks, passing the values returned by the `run()` call corresponding to
  the ops and tensors that each hook requested.

  If any call to the hooks, requests stop via run_context the session will be
  marked as needing to stop and its `should_stop()` method will now return
  `True`.
  c                 L    t         j                  | |       || _        d| _        y)zInitializes a _HookedSession object.

    Args:
      sess: A `tf.compat.v1.Session` or a `_WrappedSession` object.
      hooks: An iterable of `SessionRunHook' objects.
    FN)rG  r=   r   _should_stop)r'   r%   r   s      r!   r=   z_HookedSession.__init__  s#     T4(DKDr#   c                     | j                   S )See base class.)rm  rh   s    r!   rN  z_HookedSession._check_stop  s    r#   Nc           	      2   | j                         rt        d      d|i}t        j                  t        j                  ||      | j
                        }|xs t        j                         }| j                  ||||      }|xs t        j                         }t        j                  | ||||      }| j                  D ]3  }|j                  |t        j                  ||v r||   nd||             5 | j                  xs |j                   | _        |d   S )ro  z,Run called even after should_stop requested.caller)original_argsr	  )r   r   r   r   N)resultsr   r   )r  ru   r   SessionRunContextSessionRunArgsr   r   
RunOptions_call_hook_before_runRunMetadatarG  r   r   	after_runSessionRunValuesrm  stop_requested)	r'   r   r   r   r   actual_fetchesrun_contextoutputsr0  s	            r!   r   z_HookedSession.run  s   GHH(N"44&55gyI

K 0..0G**;+4g?I  ;:#9#9#;L!!! " #G  *
nn


+
+'+wgdmD')** ))G[-G-GD8r#   c                    i }| j                   D ]  }|j                  |      }||j                  |j                  ||<   |j                  r8| j	                  ||j                  d       |j                  |j                         |j                  s| j                  ||j                          |s|S |s|S | j	                  ||d       |j                  |       |S )z7Calls hooks.before_run and handles requests from hooks.z Same tensor is fed by two hooks.z0Same tensor is fed by a SessionRunHook and user.)r   
before_runr   r   _raise_if_feeds_intersectsupdater   _merge_run_options)r'   r}  
fetch_dictuser_feed_dictr   
hook_feedsr0  requests           r!   rw  z$_HookedSession._call_hook_before_run  s     J 
<,g		??&$__*T


)
)*g6G6G*LN


G--
.??

!
!'7??
;
< ##
:< n%r#   c                     t        |j                               t        |j                               z  }|r#t        |dz   t        t	        |            z         y )Nz Conflict(s): )setkeysru   strlist)r'   feeds1feeds2messageintersections        r!   r  z)_HookedSession._raise_if_feeds_intersects  sJ    v{{}%FKKM(::L#33c$|:L6MMNN r#   c                 V   t        |j                  |j                        |_        t        |j                  |j                        |_        t        |j                  |j                        |_        t        |j                  |j                        |_        |j
                  j                  j                  |j
                  j                         |j
                  j                  xs |j
                  j                  |j
                  _        |j                  xs |j                  |_	        y)a  Merge two instances of RunOptions into the first one.

    During the merger, the numerical fields including trace_level,
    timeout_in_ms, inter_op_thread_pool are set to the larger one of the two.
    The boolean value is set to the logical OR of the two.
    debug_tensor_watch_opts of the original options is extended with that from
    the incoming one.

    Args:
      options: The options to merge into.
      incoming_options: The options to be merged into the first argument.
    N)
maxtrace_leveltimeout_in_msinter_op_thread_pooloutput_partition_graphsdebug_optionsdebug_tensor_watch_optsr   reset_disk_byte_usage"report_tensor_allocations_upon_oom)r'   r   incoming_optionss      r!   r  z!_HookedSession._merge_run_options  s     g113C3O3OPG 5 5 0 > >@G#&w'C'C'7'L'L$NG &)''00'2G# 1188&&>>@ 	33 	=&&<< / 	22 	<;; .r#   r9  )
r   r   r   r   r=   rN  r   rw  r  r  r   r#   r!   r/  r/    s'     
!F8O
=r#   r/  )NNNNNNNr   r   r   NNT)9r   r   r   tensorflow.core.protobufr   tensorflow.python.checkpointr   r]   r   tensorflow.python.distributer   tensorflow.python.frameworkr   r   tensorflow.python.opsr	   r
   r   r   r   tensorflow.python.platformr   re   tensorflow.python.summaryr   tensorflow.python.trainingr   r   r   r   r[   r   r   r   tensorflow.python.utilr    tensorflow.python.util.tf_exportr   AbortedErrorUnavailableErrorrQ  objectr   r   r   r   ABCMetar   r   r   r   r   rB  rG  r   r.  r/  r   r#   r!   <module>r     s,    1 
 	 / E 3 G . + + 2 , + + < - > 2 3 > < 7 1 6 ))6+B+BC  h  !DE DE "DET 
m5` /01
$$#%!u5 2u5p %&'Bs{{ B (B *+,2(. 2( -2(j +,-'N> 'N .'NTk- k-\ '()`7( `7 *`7F /01f0 f 2fRHO HOVj/ jZ@/ @FA=_ A=r#   