
    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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) ddl*m+Z+ ddl*m,Z, ddl-m.Z. ddl-m/Z/ ddl0m1Z1 ddl2m3Z3 ejh                  Z4ejj                  Z5ejl                  Z6ejn                  Z7ejp                  Z8ejr                  Z9ejt                  Z:da; ejx                         Z=dZ>d Z?d  Z@ G d! d"      ZA G d# d$eA      ZBd% ZC e3d&g'       G d( d)             ZD e3d*g'      	 	 d4d+       ZE	 	 	 d5d,ZFd- ZG e3d.g'      	 	 	 	 	 	 	 	 	 	 	 	 d6d/       ZHd0 ZI ej                  ej                  j                  ej                  eDj                  eDj                  1       d2 ZP	 	 	 	 d7d3ZQy)8zSave and restore variables.

Symbols in this file are deprecated. See replacements in
tensorflow/python/training/trackable and tensorflow/python/training/saving.
    N)meta_graph_pb2)	saver_pb2)trackable_object_graph_pb2)checkpoint_management)session)context)constant_op)device)errors)
meta_graph)ops)	array_ops)control_flow_ops)
gen_io_ops)io_ops)
string_ops)	variables)gfile)
tf_logging)metrics)base)py_checkpoint_reader)training_util)saveable_object)saveable_object_util)compat)	tf_exportsaver_v1c                 0    || k  ryt        || z
  dz        S )Nr   i@B )round)start_time_secondsend_time_secondss     P/home/dcms/DCMS/lib/python3.12/site-packages/tensorflow/python/training/saver.py_get_duration_microsecondsr$   L   s%    **	 #55@	AA    c                     d}t        j                   dj                  |             }|D ]  }|t        j                  |      z  } |S )z2Calculates filesize of checkpoint based on prefix.r   z{}*)globformatr   CalculateFileSize)prefixsizefilesfiles       r#   _get_checkpoint_sizer.   S   sI    	
$
))ELL(
)% ,dG%%d++D, 
+r%   c                      e Zd ZdZej
                  Zej                  Zej                  Z	ej                  Z
ej                  j                  fdZd Zd Zd Zd Zd Zd Zd	 Z	 	 dd
Zd Zd Z	 	 	 	 	 	 	 ddZ	 	 	 	 	 	 	 	 	 ddZy)BaseSaverBuilderzEBase class for Savers.

  Can be extended to create different Ops.
  c                     || _         y N)_write_version)selfwrite_versions     r#   __init__zBaseSaverBuilder.__init__k   s
    'Dr%   c                    g }g }g }|D ]d  }|j                   D ]S  }|j                  |j                         |j                  |j                         |j                  |j                         U f | j
                  t        j                  j                  k(  rt        j                  ||||      S | j
                  t        j                  j                  k(  rt        j                  ||||      S t        d| j
                  z         )a  Create an Op to save 'saveables'.

    This is intended to be overridden by subclasses that want to generate
    different Ops.

    Args:
      filename_tensor: String Tensor.
      saveables: A list of BaseSaverBuilder.SaveableObject objects.

    Returns:
      An Operation that save the variables.

    Raises:
      RuntimeError: (implementation detail) if "self._write_version" is an
        unexpected value.
    )filenametensor_namestensorstensor_sliceszUnexpected write_version: )specsappendnametensor
slice_specr3   r   SaverDefV1r   _saveV2save_v2RuntimeError)r4   filename_tensor	saveablesr9   r:   r;   saveablespecs           r#   save_opzBaseSaverBuilder.save_opn   s    $ LGM ... .$DII&t{{#T__-..
 i00333\\"#%	' '
 
			 2 2 5 5	5 ^^O\=#% % 58K8KKLLr%   c           	         ~g }|D ]p  }|j                   r t        j                  |j                         }nd}t        j                   |      5  |j	                  | j                  |||             ddd       r |S # 1 sw Y   ~xY w)a<  Restore all tensors contained in saveables.

    By default, this issues separate calls to `restore_op` for each saveable.
    Subclasses may override to load multiple saveables in a single call.

    Args:
      filename_tensor: String Tensor.
      saveables: List of BaseSaverBuilder.SaveableObject objects.
      preferred_shard: Int.  Shard to open first when loading a sharded file.
      restore_sequentially: Unused.  Bool.  If true, each restore is sequential.

    Returns:
      A list of Tensors resulting from reading 'saveable' from
        'filename'.

    N)r
   r   set_cpu0r   extend
restore_op)r4   rG   rH   preferred_shardrestore_sequentiallyall_tensorsrI   r
   s           r#   bulk_restorezBaseSaverBuilder.bulk_restore   s    $ 	K I	%..x?::f IOOOXG	II II I Is   #A;;B	c           	          g }|j                   D ]M  }|j                  t        j                  ||j                  g|j
                  g|j                  g      d          O |S )a  Create ops to restore 'saveable'.

    This is intended to be overridden by subclasses that want to generate
    different Ops.

    Args:
      filename_tensor: String Tensor.
      saveable: A BaseSaverBuilder.SaveableObject object.
      preferred_shard: Int.  Shard to open first when loading a sharded file.

    Returns:
      A list of Tensors resulting from reading 'saveable' from
        'filename'.
    r   )r<   r=   r   
restore_v2r>   r@   dtype)r4   rG   rI   rP   r:   rJ   s         r#   rO   zBaseSaverBuilder.restore_op   sa      G .nn


Odii[4??:K!ZZL**+-..
 Nr%   c                 0    t        j                  |||      S )zAppend sharding information to a filename.

    Args:
      filename_tensor: A string tensor.
      shard: Integer.  The shard for the filename.
      num_shards: An int Tensor for the number of shards.

    Returns:
      A string tensor.
    )r   sharded_filename)r4   rG   shard
num_shardss       r#   rX   z!BaseSaverBuilder.sharded_filename   s     &&zJJr%   c                 T    | j                  ||      }t        j                  |g|      S )zAdd ops to save variables that are on the same shard.

    Args:
      filename_tensor: String Tensor.
      saveables: A list of SaveableObject objects.

    Returns:
      A tensor with the filename used to save.
    )rK   r   with_dependencies)r4   rG   rH   saves       r#   _AddSaveOpszBaseSaverBuilder._AddSaveOps   s)     <<3D--tfoFFr%   c           
         t        j                  d      5  t        j                  t	        j
                  |d      t        j                  d      t        j                  t        j                  j                  d                  }t	        j                  ||g      }ddd       t        |      }g }g }t        j                  |d      }d}	t        |      D ]  \  }
\  }}|}	t        j                  t        j                  |            5  | j!                  |
|      }|j#                  |       |j#                  | j%                  ||             ddd        t        j&                  |D cg c]  }|j(                   c}      5  t        j                  t        j                  |	            5  t+        j,                  ||d	      }t        j&                  |g      5  t        j.                  |      cddd       cddd       cddd       S # 1 sw Y   vxY w# 1 sw Y   PxY wc c}w # 1 sw Y   nxY w	 ddd       n# 1 sw Y   nxY wddd       y# 1 sw Y   yxY w)
a  Add ops to save the params per shard, for the V2 format.

    Note that the sharded save procedure for the V2 format is different from
    V1: there is a special "merge" step that merges the small metadata produced
    from each device.

    Args:
      checkpoint_prefix: scalar String Tensor.  Interpreted *NOT AS A FILENAME*,
        but as a prefix of a V2 checkpoint;
      per_device: A list of (device, BaseSaverBuilder.VarToSave) pairs, as
        returned by _GroupByDevices().

    Returns:
      An op to save the variables, which, when evaluated, returns the prefix
        "<user-fed prefix>" only and does not include the sharded spec suffix.
    CPUz^s3://.*z.partz
_temp/partNrZ   r>   T)delete_old_dirs)r   r
   r   wherer   regex_full_matchr	   constantospathnormpathstring_joinlen	enumerater   rM   rX   r=   r^   control_dependenciesopr   merge_v2_checkpointsidentity)r4   checkpoint_prefix
per_device_SHARDED_SUFFIXtmp_checkpoint_prefixrZ   sharded_savessharded_prefixesnum_shards_tensorlast_devicerY   r
   rH   rX   x
merge_steps                   r#   _AddShardedSaveOpsForV2z(BaseSaverBuilder._AddShardedSaveOpsForV2   s0   \ 
E	 0!

%
%&7
D


w
'


rww//=
>@o )44o
.00 ZJM#,,ZlKK&/
&; L""	k::*33F;< L001F1BD 01T--.>	JK	L LL 
	!	!"?A144"?	@ 
7::*33K@A 7  44/G
%%zl3 	7 ##$56	7 	77 7
7 
7+0 0L L #@	7 	7 	77 7 7
7 
7 
7sa   BH
AH-H*)I0/IH/4	I=	IHH'	/H84I<	II	
II#c                 `   | j                   t        j                  j                  k(  r| j	                  ||      S t        |      }g }t        j                  |d      }t        |      D ]Z  \  }\  }}t        j                  |      5  | j                  |||      }	|j                  | j                  |	|             ddd       \ t        j                  |D 
cg c]  }
|
j                   c}
      5  t!        j"                  ||      cddd       S # 1 sw Y   xY wc c}
w # 1 sw Y   yxY w)a  Add ops to save the params per shard.

    Args:
      filename_tensor: a scalar String Tensor.
      per_device: A list of (device, BaseSaverBuilder.SaveableObject) pairs, as
        returned by _GroupByDevices().

    Returns:
      An op to save the variables.
    rZ   ra   N)r3   r   rA   rD   rz   rj   r	   re   rk   r   r
   rX   r=   r^   rl   rm   r   sharded_filespec)r4   rG   rq   rZ   rt   rv   rY   r
   rH   rX   rx   s              r#   _AddShardedSaveOpsz#BaseSaverBuilder._AddShardedSaveOps8  s&    i00333))/:FFZJM#,,ZlK&/
&; L""	::f L00%1BDT--.>	JKL LL 
	!	!"?A144"?	@ M((:KLM ML L
 #@ M Ms   5DD3D$D	$D-c                    | j                  ||||      }g }d}	|D ]  }
d}|reg }|
j                  D ]T  }|j                  }|j                         }|j	                         st        j                  |      }|j                  |       V ||	|	t        |
j                        z    }|	t        |
j                        z  }	|j                  |
j                  ||              t        j                  |d|iS )a&  Add operations to restore saveables.

    Args:
      filename_tensor: Tensor for the path of the file to load.
      saveables: A list of SaveableObject objects.
      restore_sequentially: True if we want to restore variables sequentially
        within a shard.
      reshape: True if we want to reshape loaded tensors to the shape of the
        corresponding variable.
      preferred_shard: Shard to open first when loading a sharded file.
      name: Name for the returned op.

    Returns:
      An Operation that restores the variables.
    r   Nr>   )rS   r<   r?   	get_shapeis_fully_definedr   shaper=   rj   restorer   group)r4   rG   rH   rQ   reshaperP   r>   rR   
assign_opsidxrI   shapesrJ   vr   saveable_tensorss                   r#   _AddRestoreOpszBaseSaverBuilder._AddRestoreOpsR  s    , ##OY$8:K J
C
  Df	 NN 	Dkk!++-%'')OOA&E
--
	 %Ss8>>/B)BC	S  c(()96BCD" !!:9D99r%   c                     g }t        |      D ]L  \  }\  }}t        j                  |      5  |j                  | j	                  |||||d             ddd       N t        j                  |ddiS # 1 sw Y   mxY w)a  Add Ops to restore variables from multiple devices.

    Args:
      filename_tensor: Tensor for the path of the file to load.
      per_device: A list of (device, SaveableObject) pairs, as returned by
        _GroupByDevices().
      restore_sequentially: True if we want to restore variables sequentially
        within a shard.
      reshape: True if we want to reshape loaded tensors to the shape of the
        corresponding variable.

    Returns:
      An Operation that restores the variables.
    restore_shard)rP   r>   Nr>   restore_all)rk   r   r
   r=   r   r   r   )	r4   rG   rq   rQ   r   sharded_restoresrY   r
   rH   s	            r#   _AddShardedRestoreOpsz&BaseSaverBuilder._AddShardedRestoreOps  s      &/
&; 	'""	::f '$ %$   &	'' '	' !!#3H-HH' 's   'A22A;	c                 <   t        j                  d       }|D ]f  }t        d |j                  D              }t	        |      dk7  rt        d|j                  z        ||j                            j                  |       h t        |j                         d       S )a)  Group Variable tensor slices per device.

    TODO(touts): Make sure that all the devices found are on different
    job/replica/task/cpu|gpu.  It would be bad if 2 were on the same device.
    It can happen if the devices are unspecified.

    Args:
      saveables: A list of BaseSaverBuilder.SaveableObject objects.

    Returns:
      A list of tuples: (device_name, BaseSaverBuilder.SaveableObject) tuples.
      The list is sorted by ascending device_name.

    Raises:
      ValueError: If the tensors of a saveable are on different devices.
    c                      g S r2    r   r%   r#   <lambda>z2BaseSaverBuilder._GroupByDevices.<locals>.<lambda>  s     r%   c              3   Z   K   | ]#  }t        j                  |j                         % y wr2   )pydevcanonical_namer
   ).0rJ   s     r#   	<genexpr>z3BaseSaverBuilder._GroupByDevices.<locals>.<genexpr>  s&      H04%

t{{
+Hs   )+   z?All tensors of a saveable object must be on the same device: %sc                     | d   S )Nr   r   )ts    r#   r   z2BaseSaverBuilder._GroupByDevices.<locals>.<lambda>  s
    AaD r%   )key)collectionsdefaultdictsetr<   rj   
ValueErrorr>   popr=   sorteditems)r4   rH   rq   rI   canonical_devices        r#   _GroupByDevicesz BaseSaverBuilder._GroupByDevices  s    " ((4J : H8@H H		!	# 24<MMB C 	C!%%'(//9: *""$.99r%   Nc	           
      4    | j                  ||||||||      S )a  Builds save/restore graph nodes or runs save/restore in eager mode.

    Args:
      names_to_saveables: A dictionary mapping name to a Variable or
        SaveableObject. Each name will be associated with the corresponding
        variable in the checkpoint.
      reshape: If True, allow restoring parameters from a checkpoint that where
        the parameters have a different shape.  This is only needed when you try
        to restore from a Dist-Belief checkpoint, and only some times.
      sharded: If True, shard the checkpoints, one per device that has Variable
        nodes.
      max_to_keep: Maximum number of checkpoints to keep.  As new checkpoints
        are created, old ones are deleted.  If None or 0, no checkpoints are
        deleted from the filesystem but only the last one is kept in the
        `checkpoint` file.  Presently the number is only roughly enforced.  For
        example in case of restarts more than max_to_keep checkpoints may be
        kept.
      keep_checkpoint_every_n_hours: How often checkpoints should be kept.
        Defaults to 10,000 hours.
      name: String.  Optional name to use as a prefix when adding operations.
      restore_sequentially: A Bool, which if true, causes restore of different
        variables to happen sequentially within each device.
      filename: If known at graph construction time, filename used for variable
        loading/saving. If None, then the default name "model" will be used.

    Returns:
      A SaverDef proto.

    Raises:
      TypeError: If 'names_to_saveables' is not a dictionary mapping string
        keys to variable Tensors.
      ValueError: If any of the keys or values in 'names_to_saveables' is not
        unique.
    )names_to_saveablesr   shardedmax_to_keepkeep_checkpoint_every_n_hoursr>   rQ   r8   )_build_internal)	r4   r   r   r   r   r   r>   rQ   r8   s	            r#   buildzBaseSaverBuilder.build  s5    V -&C1    r%   c           	         t        j                         s|	r|
st        d      t        |t              st        j                  |      }t        j                  |      }|d}t        j                  |d|D cg c]  }|j                   c}      5 }t        j                  |xs ddd      }t        j                  |dd	      }|r<| j                  |      }|	r| j                  ||      }|
r?| j                  ||||      }n*|	r| j!                  ||      }|
r| j#                  ||||      }ddd       t        j                         rH|	rj%                         nd
}t'        j(                  j%                         |d
|||| j*                        S t        j,                         }|j/                         }|D ]O  }|j1                  |      D ]9  }t        |t2        j4                        s	 |j7                  |j8                         ; Q t'        j(                  j8                  j8                  j8                  |||| j*                        S c c}w # 1 sw Y   'xY w# t:        $ r |j=                          Y w xY w)z5build() with option to only perform save and restore.z[save and restore operations need to be built together  when eager execution is not enabled.Nr   r]   modelr   r8   )r   r>   Const )filename_tensor_namesave_tensor_namerestore_op_namer   r   r   version)r   executing_eagerlyr   
isinstancedictr   op_list_to_dictvalidate_and_slice_inputsr   
name_scoperm   r   placeholder_with_defaultr   r}   r   r^   r   numpyr   rA   r3   get_default_graphget_all_collection_keysget_collectionr   PartitionedVariableget_operation_by_namer>   KeyError	as_tensor)r4   r   r   r   r   r   r>   rQ   r8   
build_savebuild_restorerH   rI   rG   rq   save_tensorrO   r   graphcheck_collection_listcollection_typeelements                         r#   r   z BaseSaverBuilder._build_internal  s    $$&
0= ? @ @ ($//??
$>>Ik	f5>??
A JDH!::

gRj:o "::
'3o 
)))4
//L+11/:2FQ* (()D+**?I+?J*+JF   "0:**,.446+!(E%%' ' ##%e
 $;;=2 	"/++O< 	"G!>!>?"))',,7	"	" .33&++$//!(E%%' '} @J Jt  " !	"s%   7IBI+I I I<;I<)r   )FF        @NFr   )	FFr   r   NFr   TT)__name__
__module____qualname____doc__r   SaveSpecSaveableObjectr   ReferenceVariableSaveableVariableSaveableResourceVariableSaveabler   rA   rD   r6   rK   rS   rO   rX   r^   rz   r}   r   r   r   r   r   r   r%   r#   r0   r0   ^   s    
 %%("11. *CC1JJ#,#5#5#8#8 (&MP>4KGM7^M> &('0:dI::: *1!&3n $#"#4;+0&!%$(_'r%   r0   c                       e Zd ZdZd Zy)BulkSaverBuilderz@SaverBuilder with support for bulk restoring multiple saveables.c                 :   ~g }|D ]E  }|j                   D ]4  }|j                  |j                  |j                  |j                  f       6 G t        | \  }}	}
t        j                  d      5  t        j                  |||	|
      cd d d        S # 1 sw Y   y xY w)Nzcpu:0)
r<   r=   r>   r@   rV   zipr   r
   r   rU   )r4   rG   rH   rP   rQ   restore_specsrI   rJ   namesslicesdtypess              r#   rS   zBulkSaverBuilder.bulk_restoreV  s     	M G.. G$dii$**EFGG  /E66	G	 GvvFG G Gs   /BBN)r   r   r   r   rS   r   r%   r#   r   r   S  s    HGr%   r   c                     t         j                  j                  } t        j                  |       }|r-t	        |      dkD  rt        dj                  |             |d   S t        dd      }|t        j                  | |       |S )a&  Returns the saver from SAVERS collection, or creates a default one.

  This method is used by other members of the training module, such as
  `Scaffold`, or `CheckpointSaverHook`.

  Returns:
    `Saver`.

  Raises:
    RuntimeError: If the SAVERS collection already has more than one items.
  r   zgMore than one item in collection {}. Please indicate which one to use by passing it to the constructor.r   T)r   allow_empty)	r   	GraphKeysSAVERSr   rj   rF   r(   Saveradd_to_collection)collection_keysaverssavers      r#   _get_saver_or_defaultr   f  s     ==''.n-&
6{QO6.!# # !9
$
/%
.%0	,r%   ztrain.Saver)v1c                      e Zd ZdZdddddddddddej
                  j                  dddfdZd Zd Z	d	 Z
d
 Zd Zd ZddZd ZddZedd       Zed        Zd Zd Zd Z	 	 	 	 	 	 	 ddZ	 	 	 	 	 	 	 	 ddZd Zedd       Zy)r   a  Saves and restores variables.

  @compatibility(TF2)
  `tf.compat.v1.train.Saver` is not supported for saving and restoring
  checkpoints in TF2. Please switch to `tf.train.Checkpoint` or
  `tf.keras.Model.save_weights`, which perform a more robust [object-based
  saving](https://www.tensorflow.org/guide/checkpoint#loading_mechanics).

  ### How to Rewrite Checkpoints

  Please rewrite your checkpoints immediately using the object-based checkpoint
  APIs.

  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`.

  See the [Checkpoint compatibility](
  https://www.tensorflow.org/guide/migrate#checkpoint_compatibility)
  section of the migration guide for more details.


  ### Checkpoint Management in TF2

  Use `tf.train.CheckpointManager` to manage checkpoints in TF2.
  `tf.train.CheckpointManager` offers equivalent `keep_checkpoint_every_n_hours`
  and `max_to_keep` parameters.

  To recover the latest checkpoint,

  ```
  checkpoint = tf.train.Checkpoint(model)
  manager = tf.train.CheckpointManager(checkpoint)
  status = checkpoint.restore(manager.latest_checkpoint)
  ```

  `tf.train.CheckpointManager` also writes a [`CheckpointState` proto]
  (https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/training/checkpoint_state.proto)
  which contains the timestamp when each checkpoint was created.

  ### Writing `MetaGraphDef`s in TF2

  To replace, `tf.compat.v1.train.Saver.save(write_meta_graph=True)`, use
  `tf.saved_model.save` to write the `MetaGraphDef` (which is contained in
  `saved_model.pb`).

  @end_compatibility

  See [Variables](https://tensorflow.org/guide/variables)
  for an overview of variables, saving and restoring.

  The `Saver` class adds ops to save and restore variables to and from
  *checkpoints*.  It also provides convenience methods to run these ops.

  Checkpoints are binary files in a proprietary format which map variable names
  to tensor values.  The best way to examine the contents of a checkpoint is to
  load it using a `Saver`.

  Savers can automatically number checkpoint filenames with a provided counter.
  This lets you keep multiple checkpoints at different steps while training a
  model.  For example you can number the checkpoint filenames with the training
  step number.  To avoid filling up disks, savers manage checkpoint files
  automatically. For example, they can keep only the N most recent files, or
  one checkpoint for every N hours of training.

  You number checkpoint filenames by passing a value to the optional
  `global_step` argument to `save()`:

  ```python
  saver.save(sess, 'my-model', global_step=0) ==> filename: 'my-model-0'
  ...
  saver.save(sess, 'my-model', global_step=1000) ==> filename: 'my-model-1000'
  ```

  Additionally, optional arguments to the `Saver()` constructor let you control
  the proliferation of checkpoint files on disk:

  * `max_to_keep` indicates the maximum number of recent checkpoint files to
    keep.  As new files are created, older files are deleted.   If None or 0,
    no checkpoints are deleted from the filesystem but only the last one is
    kept in the `checkpoint` file.  Defaults to 5 (that is, the 5 most recent
    checkpoint files are kept.)

  * `keep_checkpoint_every_n_hours`: In addition to keeping the most recent
    `max_to_keep` checkpoint files, you might want to keep one checkpoint file
    for every N hours of training.  This can be useful if you want to later
    analyze how a model progressed during a long training session.  For
    example, passing `keep_checkpoint_every_n_hours=2` ensures that you keep
    one checkpoint file for every 2 hours of training.  The default value of
    10,000 hours effectively disables the feature.

  Note that you still have to call the `save()` method to save the model.
  Passing these arguments to the constructor will not save variables
  automatically for you.

  A training program that saves regularly looks like:

  ```python
  ...
  # Create a saver.
  saver = tf.compat.v1.train.Saver(...variables...)
  # Launch the graph and train, saving the model every 1,000 steps.
  sess = tf.compat.v1.Session()
  for step in range(1000000):
      sess.run(..training_op..)
      if step % 1000 == 0:
          # Append the step number to the checkpoint name:
          saver.save(sess, 'my-model', global_step=step)
  ```

  In addition to checkpoint files, savers keep a protocol buffer on disk with
  the list of recent checkpoints. This is used to manage numbered checkpoint
  files and by `latest_checkpoint()`, which makes it easy to discover the path
  to the most recent checkpoint. That protocol buffer is stored in a file named
  'checkpoint' next to the checkpoint files.

  If you create several savers, you can specify a different filename for the
  protocol buffer file in the call to `save()`.
  NFr   r   c                    t         5  t        t        j                         addd       |
r|rt        d      t	        j
                         r"t        j                  d       |t        d      || _	        || _
        || _        || _        || _        || _        || _        || _        |	| _        d| _        || _        d| _        || _        || _        || _        g | _        g | _        t	        j
                         r*t        j                         | j                  dz  z   | _        n|
s| j7                          | j                   r+| j9                          | j                   j:                  | _        || _        d| _        y# 1 sw Y   \xY w)az  Creates a `Saver`.

    The constructor adds ops to save and restore variables.

    `var_list` specifies the variables that will be saved and restored. It can
    be passed as a `dict` or a list:

    * A `dict` of names to variables: The keys are the names that will be
      used to save or restore the variables in the checkpoint files.
    * A list of variables: The variables will be keyed with their op name in
      the checkpoint files.

    For example:

    ```python
    v1 = tf.Variable(..., name='v1')
    v2 = tf.Variable(..., name='v2')

    # Pass the variables as a dict:
    saver = tf.compat.v1.train.Saver({'v1': v1, 'v2': v2})

    # Or pass them as a list.
    saver = tf.compat.v1.train.Saver([v1, v2])
    # Passing a list is equivalent to passing a dict with the variable op names
    # as keys:
    saver = tf.compat.v1.train.Saver({v.op.name: v for v in [v1, v2]})
    ```

    Note: the newer `AutoTrackable` API is not supported by `Saver`. In this
    case, the `tf.train.Checkpoint` class should be used.

    The optional `reshape` argument, if `True`, allows restoring a variable from
    a save file where the variable had a different shape, but the same number
    of elements and type.  This is useful if you have reshaped a variable and
    want to reload it from an older checkpoint.

    The optional `sharded` argument, if `True`, instructs the saver to shard
    checkpoints per device.

    Args:
      var_list: A list of `Variable`/`SaveableObject`, or a dictionary mapping
        names to `SaveableObject`s. If `None`, defaults to the list of all
        saveable objects.
      reshape: If `True`, allows restoring parameters from a checkpoint where
        the variables have a different shape.
      sharded: If `True`, shard the checkpoints, one per device.
      max_to_keep: Maximum number of recent checkpoints to keep. Defaults to 5.
      keep_checkpoint_every_n_hours: How often to keep checkpoints. Defaults to
        10,000 hours.
      name: String.  Optional name to use as a prefix when adding operations.
      restore_sequentially: A `Bool`, which if true, causes restore of different
        variables to happen sequentially within each device.  This can lower
        memory usage when restoring very large models.
      saver_def: Optional `SaverDef` proto to use instead of running the
        builder. This is only useful for specialty code that wants to recreate a
        `Saver` object for a previously built `Graph` that had a `Saver`. The
        `saver_def` proto should be the one returned by the `as_saver_def()`
        call of the `Saver` that was created for that `Graph`.
      builder: Optional `SaverBuilder` to use if a `saver_def` was not provided.
        Defaults to `BulkSaverBuilder()`.
      defer_build: If `True`, defer adding the save and restore ops to the
        `build()` call. In that case `build()` should be called before
        finalizing the graph or using the saver.
      allow_empty: If `False` (default) raise an error if there are no variables
        in the graph. Otherwise, construct the saver anyway and make it a no-op.
      write_version: controls what format to use when saving checkpoints.  It
        also affects certain filepath matching logic.  The V2 format is the
        recommended choice: it is much more optimized than V1 in terms of memory
        required and latency incurred during restore.  Regardless of this flag,
        the Saver is able to restore from both V2 and V1 checkpoints.
      pad_step_number: if True, pads the global step number in the checkpoint
        filepaths to some fixed width (8 by default).  This is turned off by
        default.
      save_relative_paths: If `True`, will write relative paths to the
        checkpoint state file. This is needed if the user wants to copy the
        checkpoint directory and reload from the copied directory.
      filename: If known at graph construction time, filename used for variable
        loading/saving.

    Raises:
      TypeError: If `var_list` is invalid.
      ValueError: If any of the keys or values in `var_list` are not unique.
      RuntimeError: If eager execution is enabled and`var_list` does not specify
        a list of variables to save.

    @compatibility(eager)
    When eager execution is enabled, `var_list` must specify a `list` or `dict`
    of variables to save. Otherwise, a `RuntimeError` will be raised.

    Although Saver works in some cases when executing eagerly, it is
    fragile. Please switch to `tf.train.Checkpoint` or
    `tf.keras.Model.save_weights`, which perform a more robust object-based
    saving. These APIs will load checkpoints written by `Saver`.
    @end_compatibility
    NzgIf `var_list` is provided then build cannot be deferred. Either set defer_build=False or var_list=None.a   Saver is deprecated, please switch to tf.train.Checkpoint or tf.keras.Model.save_weights for training checkpoints. When executing eagerly variables do not necessarily have unique names, and so the variable.name-based lookups Saver performs are error-prone.z\When eager execution is enabled, `var_list` must specify a list or dict of variables to saveF  ) _END_TIME_OF_LAST_WRITE_LOCK_END_TIME_OF_LAST_WRITEtimer   r   r   loggingwarningrF   	_var_list_reshape_sharded_max_to_keep_keep_checkpoint_every_n_hours_name_restore_sequentially	saver_def_builder	_is_built_allow_empty	_is_emptyr3   _pad_step_number	_filename_last_checkpoints_checkpoints_to_be_deleted_next_checkpoint_timer   _check_saver_defr   _save_relative_paths_object_restore_saver)r4   var_listr   r   r   r   r>   rQ   r   builderdefer_buildr   r5   pad_step_numbersave_relative_pathsr8   s                   r#   r6   zSaver.__init__  ss   ` 
& .	 	("&))+. x;< <   "oo 
	+, 	, DNDMDM#D*GD'DJ!5DDNDMDN#DDN'D+DDND&(D#  "
))+;;dB
B  
jjl~~
 NN22d 3D "&D_. .s   E<<Fc                 ~    t        j                         rt        d      | j                  | j                  dd       y )Nz0Use save/restore instead of build in eager mode.Tr   r   )r   r   rF   _buildr   r4   s    r#   r   zSaver.build  s0      "KLLKK4tKDr%   c                 ,    | j                  |||       y )Nr  )r  r4   checkpoint_pathr   r   s       r#   _build_eagerzSaver._build_eager  s    KKJm  Mr%   c                    t        j                         s| j                  ryd| _        | j                  rt        j                         r| j                  t        | j                        | _        | j                  t        j                         | _        | j                  s| j                  rd| _        yt        d      d| _        | j                  j                  | j                  | j                  | j                  | j                   | j"                  | j$                  | j&                  |||
      | _        n| j                  r| j$                  rt)        j*                  | j                  j,                  | j$                        | j                  _        t)        j*                  | j                  j.                  | j$                        | j                  _        t)        j*                  | j                  j0                  | j$                        | j                  _        | j3                          t        j                         s4t5        j4                         | j                  j6                  dz  z   | _        yy)zBuilds saver_def.NTzNo variables to saveF)	r   r   r   r   r>   rQ   r8   r   r   r   )r   r   r   r   r   r   r3   r   r   _all_saveable_objectsr   r   r   r   r   r   r   r   r   r   r   prepend_name_scoper   r   r   r  r   r   r  r  s       r#   r  zSaver._build  s   $$&	dn>>W668		()<)<=		"88:^^$.
12
2dn}}44
..----''(,(K(Kzz#99"% 5 
'dn 
DJJ -0,B,B
..
-
-tzz-;dnn)(+(>(>
..
)
)4::)7dnn%'*'='=
..
(
($**(6dnn$ 	$$& ))+DDtK
K   'r%   c                    t        | j                  t        j                        st	        d| j                  z        t        j                         so| j                  j                  s!t	        dt        | j                        z        | j                  j                  s!t	        dt        | j                        z        y y )Nz*saver_def must be a saver_pb2.SaverDef: %sz/saver_def must specify the save_tensor_name: %sz.saver_def must specify the restore_op_name: %s)
r   r   r   rA   r   r   r   r   strr   r  s    r#   r  zSaver._check_saver_def  s    dnni&8&89C~~& ' '$$&^^,,JT^^,- . 	.^^++IT^^,- . 	. ,	 'r%   c                     |\  }}|S )zReturns the checkpoint filename given a `(filename, time)` pair.

    Args:
      p: (filename, time) pair.

    Returns:
      Checkpoint file name.
    r   )r4   pr>   _s       r#   _CheckpointFilenamezSaver._CheckpointFilename  s     GD!Kr%   c                    | j                   j                  sy| j                  dd D ]2  }|| j                  |      k(  s| j                  j	                  |       4 | j                  j                  |t        j                         f       t        | j                        | j                   j                  kD  r5| j                  j                  | j                  j                  d             yy)z+Manages the list of the latest checkpoints.Nr   )
r   r   r   r  remover=   r   rj   r  r   )r4   latest_save_pathr  s      r#   _RecordLastCheckpointzSaver._RecordLastCheckpoint  s    >>%%##A& )	T55a8	8%%a()
 	!!#3TYY["AB 4!!"T^^%?%??
%%,,T-C-C-G-G-JK @r%   c                    | j                   r| j                   j                  d      }|d   | j                  kD  }|r-| xj                  | j                  j                  dz  z  c_        y	 t        j                  | j                  |      | j                  j                  |       yy# t        $ r)}t        j                  dt        |             Y d}~yd}~ww xY w)a(  Deletes old checkpoints if necessary.

    `self._checkpoints_to_be_deleted` is going to contain checkpoints that are
    over `max_to_keep`.  They are going to be deleted.  If
    `keep_checkpoint_every_n_hours` was specified, keep an additional checkpoint
    every `N` hours. For example, if `N` is 0.5, an additional checkpoint is
    kept for every 0.5 hours of training; if `N` is 10, an additional
    checkpoint is kept for every 10 hours of training.

    Args:
      meta_graph_suffix: Suffix for `MetaGraphDef` file. Defaults to 'meta'.
    r   r   r   NzIgnoring: %s)r  r   r  r   r   r   remove_checkpointr  r   	Exceptionr   r   r  )r4   meta_graph_suffixr  should_keepes        r#   _MaybeDeleteOldCheckpointsz Saver._MaybeDeleteOldCheckpoints  s     &&

)
)
-
-a
0a aD4555k	""NN884?	A"0//$$Q')?)?	 '  0A//0s   *:B& &	C/CCc                     | j                   S )zaGenerates a `SaverDef` representation of this saver.

    Returns:
      A `SaverDef` proto.
    )r   r  s    r#   as_saver_defzSaver.as_saver_def2  s     >>r%   c                 >   || j                   S | j                   j                  j                  |      rJ| j                   j                  j                  |      r%| j                   j                  j                  |      syt        j                         }|j                  | j                          t        j                  |j                  |      |_        t        j                  |j                  |      |_        t        j                  |j                  |      |_        |S )zConverts this `Saver` to a `SaverDef` protocol buffer.

    Args:
      export_scope: Optional `string`. Name scope to remove.

    Returns:
      A `SaverDef` protocol buffer.
    N)
r   r   
startswithr   r   r   rA   CopyFromr   strip_name_scope)r4   export_scoper   s      r#   to_protozSaver.to_proto:  s     ^^NN//::<HNN++66|DNN**55lC""$It~~&%(%9%9&&&6I"!$!5!5""L"2I # 4 4Y5N5N5A!CIr%   c                     t        | |      S )zReturns a `Saver` object created from `saver_def`.

    Args:
      saver_def: a `SaverDef` protocol buffer.
      import_scope: Optional `string`. Name scope to use.

    Returns:
      A `Saver` built from saver_def.
    r   r>   )r   )r   import_scopes     r#   
from_protozSaver.from_protoU  s     9<88r%   c                 @     t         fd j                  D              S )zList of not-yet-deleted checkpoint filenames.

    You can pass any of the returned values to `restore()`.

    Returns:
      A list of checkpoint filenames, sorted from oldest to newest.
    c              3   @   K   | ]  }j                  |        y wr2   )r  )r   r  r4   s     r#   r   z)Saver.last_checkpoints.<locals>.<genexpr>k  s     L((+Ls   )listr   r  s   `r#   last_checkpointszSaver.last_checkpointsb  s     LT5K5KLLLr%   c                 |    t        |t              sJ |D cg c]  }|t        j                  f c}| _        yc c}w )zDEPRECATED: Use set_last_checkpoints_with_time.

    Sets the list of old checkpoint filenames.

    Args:
      last_checkpoints: A list of checkpoint filenames.

    Raises:
      AssertionError: If last_checkpoints is not a list.
    N)r   r5  npinfr   )r4   r6  ss      r#   set_last_checkpointszSaver.set_last_checkpointsm  s6     &--- 4DDaq"&&kDDDs   9c                 6    t        |t              sJ || _        y)zSets the list of old checkpoint filenames and timestamps.

    Args:
      last_checkpoints_with_time: A list of tuples of checkpoint filenames and
        timestamps.

    Raises:
      AssertionError: If last_checkpoints_with_time is not a list.
    N)r   r5  r   )r4   last_checkpoints_with_times     r#   set_last_checkpoints_with_timez$Saver.set_last_checkpoints_with_time~  s     0$7777Dr%   c                     g }|D ]2  }	 t        j                  |g      }|s|j	                  ||d   f       4 | j                  |       y# t        j                  $ r Y \w xY w)aI  Recovers the internal saver state after a crash.

    This method is useful for recovering the "self._last_checkpoints" state.

    Globs for the checkpoints pointed to by `checkpoint_paths`.  If the files
    exist, use their mtime as the checkpoint timestamp.

    Args:
      checkpoint_paths: a list of checkpoint paths.
    r   N)r   get_checkpoint_mtimesr   NotFoundErrorr=   r>  )r4   checkpoint_pathscheckpoints_with_mtimesr  mtimes        r#   recover_last_checkpointszSaver.recover_last_checkpoints  s|     !+ D%;;_<MN
 
&&q'BCD 	''(?@ !!  	s   AA"!A"c
                 $	   t        j                          }
| j                  st        j                         st	        d      |d}| j
                  t        j                  j                  k7  r~t        j                  d       t        j                  d       t        j                  d       t        j                  d       t        j                  d       t        j                  d       t        j                  j                  |      d	   rt        d
      t        j                   |      }|Zt#        |t        j$                        st'        j(                  ||      }d||fz  }| j*                  rY|ddj-                  |      }nB|}t        j                  j/                  |      |k(  r| j0                  st        d|d|d      t        j                         s(t#        |t2        j4                        st7        d|z        t        j                  j9                  |      }| j:                  s	 t        j                         r+| j=                  |dd       | j>                  j@                  }n<|jC                  | j>                  j@                  | j>                  jD                  |i      }t        j                   |      }|rQ| jG                  |       tI        jJ                  ||| jL                  || jN                         | jQ                  |       t        j                          }t]        j^                  t`        tc        |
|             td        5  t]        jf                  t`        tc        th        |             |a4ddd       |rbtI        jj                  ||      }t        j                         s7|jl                  jo                         5  | jq                  |||	       ddd       | j:                  ryt]        jr                  t`        tu                     |S # tR        jT                  tR        jV                  f$ r6}tY        jZ                  |      st        dj-                  |            }|d}~ww xY w# 1 sw Y   xY w# 1 sw Y   xY w)a$	  Saves variables.

    This method runs the ops added by the constructor for saving variables.
    It requires a session in which the graph was launched.  The variables to
    save must also have been initialized.

    The method returns the path prefix of the newly created checkpoint files.
    This string can be passed directly to a call to `restore()`.

    Args:
      sess: A Session to use to save the variables.
      save_path: String.  Prefix of filenames created for the checkpoint.
      global_step: If provided the global step number is appended to `save_path`
        to create the checkpoint filenames. The optional argument can be a
        `Tensor`, a `Tensor` name or an integer.
      latest_filename: Optional name for the protocol buffer file that will
        contains the list of most recent checkpoints.  That file, kept in the
        same directory as the checkpoint files, is automatically managed by the
        saver to keep track of recent checkpoints.  Defaults to 'checkpoint'.
      meta_graph_suffix: Suffix for `MetaGraphDef` file. Defaults to 'meta'.
      write_meta_graph: `Boolean` indicating whether or not to write the meta
        graph file.
      write_state: `Boolean` indicating whether or not to write the
        `CheckpointStateProto`.
      strip_default_attrs: Boolean. If `True`, default-valued attributes will be
        removed from the NodeDefs. For a detailed guide, see [Stripping
        Default-Valued
        Attributes](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/saved_model/README.md#stripping-default-valued-attributes).
      save_debug_info: If `True`, save the GraphDebugInfo to a separate file,
        which in the same directory of save_path and with `_debug` added before
        the file extension. This is only enabled when `write_meta_graph` is
        `True`

    Returns:
      A string: path prefix used for the checkpoint files.  If the saver is
        sharded, this string ends with: '-?????-of-nnnnn' where 'nnnnn'
        is the number of shards created.
      If the saver is empty, returns None.

    Raises:
      TypeError: If `sess` is not a `Session`.
      ValueError: If `latest_filename` contains path components, or if it
        collides with `save_path`.
      RuntimeError: If save and restore ops weren't built.
    z;`build()` should be called before save if defer_build==TrueN
checkpointz7*******************************************************z6TensorFlow's V1 checkpoint format has been deprecated.z3Consider switching to the more efficient V2 format:z7   `tf.train.Saver(write_version=tf.train.SaverDef.V2)`znow on by default.r   z2'latest_filename' must not contain path componentsz%s-%d-z{:08d}z.'latest_filename' collides with 'save_path': 'z' and ''z'sess' must be a Session; %sTFr  )save_dirmodel_checkpoint_pathall_model_checkpoint_pathslatest_filenamer
  )r#  z1Parent directory of {} doesn't exist, can't save.	api_labelmicroseconds)strip_default_attrssave_debug_info)rO  filesize);r   r   r   r   rF   r3   r   rA   rD   r   r   rf   rg   splitr   r   as_strr   integral_typesr   global_stepr   r(   basenamer   r   SessionInterface	TypeErrordirnamer   r  r   r   runr   r  r    update_checkpoint_state_internalr6  r  r&  r   FailedPreconditionErrorrA  r   IsDirectoryr   AddCheckpointWriteDuration_SAVER_LABELr$   r   AddTrainingTimeSavedr   meta_graph_filenamer   
as_defaultexport_meta_graphRecordCheckpointSizer.   )r4   sess	save_pathrW  rM  r#  write_meta_graphwrite_staterQ  rR  
start_timecheckpoint_filesave_path_parentrK  excend_timerc  s                    r#   r]   z
Saver.save  s   r J>>'";";"=
GI I$oi00333ooOPooNOooKLooOPoo*+ooOP	ww}}_%a(KLLi(IV%:%:;#//kB9k"::o			%.0LM!o			)	$	7i)* 	* %%'tW5564t;<<wwy1>>$$&


$e  E"&.."A"A
"&((nn--~~22OD#F
 !'.C D

$
$%:
;

@
@'$9)-)>)>-"&";";= 
)
)<M
)
N yy{H&&/
HEG 
& )"" 12I2:<= !)) 1EE
->@&&(ZZ""$ 	/

 
 !"5- ! /	/ ~~"" '(=>@ #"G ,,f.B.BC   !12AHH# 	) )	/ 	/s1   1C#P ,Q:R#Q71Q22Q7:RRc	                     t        |t        j                         j                  dd      | j                  |||||||
      S )a  Writes `MetaGraphDef` to save_path/filename.

    Args:
      filename: Optional meta_graph filename including the path.
      collection_list: List of string keys to collect.
      as_text: If `True`, writes the meta_graph as an ASCII proto.
      export_scope: Optional `string`. Name scope to remove.
      clear_devices: Whether or not to clear the device field for an `Operation`
        or `Tensor` during export.
      clear_extraneous_savers: Remove any Saver-related information from the
        graph (both Save/Restore ops and SaverDefs) that are not associated with
        this Saver.
      strip_default_attrs: Boolean. If `True`, default-valued attributes will be
        removed from the NodeDefs. For a detailed guide, see [Stripping
        Default-Valued
        Attributes](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/saved_model/README.md#stripping-default-valued-attributes).
      save_debug_info: If `True`, save the GraphDebugInfo to a separate file,
        which in the same directory of filename and with `_debug` added before
        the file extension.

    Returns:
      A `MetaGraphDef` proto.
    T)
add_shapesuse_pybind11_proto)
r8   	graph_defr   collection_listas_textr-  clear_devicesclear_extraneous_saversrQ  rR  )re  r   r   as_graph_defr   )	r4   r8   rt  ru  r-  rv  rw  rQ  rR  s	            r#   re  zSaver.export_meta_graph;  sT    D '')66 7 
 ..'!# 7/' r%   c                    t        j                          }| j                  ry|t        d      t        j                  |      }t        j                  |      st        d|z         t        j                  d|       	 t        j                         r| j                  |dd       n<|j                  | j                  j                  | j                  j                  |i       t7        j8                  t:        t=        |t        j                                       y# t         j"                  $ r}	 t%        |      }n## t         j"                  $ r t'        |d      w xY wt        j(                  d	       t+        || j,                  | j.                  || j0                  
      | _        | j0                  j3                  ||       Y d}~d}~wt         j4                  $ r}t'        |d      d}~ww xY w)a  Restores previously saved variables.

    This method runs the ops added by the constructor for restoring variables.
    It requires a session in which the graph was launched.  The variables to
    restore do not have to have been initialized, as restoring is itself a way
    to initialize variables.

    The `save_path` argument is typically a value previously returned from a
    `save()` call, or a call to `latest_checkpoint()`.

    Args:
      sess: A `Session` to use to restore the parameters. None in eager mode.
      save_path: Path where parameters were previously saved.

    Raises:
      ValueError: If save_path is None or not a valid checkpoint.
    Nz%Can't load save_path when it is None.z0The passed save_path is not a valid checkpoint: zRestoring parameters from %sFTr  z2a Variable name or other graph key that is missingzRestoring an object-based checkpoint using a name-based saver. This may be somewhat fragile, and will re-build the Saver. Instead, consider loading object-based checkpoints using tf.train.Checkpoint().)r  r  r  names_to_keyscached_saver)rg  rh  z2a mismatch between the current graph and the graphrN  )r   r   r   r   ru  r   checkpoint_exists_internalr   infor   r   r  r\  r   r   r   r   rA  object_graph_key_mapping_wrap_restore_error_with_msgr   "saver_from_object_based_checkpointr   r   r  r   InvalidArgumentErrorr   AddCheckpointReadDurationra  r$   )r4   rg  rh  rk  rp   errrz  s          r#   r   zSaver.restorel  s   $ J~~>??y1 ;;<MNI() * * LL/1BC)E		"	"	$)TJ//..55yA	CL %%/
DIIKHJI  IG0;!! G +EG 	G	G oo#$
 $F#>>--%11$3d    ((di(HH&& E )
CE EEs8   >A%D G//D;:G; EA(GG/G**G/c                 4    t        j                  | ||       y)zAdds a collection to MetaGraphDef protocol buffer.

    Args:
      meta_graph_def: MetaGraphDef protocol buffer.
      key: One of the GraphKeys or user-defined string.
      export_scope: Optional `string`. Name scope to remove.
    )r-  N)r   add_collection_def)meta_graph_defr   r-  s      r#   _add_collection_defzSaver._add_collection_def  s     !!,8r%   )metar2   )NNr  TTFF)NNFNFFFF)r   r   r   r   r   rA   rD   r6   r   r  r  r  r  r  r&  r(  r.  staticmethodr2  propertyr6  r;  r>  rE  r]   re  r   r  r   r%   r#   r   r     s   FV -4$)  &//22$#(_&BE
M1Mf
.
L 0>6 
9 
9 M ME"8A4 # $ W#t "&(, %%)&+05,1(-/bJJX 	8 	8r%   r   ztrain.import_meta_graphc                 $    t        | ||fi |d   S )a  Recreates a Graph saved in a `MetaGraphDef` proto.

  This function takes a `MetaGraphDef` protocol buffer as input. If
  the argument is a file containing a `MetaGraphDef` protocol buffer ,
  it constructs a protocol buffer from the file content. The function
  then adds all the nodes from the `graph_def` field to the
  current graph, recreates all the collections, and returns a saver
  constructed from the `saver_def` field.

  In combination with `export_meta_graph()`, this function can be used to

  * Serialize a graph along with other Python objects such as `QueueRunner`,
    `Variable` into a `MetaGraphDef`.

  * Restart training from a saved graph and checkpoints.

  * Run inference from a saved graph and checkpoints.

  ```Python
  ...
  # Create a saver.
  saver = tf.compat.v1.train.Saver(...variables...)
  # Remember the training_op we want to run by adding it to a collection.
  tf.compat.v1.add_to_collection('train_op', train_op)
  sess = tf.compat.v1.Session()
  for step in range(1000000):
      sess.run(train_op)
      if step % 1000 == 0:
          # Saves checkpoint, which by default also exports a meta_graph
          # named 'my-model-global_step.meta'.
          saver.save(sess, 'my-model', global_step=step)
  ```

  Later we can continue training from this saved `meta_graph` without building
  the model from scratch.

  ```Python
  with tf.Session() as sess:
    new_saver =
    tf.train.import_meta_graph('my-save-dir/my-model-10000.meta')
    new_saver.restore(sess, 'my-save-dir/my-model-10000')
    # tf.get_collection() returns a list. In this example we only want
    # the first one.
    train_op = tf.get_collection('train_op')[0]
    for step in range(1000000):
      sess.run(train_op)
  ```

  NOTE: Restarting training from saved `meta_graph` only works if the
  device assignments have not changed.

  Example:
  Variables, placeholders, and independent operations can also be stored, as
  shown in the following example.

  ```Python
  # Saving contents and operations.
  v1 = tf.placeholder(tf.float32, name="v1")
  v2 = tf.placeholder(tf.float32, name="v2")
  v3 = tf.math.multiply(v1, v2)
  vx = tf.Variable(10.0, name="vx")
  v4 = tf.add(v3, vx, name="v4")
  saver = tf.train.Saver([vx])
  sess = tf.Session()
  sess.run(tf.global_variables_initializer())
  sess.run(vx.assign(tf.add(vx, vx)))
  result = sess.run(v4, feed_dict={v1:12.0, v2:3.3})
  print(result)
  saver.save(sess, "./model_ex1")
  ```

  Later this model can be restored and contents loaded.

  ```Python
  # Restoring variables and running operations.
  saver = tf.train.import_meta_graph("./model_ex1.meta")
  sess = tf.Session()
  saver.restore(sess, "./model_ex1")
  result = sess.run("v4:0", feed_dict={"v1:0": 12.0, "v2:0": 3.3})
  print(result)
  ```

  Args:
    meta_graph_or_file: `MetaGraphDef` protocol buffer or filename (including
      the path) containing a `MetaGraphDef`.
    clear_devices: Whether or not to clear the device field for an `Operation`
      or `Tensor` during import.
    import_scope: Optional `string`. Name scope to add. Only used when
      initializing from protocol buffer.
    **kwargs: Optional keyed arguments.

  Returns:
    A saver constructed from `saver_def` in `MetaGraphDef` or None.

    A None value is returned if no variables exist in the `MetaGraphDef`
    (i.e., there are no variables to restore).

  Raises:
    RuntimeError: If called with eager execution enabled.

  @compatibility(eager)
  Exporting/importing meta graphs is not supported. No graph exists when eager
  execution is enabled.
  @end_compatibility
  r   )'_import_meta_graph_with_return_elements)meta_graph_or_filerv  r1  kwargss       r#   import_meta_graphr    s*    \ 
11C1>
;39
;;<
> >r%   c                     t        j                         rt        d      t        | t        j
                        st        j                  |       }n| }t        j                  |f|||d|\  }}t        |||      }||fS )z@Import MetaGraph, and return both a saver and returned elements.Exporting/importing meta graphs is not supported when eager execution is enabled. No graph exists when eager execution is enabled.)rv  r1  return_elements)
r   r   rF   r   r   MetaGraphDefr   read_meta_graph_file-import_scoped_meta_graph_with_return_elements&_create_saver_from_imported_meta_graph)	r  rv  r1  r  r  r  imported_varsimported_return_elementsr   s	            r#   r  r  8  s      
 / 0 0 
&(C(C	D445GHN'N >>
%#)	
  *-) 11>@%	(	((r%   c                 >   | j                  d      rW|}t        |j                               }|r#|d   }||   }|j                  dt	        |        }t        | j                  |      S t        j                  |      r
t               S t        j                  d       y)zFReturn a saver for restoring variable values to an imported MetaGraph.r   r   Nr0  )scopezHSaver not created because there are no variables in the graph to restore)HasFieldr5  keysr>   rj   r   r   r   r  r   r}  )r  r1  r  r  	var_names
sample_key
sample_vars          r#   r  r  T  s     [)E]'')*IQ<j ,joo/J/0e>33%@@&&\:Wn ll ' (r%   ztrain.export_meta_graphc                     t        j                         r||t        d      t        j                  d| |||||||||	|
|d|\  }}|S )a  Returns `MetaGraphDef` proto.

  Optionally writes it to filename.

  This function exports the graph, saver, and collection objects into
  `MetaGraphDef` protocol buffer with the intention of it being imported
  at a later time or location to restart training, run inference, or be
  a subgraph.

  Args:
    filename: Optional filename including the path for writing the generated
      `MetaGraphDef` protocol buffer.
    meta_info_def: `MetaInfoDef` protocol buffer.
    graph_def: `GraphDef` protocol buffer.
    saver_def: `SaverDef` protocol buffer.
    collection_list: List of string keys to collect.
    as_text: If `True`, writes the `MetaGraphDef` as an ASCII proto.
    graph: The `Graph` to export. If `None`, use the default graph.
    export_scope: Optional `string`. Name scope under which to extract the
      subgraph. The scope name will be striped from the node definitions for
      easy import later into new name scopes. If `None`, the whole graph is
      exported. graph_def and export_scope cannot both be specified.
    clear_devices: Whether or not to clear the device field for an `Operation`
      or `Tensor` during export.
    clear_extraneous_savers: Remove any Saver-related information from the graph
      (both Save/Restore ops and SaverDefs) that are not associated with the
      provided SaverDef.
    strip_default_attrs: Boolean. If `True`, default-valued attributes will be
      removed from the NodeDefs. For a detailed guide, see [Stripping
      Default-Valued
      Attributes](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/saved_model/README.md#stripping-default-valued-attributes).
    save_debug_info: If `True`, save the GraphDebugInfo to a separate file,
      which in the same directory of filename and with `_debug` added before the
      file extend.
    **kwargs: Optional keyed arguments.

  Returns:
    A `MetaGraphDef` proto.

  Raises:
    ValueError: When the `GraphDef` is larger than 2GB.
    RuntimeError: If called with eager execution enabled.

  @compatibility(eager)
  Exporting/importing meta graphs is not supported unless both `graph_def` and
  `graph` are provided. No graph exists when eager execution is enabled.
  @end_compatibility
  r  )r8   meta_info_defrs  r   rt  ru  r   r-  rv  rw  rQ  rR  r   )r   r   rF   r   export_scoped_meta_graph)r8   r  rs  r   rt  ru  r   r-  rv  rw  rQ  rR  r  r  r  s                  r#   re  re  l  s    @  )*?*/*;
 / 0 0 !99 !%!5-% 	.! 
r%   c                     dj                  || j                        }| j                  | j                  | j                  |      S )NzRestoring from checkpoint failed. This is most likely due to {} from the checkpoint. Please ensure that you have not altered the graph expected based on the checkpoint. Original error:

{})r(   message	__class__node_defrm   )r  extra_verbiageerr_msgs      r#   r  r    s;    % '-f^S[[&I 
 
s||SVVW	55r%   )
proto_typer.  r2  c                 2   t        j                  |       }|j                  t        j                        }t        j                         }|j                  |       i }|j                  D ],  }|j                  D ]  }|j                  ||j                  <    . |S )zReturn name to key mappings from the checkpoint.

  Args:
    checkpoint_path: string, path to object-based checkpoint

  Returns:
    Dictionary mapping tensor names to checkpoint keys.
  )r   NewCheckpointReader
get_tensor	trackableOBJECT_GRAPH_PROTO_KEYr   TrackableObjectGraphParseFromStringnodes
attributescheckpoint_key	full_name)r  readerobject_graph_stringobject_graph_protorz  node	attributes          r#   r~  r~    s      33OD&)))*J*JK2GGI$$%89- && Dd__ D	+4+C+CmI''(DD 
r%   c                 *   |	 t        |       }|t	        j
                         }|
t               }t        |t              st        j                  |      }t        j                  |      }t               }|D ].  }|j                  D ]  }|j                  |j                          0 t        |j!                               }	||	z
  }
|
rm|	|z
  }|	j#                  |      }t        j                  ddddj%                  t'        |
            dj%                  t'        |            t)        |      fz        |D ]'  }|j                  D ]  }||j                     |_         ) |t+        |      S |S # t        j                  $ r t        d| z        w xY w)a  Return a `Saver` which reads from an object-based checkpoint.

  This function validates that all variables in the variables list are remapped
  in the object-based checkpoint (or `names_to_keys` dict if provided). A
  saver will be created with the list of remapped variables.

  The `cached_saver` argument allows the user to pass in a previously created
  saver, so multiple `saver.restore()` calls don't pollute the graph when graph
  building. This assumes that keys are consistent, meaning that the
    1) `checkpoint_path` checkpoint, and
    2) checkpoint used to create the `cached_saver`
  are the same type of object-based checkpoint. If this argument is set, this
  function will simply validate that all variables have been remapped by the
  checkpoint at `checkpoint_path`.

  Note that in general, `tf.train.Checkpoint` should be used to restore/save an
  object-based checkpoint.

  Args:
    checkpoint_path: string, path to object-based checkpoint
    var_list: list of `Variables` that appear in the checkpoint. If `None`,
      `var_list` will be set to all saveable objects.
    builder: a `BaseSaverBuilder` instance. If `None`, a new `BulkSaverBuilder`
      will be created.
    names_to_keys: dict mapping string tensor names to checkpoint keys. If
      `None`, this dict will be generated from the checkpoint file.
    cached_saver: Cached `Saver` object with remapped variables.

  Returns:
    `Saver` with remapped variables for reading from an object-based checkpoint.

  Raises:
    ValueError if the checkpoint provided is not an object-based checkpoint.
    NotFoundError: If one of the variables in `var_list` can not be found in the
      checkpoint. This could mean the checkpoint or `names_to_keys` mapping is
      missing the variable.
  Nz0Checkpoint in %s not an object-based checkpoint.a#  

Existing variables not in the checkpoint: %s

Variables names when this checkpoint was written which don't exist now: %s

(%d variable name(s) did match)

Could not find some variables in the checkpoint (see names above). Saver was attempting to load an object-based checkpoint (saved using tf.train.Checkpoint or tf.keras.Model.save_weights) using variable names. If the checkpoint was written with eager execution enabled, it's possible that variable names have changed (for example missing a '_1' suffix). It's also possible that there are new variables which did not exist when the checkpoint was written. You can construct a Saver(var_list=...) with only the variables which previously existed, and if variable names have changed you may need to make this a dictionary with the old names as keys.z, )r  )r~  r   rA  r   r   r  r   r   r   r   r   r   r   r<   addr>   r  intersectionjoinr   rj   r   )r  r  r  rz  r{  rH   current_namesrI   rJ   previous_namesmissing_namesextra_namesintersecting_namess                r#   r  r    s   T (.?m ..0H_ G	Hd	##33H=H"<<XF)%- #h #		"## }))+,..0- =0K'44]C


A 6-01499;'4)*-.@*AC!CD D*  +h +		*di++ 	]  (I&' ( ((s   E0 0"F)FN)FNN)NNNNNFNNFFFF)NNNN)Rr   r   r'   os.pathrf   	threadingr   r   r8  tensorflow.core.protobufr   r   r   tensorflow.python.checkpointr   tensorflow.python.clientr   tensorflow.python.eagerr   tensorflow.python.frameworkr	   r
   r   r   r   r   tensorflow.python.opsr   r   r   r   r   r   tensorflow.python.platformr   r   r   0tensorflow.python.saved_model.pywrap_saved_modelr   tensorflow.python.trackabler   r  tensorflow.python.trainingr   r   !tensorflow.python.training.savingr   r   tensorflow.python.utilr    tensorflow.python.util.tf_exportr   get_checkpoint_stateupdate_checkpoint_stategenerate_checkpoint_state_protolatest_checkpointcheckpoint_existsr@  r!  r   Lockr   ra  r$   r.   r0   r   r   r   r  r  r  re  r  register_proto_functionr   r   rA   r.  r2  r~  r  r   r%   r#   <module>r     s  "
       3 . ? > , + 3 7 . 2 + + 2 , ( , + , < D 9 ; 4 = B ) 6 -AA /GG 99  );; );; -CC );;   -y~~/  Br' r'jG' G&6 }o@8 @8 @8F ()*$)#'o> +o>f ;@9=<@)80 ()*#$( $ $&*# #'$).3*/&+R +Rj6   MM!!^^	!* 15/35948	[r%   