
    BVh                     l   d Z ddlZddlmZmZ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"  G d de#      Z$d Z%d Z&d Z' ejP                  dg d      Z)d Z*d Z+d  Z,y)!z7Logic for restoring checkpointed values for Trackables.    N)OptionalMappingAny)checkpoint_adapter)checkpoint_view)functional_saver)save_util_v1)saveable_compat)context)ops)tensor)	array_ops)
gen_io_ops)io_ops)
tf_logging)registration)base)	constants)python_state)trackable_utils)saveable_object_util)object_identityc                      e Zd ZdZg dZd Zd$dZd Zdej                  fdZ
d	efd
Zd	efdZ	 d$dee   d	eeej$                  f   fdZd Zd Zd Zd$dZed        Zed        Zed        Zed        Zed        Zd Zd Zd Z d Z!	 d$de"de#jH                  dededeej                     f
d Z%d! Z&d$d"Z'd# Z(y)%CheckpointPositionz>Indicates a position within a `_CheckpointRestoreCoordinator`.)_checkpoint	_proto_idskip_restorecallbackc                 `    || _         || _        d| _        t        j                         | _        y)zSpecify an object within a checkpoint.

    Args:
      checkpoint: A _CheckpointRestoreCoordinator object.
      proto_id: The index of this object in TrackableObjectGraph.nodes.
    FN)r   r   r   r   ReshardCallbackr   )self
checkpointproto_ids      T/home/dcms/DCMS/lib/python3.12/site-packages/tensorflow/python/checkpoint/restore.py__init__zCheckpointPosition.__init__.   s-     "DDN D&668DM    Nc                     t        j                         5  | j                  |      r.| j                  |      }|r| j                  j                  |       ddd       y# 1 sw Y   yxY w)z$Restore this value into `trackable`.N)r   
init_scopebind_object_restore_descendantsr   new_restore_ops)r!   	trackablereaderrestore_opss       r$   restorezCheckpointPosition.restore<   sX    		 8			)	$ //7



*
*;
78 8 8s   A AA'c                 `   | j                   }|j                  j                  |       |j                  j	                  | j
                  d      }|j                  j                  | j
                         |||j                  | j
                  <   y||urt        j                  d| d| d       y)a\  Set a checkpoint<->object correspondence.

    Args:
      trackable: The object to record a correspondence for.

    Returns:
      True if this is a new assignment, False if this object has already been
      mapped to a checkpointed `Object` proto.
    Raises:
      AssertionError: If another object is already bound to the `Object` proto.
    NTa&  Inconsistent references when loading the checkpoint into this object graph. For example, in the saved checkpoint object, `model.layer.weight` and `model.layer_copy.weight` reference the same variable, while in the current object these are two different variables. The referenced variables are:(z and z).F)	r"   all_python_objectsaddobject_by_proto_idgetr   matched_proto_idsloggingwarning)r!   r,   r"   current_assignments       r$   r)   zCheckpointPosition.bind_objectF   s     J!!%%i0#66::4>>4P  $$T^^4!6?j##DNN3 
9	,
 ##527	8 r&   r   c                     t        t        j                  t        | j                              st        d      || _        y)zAdd a resharding callback to the checkpoint.

    This will be applied to the checkpoint value before being supplied to the
    restore ops.

    Args:
     callback: Reshard callback for resharding this checkpoint position. Maybe
       None.
    z@Cannot override resharding callback, already set to non trivial.N)
issubclassr   r    typer   	TypeError)r!   r   s     r$   update_resharding_callbackz-CheckpointPosition.update_resharding_callbackh   s7     (88$t}}:MN
L  DMr&   returnc                 ^    t        t        j                  t        | j                               S )zCDetermine whether this value has a non-trivial resharding callback.)r:   r   r    r;   r   r!   s    r$    has_non_trivial_reshard_callbackz3CheckpointPosition.has_non_trivial_reshard_callbackz   s(    **D,?  r&   c                     | j                   j                  }t        |      dk(  xr9 |d   j                  t        j
                  k(  xr | j                   j                   S )zEDetermine whether this value is restorable with a Tensor initializer.   r   )object_proto
attributeslennamer   VARIABLE_VALUE_KEYchildren)r!   rE   s     r$   is_simple_variablez%CheckpointPosition.is_simple_variable   sX    ""--JJ1 	+qM)">">>	+!!***r&   shape_and_slicesc                 :   i }| j                   j                  D ]e  }|j                  }| j                  j                  j
                  xs d}t        j                         5  t        j                  |      5  ||j                  |v r||j                     }nd}| j                  j                  ||      \  }}g }	|D ]6  }
| j                  j                  |
   }|	j                  |j                         8 t        j                   | j                  j"                  |||	|j                  d      }| j                  j%                  ||      }ddd       t'        j(                        ||j                  <   ddd       h |S # 1 sw Y   8xY w# 1 sw Y   xY w)a  Create value `Tensor`s for this object's attributes.

    Does not require that the Python object has been created. Used for
    restore-on-create when executing eagerly.

    Args:
      shape_and_slices: A dict mapping from object attribute names to a shape
        and slice string that will be passed to a RestoreV2 op. If the dict is
        None or if an object attribute is not in the dict, the full tensor will
        be restored.

    Returns:
      A dictionary mapping from object attribute names to `Tensor`s.
    zcpu:0N _checkpoint_read)prefixtensor_namesrK   dtypesrG   )rD   rE   checkpoint_keyr   optionsexperimental_io_devicer   r(   devicerG   r   update_restore_inputs	dtype_mapappend
base_dtyper   
restore_v2save_path_tensorreshardr   identity)r!   rK   value_tensorsserialized_tensorrR   	io_deviceshape_and_slicecheckpoint_keysfull_shape_and_slicesrQ   keydtyperestored_valuesvalues                 r$   r^   z CheckpointPosition.value_tensors   s   " M!..99 !J(77n""**AALWi>> JZZ	" 	 *#((,<<./@/E/EFO Omm11 / 1/0
 &$ ,c$$..s3EMM%**+, #--%%66*4+<+A+AC/ --''%3	: 1:0B0B50I',,-=J J!JD =	 	J Js%   !F7CF*FF	FF	c                    | j                         }| j                  j                  s|sg i g i fS g }i }g }t        j                  t
              }t        j                  | j                        }t        j                   | j                        }|rA| j                  sQ| j                  j                  j                  }| j                  ||   |<   n|r3| j                  j                  d   j                  | j                  i||<   nt        | j                  t        j                         r|j#                  |        n|j%                         t&        j(                  hk(  r| j+                  |      \  }}n{|r| j-                  |      \  }}nd| j                  j                  D ]K  }	| j.                  j0                  j3                  | j4                  g       j#                  |	j6                         M ||||fS )zLooks up or creates SaveableObjects which don't have cached ops.

    Returns:
      A tuple of (
          existing_restore_ops: list,
          named_saveables: dict,
          python_positions: list,
          registered_savers: dict)
    r   )get_registered_saver_namerD   rE   collectionsdefaultdictdictr   saveable_objects_from_trackabler,   r   r   registered_saverobject_namerR   
isinstancer   PythonStaterX   keysr   SERIALIZE_TO_TENSORS_NAME$_create_serialize_to_tensor_saveable#_create_saveables_by_attribute_namer   unused_attributes
setdefaultr   rG   )
r!   recorded_registered_saverexisting_restore_opsnamed_saveablespython_positionsregistered_saverssaveable_factories
saver_namerG   r_   s
             r$   gather_ops_or_named_saveablesz0CheckpointPosition.gather_ops_or_named_saveables   s    !% > > @((,ER^O#//5-MM77GJ   11===A^^34T: 
 


&
&q
)
8
8$..'
# 
DNNL$<$<	=d#		 	 	"11' 
 
3
34F
G ,O	

2
23E
F ,O
  $00;; ?
**55NNB	  &'8'='= >? !/3C r&   c                    t        j                  | j                        xs d}t        | j                  j
                  d   j                        |z   }t        j                         sj| j                  j                  j                  |d      }||gi fS | j                  j                  j                  | j                  i       }||v r	g |||   ifS  |t        j                     |      }t        j                         s||<   g ||ifS )z9Creates a saveable using the _serialize_to_tensor method.rM   r   NrG   )r
   get_saveable_namer,   _extract_saveable_namerD   rE   rR   r   executing_eagerlyr   restore_ops_by_namer4   saveables_cacherw   r   rs   )r!   r}   suffixsaveable_nameexisting_opr   saveables          r$   rt   z7CheckpointPosition._create_serialize_to_tensor_saveable   s    ..t~~>D"F*$$Q'668:@AM $$&$$88<<
k		 }b  ((88CC
.."o	/	)M?=#ABBBL!/"K"KLH$$&'/om$x(((r&   c                   	 i }g }t               }| j                  j                  D ]  	t        j                         rd}n0| j
                  j                  j                  	j                  d      }||j                  |       _t        	fd|D              rt| j
                  j                  }|d}nK|j                  | j                  i       j                  	j                  d      }t        |      dk(  r|\  }nd}|'	j                  |j                  vrd}|| j                  = |t        |	|      }|K| j
                  j                   j#                  | j$                  g       j                  	j                         _|*|g|j#                  | j                  i       	j                  <   ||	j                  <    ||fS )a+  Creates or caches SaveableObjects by matching the attribute names.

    The attribute name keys in the `saveable_factories` is used to find the
    corresponding attribute in the object proto. Attributes contain checkpoint
    keys which are passed to the factory function to generate the
    SaveableObject.

    Args:
      saveable_factories: a dict mapping attribute name to a callable factory
        function that produces a SaveableObject.

    Returns:
      A tuple of (
          existing_restore_ops: list,
          named_saveables: dict)
    Nc              3   T   K   | ]  }j                   j                  |       ! y wN)rG   
startswith).0rG   r_   s     r$   	<genexpr>zICheckpointPosition._create_saveables_by_attribute_name.<locals>.<genexpr>:  s*      / ##..t4 /s   %(r   rC   )setrD   rE   r   r   r   r   r4   rR   rX   anyr   r,   rG   rF   _get_saveable_from_factoryrv   rw   r   )
r!   r}   rz   ry   created_compat_namesr   r   r   saveable_listr_   s
            @r$   ru   z6CheckpointPosition._create_saveables_by_attribute_name  s   $ O 5!..99 <C		"	"	$&&::>>,,d4		 ##K0	 /-/ 
/ ((88o		 
 (++DNN,.0034E4J4J4;1= 	 }"#)(
 (		 ++8==@(dnn-		 ..@.?.BD 
 


,
,
7
7nnb""(&):)?)?"@
&DL: 
$
$T^^%')):)?)?A:Bo'667y<C|  00r&   c                     | j                         rt        d      | j                         \  }}}}|j                  | j                  j                  |||             |S )aj  Create or fetch restore ops for this object's attributes.

    Requires that the `Trackable` Python object has been bound to an object
    ID in the checkpoint.

    Args:
      reader: A `CheckpointReader`. If None, a new instance will be created.

    Returns:
      A list of operations when graph building, or an empty list when executing
      eagerly.
    zOUnable to run individual checkpoint restore for objects with registered savers.r-   )_has_registered_saver
ValueErrorr   extendr   restore_saveables)r!   r-   r.   tensor_saveablesr{   _s         r$   r.   zCheckpointPosition.restore_opsp  sx     !!# 2 3 3 
,
,
.["$4**.v 	+ 	?@ r&   c                     | j                   S r   )r   r@   s    r$   r"   zCheckpointPosition.checkpoint  s    r&   c                 H    | j                   j                  | j                     S r   )r   r3   r   r@   s    r$   r,   zCheckpointPosition.trackable  s    ..t~~>>r&   c                 \    | j                   j                  j                  | j                     S r   )r   object_graph_protonodesr   r@   s    r$   rD   zCheckpointPosition.object_proto  s#    ..44T^^DDr&   c                     | j                   S r   )r   r@   s    r$   r#   zCheckpointPosition.proto_id  s    >>r&   c                 .    | j                   j                  S r   )r   restore_uidr@   s    r$   r   zCheckpointPosition.restore_uid  s    '''r&   c                 ,    t        | j                        S r   )reprrD   r@   s    r$   __repr__zCheckpointPosition.__repr__  s    !!""r&   c                     | j                   j                  D ]D  }|j                  t        j                  k(  s!| j
                  j                  |j                     c S  y)zoThe shape of the VARIABLE_VALUE tensor.

    Returns:
      If found a TensorShape object, otherwise None.
    N)rD   rE   rG   r   rH   r   	shape_maprR   )r!   r_   s     r$   value_shapezCheckpointPosition.value_shape  sY     "..99 L			9#?#?	?))*;*J*JKKL r&   c                 T    t        | j                  j                  j                        S r   )boolrD   rn   rG   r@   s    r$   r   z(CheckpointPosition._has_registered_saver  s    !!227788r&   c                    | j                         rC| j                  j                  j                  }	 t	        j
                  | j                  |       |S y# t        $ r)}t	        j                  |      r|d| _	        Y d}~|S d}~ww xY w)z<Returns the registered saver name defined in the Checkpoint.TN)
r   rD   rn   rG   r   validate_restore_functionr,   r   get_strict_predicate_restorer   )r!   r~   es      r$   ri   z,CheckpointPosition.get_registered_saver_name  s    !!#$$55::j!..t~~zJ
   !44Z@' 	!s    A 	BBBoptimizer_objectvariableslot_variable_id	slot_namereshard_callbackc                     t        | j                  |      }|1|j                  |       |j                  ||||j                        }n|j                  |||      }||j                  |      r||fS y)au  Generates CheckpointPosition for a slot variable.

    Args:
      optimizer_object: Optimizer that owns the slot variable.
      variable: Variable associated with the slot variable.
      slot_variable_id: ID of the slot variable.
      slot_name: Name of the slot variable.
      reshard_callback: A callback object for resharding value from checkpoint
        at restore.

    Returns:
      If there is a slot variable in the `optimizer_object` that has not been
      bound to the checkpoint, this function returns a tuple of (
        new `CheckpointPosition` for the slot variable,
        the slot variable itself).
    r"   r#   )slot_variable_positionr   r   slot_variable_shape)r   r   r   )NN)r   r"   r=    _create_or_restore_slot_variableshaper)   )r!   r   r   r   r   r   r   slot_variables           r$   create_slot_variable_positionz0CheckpointPosition.create_slot_variable_position  s    0 0??-= #778HI&GG!7&nn	 H m 'GG!7 H m  %;%G%G& $]22r&   c                 0    t        | j                  |      S )Nr   )r   r"   )r!   node_ids     r$   create_child_positionz(CheckpointPosition.create_child_position  s    7KKr&   c                 ,   t        j                  | | j                  fg      }g }i }g }t        j                  t              }|r|j                         \  }}|j                         \  }	}
}}|j                  |	       |j                  |
       |j                  |       |j                         D ]  \  }}||   j                  |        t        ||       t        ||       |r|j                  j                  j                  ||||             |S )z?Restore the bound Trackable and dependencies (may be deferred).r   )rj   dequer,   rk   rl   popleft_single_restorer   updateitems_queue_children_for_restoration_queue_slot_variablesr"   r   )r!   r-   visit_queuer.   r   r{   r|   current_positionr   r+   new_tensor_saveablesnew_python_positionsnew_registered_saversr~   trackable_maps                  r$   r*   z'CheckpointPosition._restore_descendants  s-    ##dDNN%;$<=KK#//5
'//1 
*
*
,



)2323'<'B'B'D <
#*m*%,,];< &&6D,k:% ( ##55.0A& 	6 	

 r&   c                     | j                   }|j                          | j                  }|j                  |j                  kD  r'| j                         \  }}}}|j                  |_        nd}i }d}i }||||fS )zRestores the trackable. )r,   _maybe_initialize_trackabler"   r   _update_uidr   )r!   r,   r"   r.   r   r{   r|   s          r$   r   z"CheckpointPosition._single_restore  s    I))+J 	 5 55

,
,
. Ik#%57H )44ik(*:<MMMr&   r   ))__name__
__module____qualname____doc__	__slots__r%   r/   r)   r   r    r=   r   rA   rJ   r   strr   r   Tensorr^   r   rt   ru   r.   propertyr"   r,   rD   r#   r   r   r   r   ri   r   r   	Trackabler   r   r*   r   r   r&   r$   r   r   )   sb   FF)98 D(88$ $  /34&sm4sFMM!"4l<|)4W1r.   ? ? E E   ( (#	9& HL11 1 	1
 1 !!3!C!CD1fL*XNr&   r   c           
      *   | t        d      t        |t              st        d      t        j                  |       }|j                         }|j                         D ]c  \  }}||vs|j                  j                  |   	 t        d| d| d      |t        |t        j                        rSt        d| d| d	       t        j                         }|j                         D ]  \  }}|j                  j                  |   j                  }|j                  j                  |   }	t        j                  |      }
|
s|	j                  s(t        j                   |      rt        d
| d| d	      t        j                         }t#        j$                  |	j                  d   j&                        ||<   t)        j*                  |d      \  }}t)        j,                  |      d   }t/        |	j                        t/        |      k7  r.t        dt/        |       dt/        |	j                         d	      t        j0                  ||      }|j3                         ||<   t5        ||         }|r|st        d
| d| d	      |s|rt        d
| d| d| d	      t/        |	j                        t/        ||         k7  r1t        dt/        ||          dt/        |	j                         d	      |
s&t7        j8                  |      j;                  |        5t        j                         }i ||<   |	j                  D ](  }|j<                  }|j&                  }||   |   ||   |<   * t7        j8                  |      j;                  |         y)a  Restores nodes from a dict.

  Requires that the `Trackable` Python object has been bound to an object
  ID in the checkpoint.

  Args:
    save_path: a string represents path to the checkpoint.
    nodes_to_restore: a dict maps `node_id` to `trackable` to be restored.
  Nzsave_path cannot be empty.zDExpecting a dictionary of node_id to Trackable for nodes_to_restore.zThe expected node_id: z to Trackable z- to restore does not exist in the checkpoint.z(Expecting a valid Trackable to node_id: z but got trackable: .z
Trackable z] expects checkpointed values but checkpoint does not contain serialized tensors for node_id: r   z)Size for saveable_objects for Trackable: z? did not match the size for serialized_tensors for checkpoint: zQ does not expect checkpointed values but checkpoint contains serialized tensors: z for node_id: z+Size for serialized_tensors for Trackable: z; did not match size for serialized_tensors for checkpoint: )r   rp   rl   r   CheckpointViewdescendantsr   _object_graph_protor   r   r   r   ObjectIdentityDictionaryrE   r   !trackable_has_serialize_to_tensorrm   r   extract_object_namerR   r	   !get_checkpoint_factories_and_keysgenerate_saveable_objectsrF   SaveableCompatibilityConverter_serialize_to_tensorsr   r   MultiDeviceSaverr/   rG   )	save_pathnodes_to_restore	ckpt_viewckpt_view_descendantsr   r,   serialized_tensorscurrent_trackable ckpt_contains_serialized_tensorsnoder   object_namescheckpoint_factory_mapr   saveable_objectstrackable_expects_ckpted_valueserialized_tensors_renamed	attributerG   rR   s                       r$   restore_nodesr   /  s0    
1
22	$d	+
NP P ,,Y7)#//1,224 gy,,%%++		"7)>) E6 67 7 
9dnn E4WI >!{!%  '??A$4$:$:$< F g '0'D'D'J'J( %((..w7D>>	
 &
 -__??,- .M	 
 $==?l(7(K(K
//!

+
+)-l$% 
8
8t
L  a &??
 ""#%	T__	%5!6	6D 012 3?014 5 	5 /MM
-/ /DDF %)*<=N*O%P"%.N() *IIQ 
 *.N() *@-.nWIQHI I
 4??s#56G#HIID01BCDE FLdoo./q2 3 3
 -''(:;CCIN $3#K#K#M 68 !23 J)~~"1101BCDI 	##45	J
 ''(BCKK
KFr&   c                 x    |j                  | j                  j                        }|r|j                  |      r|S y r   )_checkpoint_adapterr"   save_path_stringis_applicable)checkpoint_positionr,   adapters      r$   _maybe_get_adapterr     s;    ))$$55' &&y1N	r&   c                    | j                   }|j                         }t        | |      }| j                  j                  D ]}  }| j
                  j                  j                  |j                  d      }|7| j                  |j                        }|j                  |j                  |      }|j                  }	||	j                  d      r|	j                  j                  }
nDt        |	j                  xs- |	j                   xs |	j"                  xs |	j                  d            }
|
s|j                  }|r1|j%                  |j                        \  }}|r|j'                  |       |j(                  j+                  |g       j-                  |       W|j/                  |      sk|j-                  ||f        y)z>Queues the restoration of trackable's children or defers them.Nhas_checkpoint_valuesrn   )r,   )r,   _trackable_childrenr   rD   rI   r"   r3   r4   r   r   _lookup_dependency
local_nameHasFieldr  rg   r   rE   slot_variablesmaybe_reshardr=   _deferred_dependenciesrw   rX   r)   )r   r   r,   trackable_childrenr   childcorrespondencechild_positionlocal_objectchild_proto	has_valuelocal_trackable_namer   s                r$   r   r     s    "++) 4462I>'"//88 +;e )33FFJJtN !(>>u}}MN//0@0@0BDL --K 
		5	655;;	    8%%8))8 ##$67	
	 
$//3:3H3H4
0
 0 556FG((33 "	

&
 		#	#l	#	;
 	NL9:W+;r&    _DeferredSlotVariableRestorationoriginal_variabler   r   c           	         | j                   }| j                  }|j                  j                  | j                  d      D ]j  }| j                  ||j                  |j                  |j                  | j                         r| j                  nd      \  }}|X|j                  ||f       l |j                  j                  | j                  d      D ]  }|j                  j                  |j                  d      }|V|j                  j!                  |j                  g       j                  t#        ||j                  |j                               t%        |d      s| j                  |||j                  |j                  | j                         r| j                  nd      \  }}||j                  ||f        y)z&Queues slot variables for restoration.r   Nr  r   )r,   r"   deferred_slot_restorationspopr#   r   r  r   r   rA   r   rX   slot_restorationsr3   r4   optimizer_idrw   r  hasattr)	r   r   r,   r"   deferred_slot_restorationr   r   slot_restorationr   s	            r$   r   r     s   !++)"--*$.$I$I$M$M""B%( B 	99%77%66%//
 #CCE  ((	
 *M )0-@A#B$ %66::""B( "D!4488%%t- ++66

'
'--3V.$-#3#D#D,668.9 
!#E	F

;
;//((
 %EEG "** ,m 
 	+2MBCE"Dr&   c                 h    t         j                  dz   }| d | j                  |      t        |      z    S )N/)r   OBJECT_ATTRIBUTES_NAMEindexrF   )rR   
search_keys     r$   r   r     s4    55;*	K--j9C
OK	LLr&   c                 <   d}|j                   }|j                  }|| v r| |   }|b| j                         D ]O  \  }}|j                  |      s|t	        d      |}t        |j                        |z   }|j                  |       Q t        |      r	 ||      S |S )z7Returns the saveable generated from the factory method.NzForward compatibility load error: Unable to load checkpoint saved in future version of TensorFlow. Please update your version of TensorFlow to the version in which the checkpoint was saved.r   )rG   rR   r   r   r   r   r2   callable)r}   r_   r   matched_factoryexpected_factory_namefactory_input_namefactory_namefactorys           r$   r   r      s     /
 ,00(77 00()>?O !3!9!9!; /g		)	),	7&
  H I I
 "3,,.0<=  ./" o 233	r&   )-r   rj   typingr   r   r   tensorflow.python.checkpointr   r   r   r	   r
   tensorflow.python.eagerr   tensorflow.python.frameworkr   r   tensorflow.python.opsr   r   r   tensorflow.python.platformr   r6   tensorflow.python.saved_modelr   tensorflow.python.trackabler   r   r   r   !tensorflow.python.training.savingr   tensorflow.python.utilr   objectr   r   r   r   
namedtupler  r   r   r   r   r&   r$   <module>r4     s    >  ) ) ; 8 9 5 8 + + . + 6 ( < 6 , 1 4 7 B 2CN CNLhV1;h $:;#9#9& )$  8DvM&r&   