
    BVh                     *   d Z ddlZddl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 Z"d Z# e!dg      	 	 	 d1d       Z$ ejJ                  dd       e!dg      	 	 	 	 d2d              Z& e!dg       	 	 	 	 	 d3d       Z' e!d      d4d       Z(d Z) e!d      d4d        Z*d! Z+ ejJ                  dd"       e!d#g      d$               Z, ejJ                  dd%       e!d&g      d'               Z- ejJ                  dd(       e!d)g      e
j\                  j^                  d*fd+              Z0d, Z1d5d-Z2 e!d.       G d/ d0e3             Z4y)6z@Checkpoint Manager and other utilities for managing checkpoints.    N)text_format)	saver_pb2)checkpoint_options)context)errors)ops)file_io)variable_scope)
tf_logging)training_util)CheckpointState)compat)deprecation)	tf_exportc                     t        j                         r| j                         S t        j                         j                  |       S )z$Returns the numpy value of a tensor.)r   executing_eagerlynumpyr   get_default_sessionrun)tensors    b/home/dcms/DCMS/lib/python3.12/site-packages/tensorflow/python/checkpoint/checkpoint_management.py	_evaluater   )   s4     <<>		 	 	"	&	&v	..    c                 J    |d}t         j                  j                  | |      S )a4  Returns a filename for storing the CheckpointState.

  Args:
    save_dir: The directory for saving and restoring checkpoints.
    latest_filename: Name of the file in 'save_dir' that is used
      to store the CheckpointState.

  Returns:
    The path of the file that contains the CheckpointState proto.
  
checkpoint)ospathjoin)save_dirlatest_filenames     r   _GetCheckpointFilenamer!   0   s$     "O	h	00r   z%train.generate_checkpoint_state_proto)v1c                 L   |g }|r|d   |k7  r't        j                  d|       |j                  |       |r)t        |      t        |      k7  rt	        d|d|d      t
        j                  j                  |       st
        j                  j                  |      s t
        j                  j                  ||       }t        |      D ]H  \  }}t
        j                  j                  |      r&t
        j                  j                  ||       ||<   J t        ||||      }|S )a  Generates a checkpoint state proto.

  Args:
    save_dir: Directory where the model was saved.
    model_checkpoint_path: The checkpoint file.
    all_model_checkpoint_paths: List of strings.  Paths to all not-yet-deleted
      checkpoints, sorted from oldest to newest.  If this is a non-empty list,
      the last element must be equal to model_checkpoint_path.  These paths
      are also saved in the CheckpointState proto.
    all_model_checkpoint_timestamps: A list of floats, indicating the number of
      seconds since the Epoch when each checkpoint was generated.
    last_preserved_timestamp: A float, indicating the number of seconds since
      the Epoch when the last preserved checkpoint was written, e.g. due to a
      `keep_checkpoint_every_n_hours` parameter (see
      `tf.train.CheckpointManager` for an implementation).
  Returns:
    CheckpointState proto with model_checkpoint_path and
    all_model_checkpoint_paths updated to either absolute paths or
    relative paths to the current save_dir.

  Raises:
    ValueError: If `all_model_checkpoint_timestamps` was provided but its length
      does not match `all_model_checkpoint_paths`.
  z<%s is not in all_model_checkpoint_paths. Manually adding it.zKCheckpoint timestamps, if provided, must match checkpoint paths (got paths z and timestamps ))model_checkpoint_pathall_model_checkpoint_pathsall_model_checkpoint_timestampslast_preserved_timestamp)logginginfoappendlen
ValueErrorr   r   isabsrelpath	enumerater   )r   r&   r'   r(   r)   ipcoord_checkpoint_protos           r   generate_checkpoint_state_protor5   @   s   <  '!#
$ $(==LLO&(%%&;<%./,-.
 &'F	HI I 
x	 77==./ ggoo.CXN45 E1WW]]1(*8(D"1%E +1!;&E7	9 
 r   ziUse `tf.train.CheckpointManager` to manage checkpoints rather than manually editing the Checkpoint proto.)dateinstructionsztrain.update_checkpoint_statec           	      (    t        | |||d||       y)a  Updates the content of the 'checkpoint' file.

  This updates the checkpoint file containing a CheckpointState
  proto.

  Args:
    save_dir: Directory where the model was saved.
    model_checkpoint_path: The checkpoint file.
    all_model_checkpoint_paths: List of strings.  Paths to all not-yet-deleted
      checkpoints, sorted from oldest to newest.  If this is a non-empty list,
      the last element must be equal to model_checkpoint_path.  These paths
      are also saved in the CheckpointState proto.
    latest_filename: Optional name of the checkpoint file.  Default to
      'checkpoint'.
    all_model_checkpoint_timestamps: Optional list of timestamps (floats,
      seconds since the Epoch) indicating when the checkpoints in
      `all_model_checkpoint_paths` were created.
    last_preserved_timestamp: A float, indicating the number of seconds since
      the Epoch when the last preserved checkpoint was written, e.g. due to a
      `keep_checkpoint_every_n_hours` parameter (see
      `tf.train.CheckpointManager` for an implementation).
  Raises:
    RuntimeError: If any of the model checkpoint paths conflict with the file
      containing CheckpointSate.
  F)r   r&   r'   r    save_relative_pathsr(   r)   N) update_checkpoint_state_internal)r   r&   r'   r    r(   r)   s         r   update_checkpoint_stater;      s"    H #1!;%&E79r   z*__internal__.train.update_checkpoint_statec                 D   t        | |      }|rt        j                  j                  |      r!t        j                  j	                  ||       }n|}g }	|D ]b  }
t        j                  j                  |
      r0|	j                  t        j                  j	                  |
|              R|	j                  |
       d t        | ||	||      }nt        | ||||      }||j                  k(  rt        d|z        t        j                  |t        j                  |             y)a  Updates the content of the 'checkpoint' file.

  This updates the checkpoint file containing a CheckpointState
  proto.

  Args:
    save_dir: Directory where the model was saved.
    model_checkpoint_path: The checkpoint file.
    all_model_checkpoint_paths: List of strings.  Paths to all not-yet-deleted
      checkpoints, sorted from oldest to newest.  If this is a non-empty list,
      the last element must be equal to model_checkpoint_path.  These paths
      are also saved in the CheckpointState proto.
    latest_filename: Optional name of the checkpoint file.  Default to
      'checkpoint'.
    save_relative_paths: If `True`, will write relative paths to the checkpoint
      state file.
    all_model_checkpoint_timestamps: Optional list of timestamps (floats,
      seconds since the Epoch) indicating when the checkpoints in
      `all_model_checkpoint_paths` were created.
    last_preserved_timestamp: A float, indicating the number of seconds since
      the Epoch when the last preserved checkpoint was written, e.g. due to a
      `keep_checkpoint_every_n_hours` parameter (see
      `tf.train.CheckpointManager` for an implementation).

  Raises:
    RuntimeError: If any of the model checkpoint paths conflict with the file
      containing CheckpointSate.
  )r'   r(   r)   z`Save path '%s' conflicts with path used for checkpoint state.  Please use a different save path.N)r!   r   r   r/   r0   r,   r5   r&   RuntimeErrorr	   atomic_write_string_to_filer   MessageToString)r   r&   r'   r    r9   r(   r)   coord_checkpoint_filenamerel_model_checkpoint_pathrel_all_model_checkpoint_pathsr3   ckpts               r   r:   r:      s   J 5XO	ww}}*+"$''//
#+ #8%'"' 1	q	&--bggooa.JK&--a0	1
 +!#A(G!9;D +#=(G!9;D $"<"<<
 N,- . . 
%%&?&1&A&A$&GIr   ztrain.get_checkpoint_statec                    t        | t        j                        rt        j                  |       } d}t	        | |      }d}	 t        j                  |      rt        j                  |      }t               }t        j                  ||       |j                  st        d| z         t        j                  j                  |j                        s/t        j                  j                  | |j                        |_        t!        |j"                        D ]R  \  }}t        j                  j                  |      r&t        j                  j                  | |      |j"                  |<   T |r|j1                          |S # t$        j&                  $ r]}t)        j*                  dt-        |      j.                  |       t)        j*                  d|       Y d}~|r|j1                          yyd}~wt        j2                  $ r]}t)        j*                  dt-        |      j.                  |       t)        j*                  d|       Y d}~|r|j1                          yyd}~ww xY w# |r|j1                          w w xY w)a  Returns CheckpointState proto from the "checkpoint" file.

  If the "checkpoint" file contains a valid CheckpointState
  proto, returns it.

  Args:
    checkpoint_dir: The directory of checkpoints.
    latest_filename: Optional name of the checkpoint file.  Default to
      'checkpoint'.

  Returns:
    A CheckpointState if the state was available, None
    otherwise.

  Raises:
    ValueError: if the checkpoint read doesn't have model_checkpoint_path set.
  Nz%Invalid checkpoint state loaded from z%s: %sz%s: Checkpoint ignored)
isinstancer   PathLikefspathr!   r	   file_existsread_file_to_stringr   r   Merger&   r.   r   r/   r   r1   r'   r   OpErrorr*   warningtype__name__close
ParseError)	checkpoint_dirr    rC   r@   ffile_contentr2   r3   es	            r   get_checkpoint_staterU      s   & ,YY~.N	$4^5DF
! 4500
#%ldd+''@)* + 	+ WW]]4556%'WW\\.262L2L&N"D;;< O$!Qww}}Q/1ww||NA/N$
)
)!
,O 	ggi	+ 
 OOHd1g..2OO,.GH 	ggi 	 
		 OOHd1g..2OO,.GHggi 	
 	ggi 	sE   C7E< 9/E< <IA G'I 'I=A I=I II I2c                 J    |t         j                  j                  k(  r| dz   S | S )a  Returns the pathname of a checkpoint file, given the checkpoint prefix.

  For V1 checkpoint, simply returns the prefix itself (the data file).  For V2,
  returns the pathname to the index file.

  Args:
    prefix: a string, the prefix of a checkpoint.
    format_version: the checkpoint format version that corresponds to the
      prefix.
  Returns:
    The pathname of a checkpoint file, taking into account the checkpoint
      format version.
  .index)r   SaverDefV2)prefixformat_versions     r   _prefix_to_checkpoint_pathr\   5  s(     y)),,,H	-r   ztrain.latest_checkpointc                    t        | |      }|r|j                  rt        |j                  t        j                  j
                        }t        |j                  t        j                  j                        }t        j                  |      st        j                  |      r|j                  S t        j                  d|j                         y)a  Finds the filename of latest saved checkpoint file.

  Gets the checkpoint state given the provided checkpoint_dir and looks for a
  corresponding TensorFlow 2 (preferred) or TensorFlow 1.x checkpoint path.
  The latest_filename argument is only applicable if you are saving checkpoint
  using `v1.train.Saver.save`


  See the [Training Checkpoints
  Guide](https://www.tensorflow.org/guide/checkpoint) for more details and
  examples.`

  Args:
    checkpoint_dir: Directory where the variables were saved.
    latest_filename: Optional name for the protocol buffer file that
      contains the list of most recent checkpoint filenames.
      See the corresponding argument to `v1.train.Saver.save`.

  Returns:
    The full path to the latest checkpoint or `None` if no checkpoint was found.
  z&Couldn't match files for checkpoint %sN)rU   r&   r\   r   rX   rY   V1r	   get_matching_filesr*   error)rQ   r    rC   v2_pathv1_paths        r   latest_checkpointrc   H  s    0 
no	>$	d((()C)C)2););)>)>@G()C)C)2););)>)>@G!!'*g.H.H/'''mm<..0	r   c                     t        | t        j                  j                        }t	        j
                  |      ryt	        j
                  |       ryy)a  Checks whether a V1 or V2 checkpoint exists with the specified prefix.

  This is an internal function to check if a checkpoint exists,
  since it takes into account the naming difference between V1 and V2 formats.

  Args:
    checkpoint_prefix: the prefix of a V1 or V2 checkpoint, with V2 taking
      priority.  Typically the result of `Saver.save()` or that of
      `tf.train.latest_checkpoint()`, regardless of sharded/non-sharded or
      V1/V2.
  Returns:
    A bool, true if a checkpoint referred to by `checkpoint_prefix` exists.
  TF)r\   r   rX   rY   r	   r_   )checkpoint_prefixpathnames     r   checkpoint_exists_internalrg   p  sF     ((9(1(:(:(=(=?()!!"34r   z;Use standard file APIs to check for files with this prefix.ztrain.checkpoint_existsc                     t        |       S )a  Checks whether a V1 or V2 checkpoint exists with the specified prefix.

  This is the recommended way to check if a checkpoint exists, since it takes
  into account the naming difference between V1 and V2 formats.

  Args:
    checkpoint_prefix: the prefix of a V1 or V2 checkpoint, with V2 taking
      priority.  Typically the result of `Saver.save()` or that of
      `tf.train.latest_checkpoint()`, regardless of sharded/non-sharded or
      V1/V2.

  Returns:
    A bool, true if a checkpoint referred to by `checkpoint_prefix` exists.
  )rg   )re   s    r   checkpoint_existsri     s    & 
$$5	66r   z*Use standard file utilities to get mtimes.ztrain.get_checkpoint_mtimesc                     g fd}| D ]7  }t        |t        j                  j                        } ||      r0 ||       9 S )a^  Returns the mtimes (modification timestamps) of the checkpoints.

  Globs for the checkpoints pointed to by `checkpoint_prefixes`.  If the files
  exist, collect their mtime.  Both V2 and V1 checkpoints are considered, in
  that priority.

  This is the recommended way to get the mtimes, since it takes into account
  the naming difference between V1 and V2 formats.

  Note: If not all checkpoints exist, the length of the returned mtimes list
  will be smaller than the length of `checkpoint_prefixes` list, so mapping
  checkpoints to corresponding mtimes will not be possible.

  Args:
    checkpoint_prefixes: a list of checkpoint paths, typically the results of
      `Saver.save()` or those of `tf.train.latest_checkpoint()`, regardless of
      sharded/non-sharded or V1/V2.
  Returns:
    A list of mtimes (in microseconds) of the found checkpoints.
  c                     t        j                  |       }|r5j                  t        j                  |d         j                  dz         yy)Nr   g    eATF)r	   r_   r,   stat
mtime_nsec)rf   fnamesmtimess     r   match_maybe_appendz1get_checkpoint_mtimes.<locals>.match_maybe_append  s@    ''1FmmGLL+66<=r   )r\   r   rX   rY   )checkpoint_prefixesrp   re   rf   ro   s       @r   get_checkpoint_mtimesrr     sY    2 & / *)*;*3*<*<*?*?AH(#()* 
-r   z8Use standard file APIs to delete files with this prefix.ztrain.remove_checkpointmetac                     t        t        | |             |t        j                  j                  k(  rt        | dz          t        | dz          yt        |        y)a  Removes a checkpoint given by `checkpoint_prefix`.

  Args:
    checkpoint_prefix: The prefix of a V1 or V2 checkpoint. Typically the result
      of `Saver.save()` or that of `tf.train.latest_checkpoint()`, regardless of
      sharded/non-sharded or V1/V2.
    checkpoint_format_version: `SaverDef.CheckpointFormatVersion`, defaults to
      `SaverDef.V2`.
    meta_graph_suffix: Suffix for `MetaGraphDef` file. Defaults to 'meta'.
  rW   .data-?????-of-?????N)_delete_file_if_existsmeta_graph_filenamer   rX   rY   )re   checkpoint_format_versionmeta_graph_suffixs      r   remove_checkpointrz     sU    " +->?A)"4"4"7"77,x78,/EEF ,-r   c                     t        j                  |       D ]  }	 t        j                  |        y# t        j                  $ r t        j                  d|       Y Gw xY w)z"Deletes files matching `filespec`.zsHit NotFoundError when deleting '%s', possibly because another process/thread is also deleting/moving the same fileN)r	   r_   delete_filer   NotFoundErrorr*   rL   )filespecrf   s     r   rv   rv     sa    ,,X6 LhL(#L  LooABJLLs   2)AAc                 Z    t        j                  dd|       }dj                  ||g      }|S )zReturns the meta graph filename.

  Args:
    checkpoint_filename: Name of the checkpoint file.
    meta_graph_suffix: Suffix for `MetaGraphDef` file. Defaults to 'meta'.

  Returns:
    MetaGraph file name.
  z-[\d\?]+-of-\d+$ .)resubr   )checkpoint_filenamery   basenamesuffixed_filenames       r   rw   rw     s3     VV'-@A(hh*;<=	r   ztrain.CheckpointManagerc                       e Zd ZdZ	 	 	 	 	 ddZed        Zed        Zed        Zed        Z	d Z
d	 Zed
        Zed        ZddZd Zd Zy)CheckpointManageraN  Manages multiple checkpoints by keeping some and deleting unneeded ones.

  Example usage:

  ```python
  import tensorflow as tf
  checkpoint = tf.train.Checkpoint(optimizer=optimizer, model=model)
  manager = tf.train.CheckpointManager(
      checkpoint, directory="/tmp/model", max_to_keep=5)
  status = checkpoint.restore(manager.latest_checkpoint)
  while True:
    # train
    manager.save()
  ```

  `CheckpointManager` preserves its own state across instantiations (see the
  `__init__` documentation for details). Only one should be active in a
  particular directory at a time.
  Nc	                    || _         d| _        ||dk  rt        d|fz        || _        || _        t        |t        j                        rt        j                  |      }|| _	        t        j                  j                  ||      | _        || _        ||t        d      d| _        || _        || _        t#        |      }	t%        j$                         }
t'        j(                         | _        |	d| _        |
dz
  | _        y|	j0                  | _        |	j2                  | _        |
| j.                  k  r-t5        j6                  d| j.                  |
z
  fz         |
| _        |	j8                  }|	j:                  }~	|s| j.                  gt=        |      z  }t?        ||      D ]0  \  }}tA        ||
      }|| j.                  kD  s"|| j*                  |<   2 y)a  Configure a `CheckpointManager` for use in `directory`.

    If a `CheckpointManager` was previously used in `directory`, its
    state will be restored. This includes the list of managed checkpoints and
    the timestamp bookkeeping necessary to support
    `keep_checkpoint_every_n_hours`. The behavior of the new `CheckpointManager`
    will be the same as the previous `CheckpointManager`, including cleaning up
    existing checkpoints if appropriate.

    Checkpoints are only considered for deletion just after a new checkpoint has
    been added. At that point, `max_to_keep` checkpoints will remain in an
    "active set". Once a checkpoint is preserved by
    `keep_checkpoint_every_n_hours` it will not be deleted by this
    `CheckpointManager` or any future `CheckpointManager` instantiated in
    `directory` (regardless of the new setting of
    `keep_checkpoint_every_n_hours`). The `max_to_keep` checkpoints in the
    active set may be deleted by this `CheckpointManager` or a future
    `CheckpointManager` instantiated in `directory` (subject to its
    `max_to_keep` and `keep_checkpoint_every_n_hours` settings).

    `CheckpointManager` can be also used for initializing the model if
    there is no checkpoints for restoring in `directory`. An example usage is:

    >>> import tempfile

    >>> tmp_dir = tempfile.mkdtemp()
    >>> checkpoint = tf.train.Checkpoint()
    >>> init_path = checkpoint.save(os.path.join(tmp_dir, 'init'))

    >>> def init_fn():
    ...   # Partially restore the checkpoint from `init_path`.
    ...   checkpoint.restore(init_path)

    >>> manager = tf.train.CheckpointManager(
    ...     checkpoint,
    ...     directory=os.path.join(tmp_dir, 'ckpt'),
    ...     max_to_keep=None,
    ...     init_fn=init_fn)
    >>> # `restore_or_initialize` will call `init_fn` if there is no existing
    >>> # checkpoint in `directory`.
    >>> manager.restore_or_initialize()

    Args:
      checkpoint: The `tf.train.Checkpoint` instance to save and manage
        checkpoints for.
      directory: The path to a directory in which to write checkpoints. A
        special file named "checkpoint" is also written to this directory (in a
        human-readable text format) which contains the state of the
        `CheckpointManager`.
      max_to_keep: An integer, the number of checkpoints to keep. Unless
        preserved by `keep_checkpoint_every_n_hours`, checkpoints will be
        deleted from the active set, oldest first, until only `max_to_keep`
        checkpoints remain. If `None`, no checkpoints are deleted and everything
        stays in the active set. Note that `max_to_keep=None` will keep all
        checkpoint paths in memory and in the checkpoint state protocol buffer
        on disk.
      keep_checkpoint_every_n_hours: Upon removal from the active set, a
        checkpoint will be preserved if it has been at least
        `keep_checkpoint_every_n_hours` since the last preserved checkpoint. The
        default setting of `None` does not preserve any checkpoints in this way.
      checkpoint_name: Custom name for the checkpoint file.
      step_counter: A `tf.Variable` instance for checking the current step
        counter value, in case users want to save checkpoints every N steps.
      checkpoint_interval: An integer, indicates the minimum step interval
        between two checkpoints.
      init_fn: Callable. A function to do customized initialization if no
        checkpoints are in the directory.

    Raises:
      ValueError: If `max_to_keep` is not a positive integer.
    Nr   z@Expected a positive integer or `None` for `max_to_keep`, got %d.zE`step_counter` should be passed if `checkpoint_interval` is not None.g      ?zWtime.time() returned a value %f seconds behind the last preserved checkpoint timestamp.)!_checkpoint_save_counter_assignr.   _max_to_keep_keep_checkpoint_every_n_hoursrE   r   rF   rG   
_directoryr   r   _checkpoint_prefix_init_fn_last_checkpoint_step_step_counter_checkpoint_intervalrU   timecollectionsOrderedDict_maybe_delete_latest_checkpoint_last_preserved_timestampr&   r)   r*   rL   r(   r'   r-   zipmin)selfr   	directorymax_to_keepkeep_checkpoint_every_n_hourscheckpoint_namestep_countercheckpoint_intervalinit_fnrecovered_statecurrent_clockall_timestamps	all_pathsfilename	timestamps                  r   __init__zCheckpointManager.__init__  s   ` "D $D;!#3N  $D*GD')R[[)))I&iDO ggll9oFDDM&		 > ? 	?#'d 'd 3D*95OIIKM$002D $d (5r'9d$ / E Ed'6'O'Od$	77	7 	/--=?@	A *7&&FFn!<<i
889C	NJ!$Y!? 3
(I	=1	t555)2$

X
&3r   c                     | j                   S N)r   r   s    r   r   zCheckpointManager.directory  s    ??r   c                     | j                   S r   )r   r   s    r   r   z%CheckpointManager.checkpoint_interval  s    $$$r   c                     | j                   S )ai  The prefix of the most recent checkpoint in `directory`.

    Equivalent to `tf.train.latest_checkpoint(directory)` where `directory` is
    the constructor argument to `CheckpointManager`.

    Suitable for passing to `tf.train.Checkpoint.restore` to resume training.

    Returns:
      The checkpoint prefix. If there are no checkpoints, returns `None`.
    )r   r   s    r   rc   z#CheckpointManager.latest_checkpoint  s     """r   c                 H    t        | j                  j                               S )zA list of managed checkpoints.

    Note that checkpoints saved due to `keep_checkpoint_every_n_hours` will not
    show up in this list (to avoid ever-growing filename lists).

    Returns:
      A list of filenames, sorted from oldest to newest.
    )listr   keysr   s    r   checkpointszCheckpointManager.checkpoints  s     ""'')**r   c                    | j                   syt        | j                        | j                   kD  r| j                  j                  d      \  }}| j                  r'|| j                  dz  z
  | j
                  k\  r|| _        tt        |dz          t        |dz          t        | j                        | j                   kD  ryy)z)Deletes or preserves managed checkpoints.NF)lastg      @rW   ru   )r   r-   r   popitemr   r   rv   )r   r   r   s      r   _sweepzCheckpointManager._sweep  s     
d  
!D$5$5
5 ..66E6Bh	 
-
-4>>FF001)2&X01X(>>? d  
!D$5$5
5r   c                     t        | j                  j                          \  }}t        | j                  | j
                  ||| j                  d       y)z5Saves the `CheckpointManager`'s state in `directory`.T)r&   r'   r(   r)   r9   N)r   r   itemsr:   r   rc   r   )r   	filenames
timestampss      r   _record_statezCheckpointManager._record_state  sJ    !3!3!9!9!;<Iz$"44#,(2!%!?!? "r   c                     | j                   S )a  A common prefix for all checkpoints saved with this manager.

    For example, if `directory` (a constructor argument) were `"/tmp/tf-model"`,
    `prefix` would be `"/tmp/tf-model/ckpt"` and checkpoints would generally be
    numbered `"/tmp/tf-model/ckpt-1"`, `"/tmp/tf-model/ckpt-2"`, and so on. Each
    checkpoint has several associated files
    (e.g. `"/tmp/tf-model/ckpt-2.index"`).

    Returns:
      A string prefix.
    )r   r   s    r   _prefixzCheckpointManager._prefix  s     """r   c                     | j                   S )z)Returns the `tf.train.Checkpoint` object.)r   r   s    r   r   zCheckpointManager.checkpoint  s     r   c                    
  j                   Wt         j                        } j                  /| j                  k(  ry|r| j                   j                   z   k  ry| _        t	        j
                         r* j                  j                  }|j                  d       d
nt        j                         

fd}t        j                  |      5   j                  j                  }ddd        j                  j                  dd       _        
j                   j                         |}t        |t         j"                        st%        j&                  
|      }d j(                  |fz  } fd}|t+        j,                  |g	      }nEt/        j.                  |      }|j0                  	|g|_        n|j0                  j3                  |        j                  j5                  ||
      }	|	S # 1 sw Y   xY w)a  Creates a new checkpoint and manages it.

    Args:
      checkpoint_number: An optional integer, or an integer-dtype `Variable` or
        `Tensor`, used to number the checkpoint. If `None` (default),
        checkpoints are numbered using `checkpoint.save_counter`. Even if
        `checkpoint_number` is provided, `save_counter` is still incremented. A
        user-provided `checkpoint_number` is not incremented even if it is a
        `Variable`.
      check_interval: An optional boolean. The argument is only effective when
        `checkpoint_interval` is passed into the manager. If `True`, the manager
        will only save the checkpoint if the interval between checkpoints is
        larger than `checkpoint_interval`. Otherwise it will always save the
        checkpoint unless a checkpoint has already been saved for the current
        step.
      options: Optional `tf.train.CheckpointOptions` object. This argument only
        works with TF2 checkpoint objects. For example, options =
        tf.saved_model.SaveOptions(experimental_io_device='/job:localhost')

    Returns:
      The path to the new checkpoint. It is also recorded in the `checkpoints`
      and `latest_checkpoint` properties. `None` if no checkpoint is saved.
    N   c                 N     | di |}j                  |j                         |S )z9Initialize the save counter if it has been newly created. )r   initializer)next_creatorkwargsvsessions      r   _initializing_creatorz5CheckpointManager.save.<locals>._initializing_creator!  s%    "6"AMM"r   F)
read_value)sessglobal_step_tensorz%s-%dc                     t        j                          }| j                  v rj                  | = |j                  | <   | _        j                          j	                          j                          y r   )r   r   r   r   r   )	save_pathr   r   s     r   _record_and_sweep_statez7CheckpointManager.save.<locals>._record_and_sweep_state3  si    ))+i 
d((	(y)&/d# )d
 
kkm r   )experimental_write_callbacks)options)r   r   r   r   r   r   r   save_counter
assign_addr   r   r
   variable_creator_scoper   r   rE   r   integral_typesr   global_stepr   r   CheckpointOptionscopyr   r,   _write)r   checkpoint_numbercheck_intervalr   current_stepr   r   rZ   r   r   r   s   `         @r   savezCheckpointManager.save  s   0   ,t112l		#	#	/4555l&&)B)BBD#/d    "%%22la g'')g 001FG 5''445		"	"	*$0$;$;A%$;$P!kk$++, &')>)>?'33+<>&788F& "44(?'@g 		'"g		-	-	50G/H,,,334KL  '''@I[5 5s   G99Hc                 ,   | j                   W| j                  j                  | j                          | j                  t	        | j
                        | _        | j                   S | j                  %| j                          t        j                  d       y)a  Restore items in `checkpoint` from the latest checkpoint file.

    This method will first try to restore from the most recent checkpoint in
    `directory`. If no checkpoints exist in `directory`, and `init_fn` is
    specified, this method will call `init_fn` to do customized
    initialization. This can be used to support initialization from pretrained
    models.

    Note that unlike `tf.train.Checkpoint.restore()`, this method doesn't return
    a load status object that users can run assertions on
    (e.g. assert_consumed()). Thus to run assertions, users should directly use
    `tf.train.Checkpoint.restore()` method.

    Returns:
      The restored checkpoint path if the latest checkpoint is found and
      restored. Otherwise None.
    Nz?Customized initialization is done through the passed `init_fn`.)
r   r   restorer   r   r   r   r   r*   r+   r   s    r   restore_or_initializez'CheckpointManager.restore_or_initializeV  s{    2 *
t667		"	"	.%.t/A/A%B"$$$}} 
mmoll
KMr   c                 R    | j                   r| j                   j                          yy)z4Wait for any outstanding save or restore operations.N)r   syncr   s    r   r   zCheckpointManager.sync{  s"    
 r   )NrC   NNN)NTN)rN   
__module____qualname____doc__r   propertyr   r   rc   r   r   r   r   r   r   r   r   r   r   r   r   r     s    0 .2% #'D3L   % % # # 	+ 	+@&	" # #  ^@#Jr   r   )NNN)NNNN)NNFNNr   )rs   )5r   r   r   os.pathr   r   r   google.protobufr   tensorflow.core.protobufr   tensorflow.python.checkpointr   tensorflow.python.eagerr   tensorflow.python.frameworkr   r   tensorflow.python.lib.ior	   tensorflow.python.opsr
   tensorflow.python.platformr   r*   tensorflow.python.trainingr   /tensorflow.python.training.checkpoint_state_pb2r   tensorflow.python.utilr   r    tensorflow.python.util.tf_exportr   r   r!   r5   
deprecatedr;   r:   rU   r\   rc   rg   ri   rr   rX   rY   rz   rv   rw   objectr   r   r   r   <module>r      s0  " G    	  ' . ; + . + , 0 < 4 K ) . 6/1  678 @DDH=A	=  9= @ 	GI ./0 8<,0<@59&9 1	I
&9R 7B? AE599>EI>BGI @GIT '(7 )7t& $%$ &$N0 	NP ()*7 +P7$ 	=? ,-.' /?'T 	KM ()*090B0B0E0E(.. +M.0L& $%w w &wr   