o
    ?e"[                     @   s   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 Zdd ZedgdG dd dZdd ZG dd dZdS )z<Training helper that checkpoints models and creates session.    N)checkpoint_management)session)distribute_lib)errors)ops)
tf_logging)	tf_exportc                 C   s(   | du rdS t | dr| jS dt|  S )zReturns object name if it has one, or a message otherwise.

  This is useful for names that apper in error messages.
  Args:
    obj: Object to get the name of.
  Returns:
    name, "None", or a "no name" message.
  NNonenamez<no name for %s>)hasattrr
   type)obj r   k/home/www/facesmatcher.com/pyenv/lib/python3.10/site-packages/tensorflow/python/training/session_manager.py_maybe_name   s
   	
r   c                 C   s(   t d}|r| | || | dS )z@Restores checkpoint values and SavedModel initializers if found.Zsaved_model_initializersN)r   Zget_collectionrunrestore)sesssaverpathZsaved_model_init_opsr   r   r   :_restore_checkpoint_and_maybe_run_saved_model_initializers-   s   

r   ztrain.SessionManager)v1c                   @   s   e Zd ZdZ							dddZ						ddd	Z									dd
dZ						dddZdedfddZ	dd Z
dd Zdd Zdd ZdS )SessionManagera  Training helper that restores from checkpoint and creates session.

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

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

  ### Usage:

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

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

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

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

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

  N   c                 C   sd   |du rt  }|| _|| _|| _|| _|| _d| _|| _|| _	|dur.|du r0t
d| dS dS )a_  Creates a SessionManager.

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

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

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

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

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

    Args:
      local_init_op: An `Operation` run immediately after session creation.
         Usually used to initialize tables and local variables.
      ready_op: An `Operation` to check if the model is initialized.
      ready_for_local_init_op: An `Operation` to check if the model is ready
         to run local_init_op.
      graph: The `Graph` that the model will use.
      recovery_wait_secs: Seconds between checks for the model to be ready.
      local_init_run_options: RunOptions to be passed to session.run when
        executing the local_init_op.
      local_init_feed_dict: Optional session feed dictionary to use when running
        the local_init_op.

    Raises:
      ValueError: If ready_for_local_init_op is not None but local_init_op is
        None
    NzgIf you pass a ready_for_local_init_op you must also pass a local_init_op , ready_for_local_init_op [%s])r   Zget_default_graph_local_init_op	_ready_op_ready_for_local_init_op_graph_recovery_wait_secs_target_local_init_run_options_local_init_feed_dict
ValueError)selfZlocal_init_opZready_opZready_for_local_init_opgraphZrecovery_wait_secsZlocal_init_run_optionsZlocal_init_feed_dictr   r   r   __init__r   s   1zSessionManager.__init__F   c                 C   s   || _ t }|rt|jdr|j  tj| j | j|d}	|r&|r&t	d|r,|s0|s0|	dfS |r<t
|	|| |	dfS d}
t|}|rH|jsm|rd|
|k rdtd t| j |
| j7 }
t|}n|	dfS |rH|jrHt
|	||j ||j |	dfS )af  Creates a `Session`, and tries to restore a checkpoint.


    Args:
      master: `String` representation of the TensorFlow master to use.
      saver: A `Saver` object used to restore a model.
      checkpoint_dir: Path to the checkpoint files. The latest checkpoint in the
        dir will be used to restore.
      checkpoint_filename_with_path: Full file name path to the checkpoint file.
      wait_for_checkpoint: Whether to wait for checkpoint to become available.
      max_wait_secs: Maximum time to wait for checkpoints to become available.
      config: Optional `ConfigProto` proto used to configure the session.

    Returns:
      A pair (sess, is_restored) where 'is_restored' is `True` if
      the session could be restored, `False` otherwise.

    Raises:
      ValueError: If both checkpoint_dir and checkpoint_filename_with_path are
        set.
    _experimental_initialize_systemr$   configzFCan not provide both checkpoint_dir and checkpoint_filename_with_path.FTr   z'Waiting for checkpoint to be available.)r   r   Zget_strategyr   extendedr'   r   Sessionr   r"   r   r   Zget_checkpoint_stateZmodel_checkpoint_pathlogginginfotimesleepr   Zrecover_last_checkpointsZall_model_checkpoint_paths)r#   masterr   checkpoint_dircheckpoint_filename_with_pathwait_for_checkpointmax_wait_secsr)   Zstrategyr   Z	wait_timeZckptr   r   r   _restore_checkpoint   s>   







z"SessionManager._restore_checkpointc              	   C   s   | j |||||||d\}}|s0|du r|
s| jdu rtd|dur*|j||	d |
r0|
| | |\}}|sDtdt||
|f | |\}}|sZtdt||
| j|f |S )a>	  Creates a `Session`. Makes sure the model is ready to be used.

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

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

    If the model is recovered from a checkpoint it is assumed that all
    global variables have been initialized, in particular neither `init_op`
    nor `init_fn` will be executed.

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

    Args:
      master: `String` representation of the TensorFlow master to use.
      init_op: Optional `Operation` used to initialize the model.
      saver: A `Saver` object used to restore a model.
      checkpoint_dir: Path to the checkpoint files. The latest checkpoint in the
        dir will be used to restore.
      checkpoint_filename_with_path: Full file name path to the checkpoint file.
      wait_for_checkpoint: Whether to wait for checkpoint to become available.
      max_wait_secs: Maximum time to wait for checkpoints to become available.
      config: Optional `ConfigProto` proto used to configure the session.
      init_feed_dict: Optional dictionary that maps `Tensor` objects to feed
        values.  This feed dictionary is passed to the session `run()` call when
        running the init op.
      init_fn: Optional callable used to initialize the model. Called after the
        optional `init_op` is called.  The callable must accept one argument,
        the session being initialized.

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

    Raises:
      RuntimeError: If the model cannot be initialized or recovered.
      ValueError: If both checkpoint_dir and checkpoint_filename_with_path are
        set.
    r1   r2   r3   r4   r)   NzMModel is not initialized and no init_op or init_fn or local_init_op was given)	feed_dictz]Init operations did not make model ready for local_init.  Init op: %s, init fn: %s, error: %szaInit operations did not make model ready.  Init op: %s, init fn: %s, local_init_op: %s, error: %s)r5   r   RuntimeErrorr   _try_run_local_init_opr   _model_ready)r#   r0   Zinit_opr   r1   r2   r3   r4   r)   Zinit_feed_dictZinit_fnr   is_loaded_from_checkpointlocal_init_successmsgis_readyr   r   r   prepare_session   sD   ;
zSessionManager.prepare_sessionc              	   C   s   | j |||||||d\}}	| |\}
}|	s|dfS |p|}|
s,td|| |dfS | |\}}|s@td|| |dfS td| ||	fS )a  Creates a `Session`, recovering if possible.

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

    Args:
      master: `String` representation of the TensorFlow master to use.
      saver: A `Saver` object used to restore a model.
      checkpoint_dir: Path to the checkpoint files. The latest checkpoint in the
        dir will be used to restore.
      checkpoint_filename_with_path: Full file name path to the checkpoint file.
      wait_for_checkpoint: Whether to wait for checkpoint to become available.
      max_wait_secs: Maximum time to wait for checkpoints to become available.
      config: Optional `ConfigProto` proto used to configure the session.

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

    Raises:
      ValueError: If both checkpoint_dir and checkpoint_filename_with_path are
        set.
    r6   FzCRestoring model from %s did not make model ready for local init: %sz4Restoring model from %s did not make model ready: %szRestored model from %s)r5   r9   r,   r-   r:   )r#   r0   r   r1   r2   r3   r4   r)   r   r;   r<   r=   Zrestoring_filer>   r   r   r   recover_sessionV  s6    

zSessionManager.recover_sessionInfc                 C   s   || _ |du rtd}t|}	 tj| j | j|d}d}d}| |\}}|r2| |\}	}|	r2|S | | |	 | j
 }
|
dk rLtddd|f td|| t| j
 q)aO  Creates a new `Session` and waits for model to be ready.

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

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

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

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

    Raises:
      tf.DeadlineExceededError: if the session is not available after
        max_wait_secs.
    NrA   Tr(   r   z,Session was not ready after waiting %d secs.zGWaiting for model to be ready.  Ready_for_local_init_op:  %s, ready: %s)r   float_CountDownTimerr   r+   r   r9   r:   _safe_closesecs_remainingr   r   ZDeadlineExceededErrorr,   r-   r.   r/   )r#   r0   r)   r4   timerr   Znot_ready_msgZnot_ready_local_msgr<   r>   Zremaining_ms_after_waitr   r   r   wait_for_session  s8   
zSessionManager.wait_for_sessionc                 C   s$   z|   W dS  ty   Y dS w )zCloses a session without raising an exception.

    Just like sess.close() but ignores exceptions.

    Args:
      sess: A `Session`.
    N)close	Exceptionr#   r   r   r   r   rD     s
   	zSessionManager._safe_closec                 C      t | j|dS )a  Checks if the model is ready or not.

    Args:
      sess: A `Session`.

    Returns:
      A tuple (is_ready, msg), where is_ready is True if ready and False
      otherwise, and msg is `None` if the model is ready, a `String` with the
      reason why it is not ready otherwise.
    zModel not ready)_readyr   rJ   r   r   r   r:     s   zSessionManager._model_readyc                 C   rK   )a\  Checks if the model is ready to run local_init_op.

    Args:
      sess: A `Session`.

    Returns:
      A tuple (is_ready, msg), where is_ready is True if ready to run
      local_init_op and False otherwise, and msg is `None` if the model is
      ready to run local_init_op, a `String` with the reason why it is not ready
      otherwise.
    zModel not ready for local init)rL   r   rJ   r   r   r   _model_ready_for_local_init  s   z*SessionManager._model_ready_for_local_initc                 C   sV   | j dur)| |\}}|r%td |j| j | j| jd td dS d|fS dS )an  Tries to run _local_init_op, if not None, and is ready for local init.

    Args:
      sess: A `Session`.

    Returns:
      A tuple (is_successful, msg), where is_successful is True if
      _local_init_op is None, or we ran _local_init_op, and False otherwise;
      and msg is a `String` with the reason why the model was not ready to run
      local init.
    NzRunning local_init_op.)r7   optionszDone running local_init_op.TNF)r   rM   r,   r-   r   r!   r    )r#   r   Zis_ready_for_local_initr=   r   r   r   r9     s   


z%SessionManager._try_run_local_init_op)NNNNr   NN)NNNFr&   N)	NNNNFr&   NNN)__name__
__module____qualname____doc__r%   r5   r?   r@   rB   rG   rD   r:   rM   r9   r   r   r   r   r   E   sN    ,
C
I
^
@;r   c              
   C   s   | du rdS z(| | }|du s|jtjks|jdkrW dS ddd |D }dd| fW S  tjyX } zd	t|vrHt	
d
|t| |dt|fW  Y d}~S d}~ww )a  Checks if the model is ready or not, as determined by op.

  Args:
    op: An op, either _ready_op or _ready_for_local_init_op, which defines the
      readiness of the model.
    sess: A `Session`.
    msg: A message to log to warning if not ready

  Returns:
    A tuple (is_ready, msg), where is_ready is True if ready and False
    otherwise, and msg is `None` if the model is ready, a `String` with the
    reason why it is not ready otherwise.
  NrO   r   z, c                 S   s   g | ]}| d qS )zutf-8)decode).0ir   r   r   
<listcomp>6  s    z_ready.<locals>.<listcomp>FzVariables not initialized: Zuninitializedz%s : error [%s])r   ZdtypenpZint32sizejoinr   ZFailedPreconditionErrorstrr,   warning)opr   r=   Zready_valueZnon_initialized_varnameser   r   r   rL     s&   
rL   c                   @   s(   e Zd ZdZddgZdd Zdd ZdS )	rC   z.A timer that tracks a duration since creation._start_time_secs_duration_secsc                 C   s   t   | _|| _d S )N)r.   r_   r`   )r#   Zduration_secsr   r   r   r%   D  s   

z_CountDownTimer.__init__c                 C   s   | j t | j  }td|S )Nr   )r`   r.   r_   max)r#   diffr   r   r   rE   H  s   
z_CountDownTimer.secs_remainingN)rP   rQ   rR   rS   	__slots__r%   rE   r   r   r   r   rC   ?  s
    rC   )rS   r.   numpyrX   Ztensorflow.python.checkpointr   Ztensorflow.python.clientr   Ztensorflow.python.distributer   Ztensorflow.python.frameworkr   r   Ztensorflow.python.platformr   r,   Z tensorflow.python.util.tf_exportr   r   r   r   rL   rC   r   r   r   r   <module>   s&   
   U'