
    BVh_Y                        d Z ddlm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 g dZ ed      d        Z ed      d        Z ed      d        Z	 	 	 d#dZ ed      	 	 	 d$d       Z  edg      d        Z!d Z"d Z#	 d%dZ$d  Z%d! Z&d" Z'y)&a   Tools to work with name-based checkpoints.

While some of these symbols also work with the TF2 object-based checkpoints,
they are not recommended for TF2. Please check  `tensorflow/python/checkpoint`
for newer utilities built to work with TF2 checkpoints.
    )abcN)checkpoint_management)distribute_lib)ops)io_ops)resource_variable_ops)variable_scope)	variables)gfile)
tf_logging)py_checkpoint_reader)saveable_object_util)	tf_export)load_checkpointload_variablelist_variablescheckpoints_iteratorinit_from_checkpointztrain.load_checkpointc                 b    t        |       }|t        d| z        t        j                  |      S )a  Returns `CheckpointReader` for checkpoint found in `ckpt_dir_or_file`.

  If `ckpt_dir_or_file` resolves to a directory with multiple checkpoints,
  reader for the latest checkpoint is returned.

  Example usage:

  ```python
  import tensorflow as tf
  a = tf.Variable(1.0)
  b = tf.Variable(2.0)
  ckpt = tf.train.Checkpoint(var_list={'a': a, 'b': b})
  ckpt_path = ckpt.save('tmp-ckpt')
  reader= tf.train.load_checkpoint(ckpt_path)
  print(reader.get_tensor('var_list/a/.ATTRIBUTES/VARIABLE_VALUE'))  # 1.0
  ```

  Args:
    ckpt_dir_or_file: Directory with checkpoints file or path to checkpoint
      file.

  Returns:
    `CheckpointReader` object.

  Raises:
    ValueError: If `ckpt_dir_or_file` resolves to a directory with no
      checkpoints.
  zDCouldn't find 'checkpoint' file or checkpoints in given directory %s)_get_checkpoint_filename
ValueErrorr   NewCheckpointReader)ckpt_dir_or_filefilenames     [/home/dcms/DCMS/lib/python3.12/site-packages/tensorflow/python/training/checkpoint_utils.pyr   r   .   s@    < &&67(
 *,<= > >		1	1(	;;    ztrain.load_variablec                 f    |j                  d      r|dd }t        |       }|j                  |      S )a  Returns the tensor value of the given variable in the checkpoint.

  When the variable name is unknown, you can use `tf.train.list_variables` to
  inspect all the variable names.

  Example usage:

  ```python
  import tensorflow as tf
  a = tf.Variable(1.0)
  b = tf.Variable(2.0)
  ckpt = tf.train.Checkpoint(var_list={'a': a, 'b': b})
  ckpt_path = ckpt.save('tmp-ckpt')
  var= tf.train.load_variable(
      ckpt_path, 'var_list/a/.ATTRIBUTES/VARIABLE_VALUE')
  print(var)  # 1.0
  ```

  Args:
    ckpt_dir_or_file: Directory with checkpoints file or path to checkpoint.
    name: Name of the variable to return.

  Returns:
    A numpy `ndarray` with a copy of the value of this variable.
  z:0N)endswithr   
get_tensor)r   namereaders      r   r   r   S   s7    8 
]]49D+,&			4	  r   ztrain.list_variablesc                     t        |       }|j                         }t        |j                               }g }|D ]  }|j	                  |||   f        |S )ad  Lists the checkpoint keys and shapes of variables in a checkpoint.

  Checkpoint keys are paths in a checkpoint graph.

  Example usage:

  ```python
  import tensorflow as tf
  import os
  ckpt_directory = "/tmp/training_checkpoints/ckpt"
  ckpt = tf.train.Checkpoint(optimizer=optimizer, model=model)
  manager = tf.train.CheckpointManager(ckpt, ckpt_directory, max_to_keep=3)
  train_and_checkpoint(model, manager)
  tf.train.list_variables(manager.latest_checkpoint)
  ```

  Args:
    ckpt_dir_or_file: Directory with checkpoints file or path to checkpoint.

  Returns:
    List of tuples `(key, shape)`.
  )r   get_variable_to_shape_mapsortedkeysappend)r   r"   variable_mapnamesresultr!   s         r   r   r   u   s_    0 +,&113,
""$
%%& .d
MM4d+,-.	-r   c                 6   t        j                  d|        |t        j                         |z   nd}	 t        j                  |       }|||k(  r3|t        j                         |z   |kD  ryt        j
                  |       nt        j                  d|       |S h)a  Waits until a new checkpoint file is found.

  Args:
    checkpoint_dir: The directory in which checkpoints are saved.
    last_checkpoint: The last checkpoint path used or `None` if we're expecting
      a checkpoint for the first time.
    seconds_to_sleep: The number of seconds to sleep for before looking for a
      new checkpoint.
    timeout: The maximum number of seconds to wait. If left as `None`, then the
      process will wait indefinitely.

  Returns:
    a new checkpoint path, or None if the timeout was reached.
  z Waiting for new checkpoint at %sNzFound new checkpoint at %s)logginginfotimer   latest_checkpointsleep)checkpoint_dirlast_checkpointseconds_to_sleeptimeout	stop_timecheckpoint_paths         r   wait_for_new_checkpointr7      s    $ 
,,1>B'.':diikG#)+==nMO/_"D		499;1A#AI#M
jj!"ll/A 	r   ztrain.checkpoints_iteratorc              #   :  K   d}	 t        | ||      }|6|st        j                  d       y |       rt        j                  d       yGt        j                         }|}| ||z   t        j                         z
  }|dkD  rt        j                  |       w)ae  Continuously yield new checkpoint files as they appear.

  The iterator only checks for new checkpoints when control flow has been
  reverted to it. This means it can miss checkpoints if your code takes longer
  to run between iterations than `min_interval_secs` or the interval at which
  new checkpoints are written.

  The `timeout` argument is the maximum number of seconds to block waiting for
  a new checkpoint.  It is used in combination with the `timeout_fn` as
  follows:

  * If the timeout expires and no `timeout_fn` was specified, the iterator
    stops yielding.
  * If a `timeout_fn` was specified, that function is called and if it returns
    a true boolean value the iterator stops yielding.
  * If the function returns a false boolean value then the iterator resumes the
    wait for new checkpoints.  At this point the timeout logic applies again.

  This behavior gives control to callers on what to do if checkpoints do not
  come fast enough or stop being generated.  For example, if callers have a way
  to detect that the training has stopped and know that no new checkpoints
  will be generated, they can provide a `timeout_fn` that returns `True` when
  the training has stopped.  If they know that the training is still going on
  they return `False` instead.

  Args:
    checkpoint_dir: The directory in which checkpoints are saved.
    min_interval_secs: The minimum number of seconds between yielding
      checkpoints.
    timeout: The maximum number of seconds to wait between checkpoints. If left
      as `None`, then the process will wait indefinitely.
    timeout_fn: Optional function to call after a timeout.  If the function
      returns True, then it means that no new checkpoints will be generated and
      the iterator will exit.  The function is called with no arguments.

  Yields:
    String paths to latest checkpoint files as they arrive.
  N)r4   z8Timed-out waiting for a checkpoint (without timeout_fn).z#Timed-out waiting for a checkpoint.r   )r7   r,   r-   r.   r0   )r1   min_interval_secsr4   
timeout_fnr6   new_checkpoint_pathstarttime_to_next_evals           r   r   r      s     V /1:"OP	:; 	IIKE)O
 11DIIK?1
jj"#) 	s   BBztrain.init_from_checkpoint)v1c                       fd}t        j                         r	 |d       yt        j                         j                  |       y)a  Replaces `tf.Variable` initializers so they load from a checkpoint file.

  @compatibility(TF2)
  `tf.compat.v1.train.init_from_checkpoint` is not recommended for restoring
  variable values in TF2.

  To restore checkpoints in TF2, please use
  `tf.keras.Model.load_weights` or `tf.train.Checkpoint.restore`. These APIs use
  use an [object-based method of checkpointing]
  (https://www.tensorflow.org/guide/checkpoint#loading_mechanics), while
  `tf.compat.v1.init_from_checkpoint` relies on a more-fragile variable-name
  based method of checkpointing. There is no object-based equivalent of
  `init_from_checkpoint` in TF2.

  Please re-write your checkpoints immediately using the object-based APIs,
  see [migration guide]
  (https://www.tensorflow.org/guide/migrate#checkpoint_compatibility) for more
  details.

  You can load a name-based checkpoint written by `tf.compat.v1.train.Saver`
  using `tf.train.Checkpoint.restore` or `tf.keras.Model.load_weights`. However,
  you may have to change the names of the variables in your model to match the
  variable names in the name-based checkpoint, which can be viewed with
  `tf.train.list_variables(path)`.

  Another option is to create an `assignment_map` that maps the name of the
  variables in the name-based checkpoint to the variables in your model, eg:
  ```
  {
      'sequential/dense/bias': model.variables[0],
      'sequential/dense/kernel': model.variables[1]
  }
  ```
  and use `tf.compat.v1.train.init_from_checkpoint(path, assignment_map)` to
  restore the name-based checkpoint.

  After restoring, re-encode your checkpoint using `tf.train.Checkpoint.save`
  or `tf.keras.Model.save_weights`.

  @end_compatibility

  Values are not loaded immediately, but when the initializer is run
  (typically by running a `tf.compat.v1.global_variables_initializer` op).

  Note: This overrides default initialization ops of specified variables and
  redefines dtype.

  Assignment map supports following syntax:

  * `'checkpoint_scope_name/': 'scope_name/'` - will load all variables in
    current `scope_name` from `checkpoint_scope_name` with matching tensor
    names.
  * `'checkpoint_scope_name/some_other_variable': 'scope_name/variable_name'` -
    will initialize `scope_name/variable_name` variable
    from `checkpoint_scope_name/some_other_variable`.
  * `'scope_variable_name': variable` - will initialize given `tf.Variable`
    object with tensor 'scope_variable_name' from the checkpoint.
  * `'scope_variable_name': list(variable)` - will initialize list of
    partitioned variables with tensor 'scope_variable_name' from the checkpoint.
  * `'/': 'scope_name/'` - will load all variables in current `scope_name` from
    checkpoint's root (e.g. no scope).

  Supports loading into partitioned variables, which are represented as
  `'<variable>/part_<part #>'`.

  Assignment map can be a dict, or a list of pairs.  The latter is
  necessary to initialize multiple variables in the current graph from
  the same variable in the checkpoint.

  Example:

  ```python

  # Say, '/tmp/model.ckpt' has the following tensors:
  #  -- name='old_scope_1/var1', shape=[20, 2]
  #  -- name='old_scope_1/var2', shape=[50, 4]
  #  -- name='old_scope_2/var3', shape=[100, 100]

  # Create new model's variables
  with tf.compat.v1.variable_scope('new_scope_1'):
    var1 = tf.compat.v1.get_variable('var1', shape=[20, 2],
                           initializer=tf.compat.v1.zeros_initializer())
  with tf.compat.v1.variable_scope('new_scope_2'):
    var2 = tf.compat.v1.get_variable('var2', shape=[50, 4],
                           initializer=tf.compat.v1.zeros_initializer())
    # Partition into 5 variables along the first axis.
    var3 = tf.compat.v1.get_variable(name='var3', shape=[100, 100],
                           initializer=tf.compat.v1.zeros_initializer(),
                           partitioner=lambda shape, dtype: [5, 1])

  # Initialize all variables in `new_scope_1` from `old_scope_1`.
  init_from_checkpoint('/tmp/model.ckpt', {'old_scope_1/': 'new_scope_1/'})

  # Use names to specify which variables to initialize from checkpoint.
  init_from_checkpoint('/tmp/model.ckpt',
                       {'old_scope_1/var1': 'new_scope_1/var1',
                        'old_scope_1/var2': 'new_scope_2/var2'})

  # Or use tf.Variable objects to identify what to initialize.
  init_from_checkpoint('/tmp/model.ckpt',
                       {'old_scope_1/var1': var1,
                        'old_scope_1/var2': var2})

  # Initialize partitioned variables using variable's name
  init_from_checkpoint('/tmp/model.ckpt',
                       {'old_scope_2/var3': 'new_scope_2/var3'})

  # Or specify the list of tf.Variable objects.
  init_from_checkpoint('/tmp/model.ckpt',
                       {'old_scope_2/var3': var3._get_variable_list()})

  ```

  Args:
    ckpt_dir_or_file: Directory with checkpoints file or path to checkpoint.
    assignment_map: Dict, or a list of key-value pairs, where keys are names
      of the variables in the checkpoint and values are current variables or
      names of current variables (in default graph).

  Raises:
    ValueError: If missing variables in current graph, or if missing
      checkpoints or tensors in checkpoints.

  c                     t              S N)_init_from_checkpoint)_assignment_mapr   s    r   <lambda>z&init_from_checkpoint.<locals>.<lambda>v  s    &;'( r   N)r   get_cross_replica_contextget_replica_context
merge_call)r   rD   init_from_checkpoint_fns   `` r   r   r      s:    |(--/D!&&(33!r   c                    t        |       }t        |       }|j                         }t        |t        j
                        r|j                         }d }t        ||      D ]  \  }}d}t        |      s"t        |t              rt        d |D              r|}n>t        j                         j                  }	|	j                  |d      }|t        ||	      }|||vrt!        d|d| d|      t        |      rt|j#                         j%                  ||         sEt!        d|j&                  d	t)        |j#                               d
|d	t)        ||         d	      |j&                  }
ndj+                  d |D              }
t-        |||       t/        j0                  d|
| |       Od}d|v r|d|j3                  d       }|j5                  d      st!        dj7                  ||            t9               }	D ]B  }
|r|
j;                  |dz         sd|
v r|
d|
j=                  d       }
|j?                  |
       D t        |      D ]  }
|
tA        |      d }|dk7  r|dd }|dk7  r||z   }|j5                  d      r|dd }||vr't!        d|d	|
tA        |      dz   d d|d| d	      |	j                  |
d      }|t        |
|	      }t-        |||       t/        j0                  d|
| |         y)z-See `init_from_checkpoint` for documentation.c                     | d   S )Nr    )pairs    r   rE   z'_init_from_checkpoint.<locals>.<lambda>  s
    $q' r   )keyNc              3   2   K   | ]  }t        |        y wrA   )_is_variable.0vs     r   	<genexpr>z(_init_from_checkpoint.<locals>.<genexpr>  s     =AQ=s   zTensor z is not found in z checkpoint zShape of variable z (z%) doesn't match with shape of tensor z) from checkpoint reader.,c              3   4   K   | ]  }|j                     y wrA   r!   rQ   s     r   rT   z(_init_from_checkpoint.<locals>.<genexpr>  s     0qAFF0s   z1Initialize variable %s from checkpoint %s with %s /zgAssignment map with scope only name {} should map to scope only {}. Should be 'scope/': 'other_scope/'.z/part_   z in z) is not found in z checkpoint)!r   r   r$   
isinstancer   Mappingitemsr%   rP   listallvs_get_default_variable_store_varsget_collect_partitioned_variabler   	get_shapeis_compatible_withr!   strjoin!_set_variable_or_list_initializerr,   debugrindexr   formatset
startswithindexaddlen)r   rD   	ckpt_filer"   r(   sort_keytensor_name_in_ckptcurrent_var_or_namevar
store_varsvar_namescopesscope_variablesfull_tensor_names                 r   rB   rB     s=   &'78)+,&113,,#))+N "(28(3$ OD..
C '(&-=)<==c11399jNN.5c	+,?L
	L	0!1<
  	 
c	}}11,-/ ((C0%s<8K+L'M  88880C00'Y8KLmmG.0CE f	#	#$%E&9&@&@&EF ))#.66<f+7-. 	. o  ((,,Vc\:! 9!9:H


h
'( _- D( $CKL1#%-ab1
#%03CC
$$S)-cr2
</"HS[1_-=$>%'7 
 nnXt,;-h
C#)#y:JKI 02B	D+DsODr   c                     t        | t        j                        rt        j                  |       } t	        j
                  |       rt        j                  |       S | S )zHReturns checkpoint filename given directory or specific checkpoint file.)r\   osPathLikefspathr   IsDirectoryr   r/   )r   s    r   r   r     sH     "++.yy!12
'( 223CDD	r   c           	         | j                   j                  }t        j                  | j                        5  t        j                  d      5  t	        j
                  ||g|g|g|      d   }t        j                  | g      }g }|j                         D ]1  \  }}	t        j                  |	|      D ]  }
|j                  |
        3 t        |      dk(  sJ 	 ddd       ddd       d   j                  gd      }|| _        |j                  | j                         || _        y# 1 sw Y   RxY w# 1 sw Y   VxY w)a  Overrides given variable's initialization op.

  Sets variable initializer to assign op that initializes variable from tensor's
  value in the checkpoint.

  Args:
    variable: `tf.Variable` object.
    ckpt_file: string, full path of the checkpoint.
    tensor_name: Name of the tensor to load from the checkpoint.
    slice_spec: Slice specification for loading partitioned tensors.
    name: Name of the operation.
  z/cpu:0rW   r   rZ   N)restored_shapes)dtype
base_dtyper   devicer   
restore_v2r   op_list_to_dictr^   saveable_objects_for_opr'   rr   restore_initializer_op	set_shapeshape_initial_value)variablers   tensor_name
slice_specr!   	base_type
restore_opnames_to_saveablessaveable_objectsopsinit_ops               r   _set_checkpoint_initializerr     s>   " nn'')
 zz(//" 
&CJJx$8 
&""K=:,$HHIKJ .==xjI&,,. #b#;;BE #!"##  A%%%
& 
& Q''d'K' %(x~~&&(!
& 
& 
& 
&s$   D7BD+D7+D4	0D77E c                    t        | t        t        f      rgd}| D ]_  }|j                  }||j                  }n*||j                  k7  rt        d|d|j                        t        ||||j                         a yt        | ||d       y)a  Overrides initialization op of given variable or list of variables.

  Calls `_set_checkpoint_initializer` for each variable in the given list of
  variables.

  Args:
    variable_or_list: `tf.Variable` object or a list of `tf.Variable` objects.
    ckpt_file: string, full path of the checkpoint.
    tensor_name: Name of the tensor to load from the checkpoint.

  Raises:
    ValueError: if all objects in `variable_or_list` are not partitions of the
      same large variable.
  Nz)Slices must all be from the same tensor: z != rX   )r\   r_   tuple_save_slice_info	full_namer   r   spec)variable_or_listrs   r   
slice_namerS   
slice_infos         r   rj   rj     s       4-0J N%%j		))
---$j&:&:< = 	=!!YZ__MN   0)["Mr   c                 d    t        | t        j                        xs t        j                  |       S rA   )r\   r
   Variabler   is_resource_variable)xs    r   rP   rP   .  s*    
Q	**
+ 8

4
4Q
79r   c                     | dz   |v r:g }d}| d|z  z   |v r*|j                  || d|z  z             |dz  }| d|z  z   |v r*|S y)zEReturns list of `tf.Variable` that comprise the partitioned variable.z/part_0r   z/part_%drZ   N)r'   )r!   all_varsrw   is       r   re   re   3  sj    	I!
C	A
a
8
+	jj$a/011fa a
8
+ J	r   )NrZ   N)r   NN)checkpoint_initializer)(__doc__collectionsr   r~   r.   tensorflow.python.checkpointr   tensorflow.python.distributer   tensorflow.python.frameworkr   tensorflow.python.opsr   r   r	   ra   r
   tensorflow.python.platformr   r   r,   tensorflow.python.trainingr   !tensorflow.python.training.savingr    tensorflow.python.util.tf_exportr   __all__r   r   r   r7   r   r   rB   r   r   rj   rP   re   rL   r   r   <module>r      s    	  > 7 + ( 7 6 + , < ; B 6 "#!< $!<H  !! "!B !" #B -1-.$(> '(+,!%$(?$ )?$D +,-C! .C!LZDz &>	&'TN>9
	r   