o
    2h                     @   sX  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 de#Z$dd Z%dd Z&dd Z'e(dg d Z)d!d" Z*d#d$ Z+d%d& Z,dS )'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                   @   sD  e Zd ZdZg dZdd Zd<ddZdd	 Zd
ej	fddZ
defddZdefddZ	d<dee deeejf fddZdd Zdd Zdd Zd<ddZedd Zedd  Zed!d" Zed#d$ Zed%d& Zd'd( Zd)d* Zd+d, Z d-d. Z!	d<d/e"d0e#j$d1ed2ed3eej	 f
d4d5Z%d6d7 Z&d<d8d9Z'd:d; Z(dS )=CheckpointPositionz>Indicates a position within a `_CheckpointRestoreCoordinator`.)_checkpoint	_proto_idskip_restorecallbackc                 C   s    || _ || _d| _t | _dS )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_id r!   _/var/www/html/chatgem/venv/lib/python3.10/site-packages/tensorflow/python/checkpoint/restore.py__init__.   s   zCheckpointPosition.__init__Nc                 C   sr   t  + | |r| |}|r'| j| W d   dS W d   dS W d   dS 1 s2w   Y  dS )z$Restore this value into `trackable`.N)r   
init_scopebind_object_restore_descendantsr   new_restore_ops)r   	trackablereaderrestore_opsr!   r!   r"   restore<   s   


"zCheckpointPosition.restorec                 C   sl   | j }|j| |j| jd}|j| j |du r$||j| j< dS ||ur4td| d| d dS )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_assignmentr!   r!   r"   r%   F   s    zCheckpointPosition.bind_objectr   c                 C   s$   t tjt| jstd|| _dS )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   r!   r!   r"   update_resharding_callbackh   s
   
z-CheckpointPosition.update_resharding_callbackreturnc                 C   s   t tjt| j S )zCDetermine whether this value has a non-trivial resharding callback.)r4   r   r   r5   r   r   r!   r!   r"    has_non_trivial_reshard_callbackz   s   z3CheckpointPosition.has_non_trivial_reshard_callbackc                 C   s.   | j j}t|dko|d jtjko| j j S )zEDetermine whether this value is restorable with a Tensor initializer.   r   )object_proto
attributeslennamer   VARIABLE_VALUE_KEYchildren)r   r=   r!   r!   r"   is_simple_variable   s   z%CheckpointPosition.is_simple_variableshape_and_slicesc              
   C   s  i }| j jD ]}|j}| jjjpd}t i t|L |dur,|j	|v r,||j	 }nd}| j
||\}}g }	|D ]}
| jj|
 }|	|j q;tj| jj|||	d|j	f d}| j
||}W d   n1 skw   Y  t|||j	< W d   n1 sw   Y  q|S )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 z%s_checkpoint_read)prefixtensor_namesrC   dtypesr?   )r<   r=   checkpoint_keyr   optionsexperimental_io_devicer   r$   devicer?   r   update_restore_inputs	dtype_mapappend
base_dtyper   
restore_v2save_path_tensorreshardr   identity)r   rC   value_tensorsserialized_tensorrH   	io_deviceshape_and_slicecheckpoint_keysfull_shape_and_slicesrG   keydtyperestored_valuesvaluer!   r!   r"   rT      sB   


z CheckpointPosition.value_tensorsc           
      C   s  |   }| jjs|sg i g i fS g }i }g }tt}t| j}t	 | j}|r9| j
s8| jjj}| j|| |< nJ|rH| jjd j| ji||< n;t| jtjrU||  n.| tjhkre| |\}}n|ro| |\}}n| jjD ]}	| jj| jg |	j qs||||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_namer<   r=   collectionsdefaultdictdictr   saveable_objects_from_trackabler(   r   r   registered_saverobject_namerH   
isinstancer   PythonStaterN   keysr   SERIALIZE_TO_TENSORS_NAME$_create_serialize_to_tensor_saveable#_create_saveables_by_attribute_namer   unused_attributes
setdefaultr   r?   )
r   recorded_registered_saverexisting_restore_opsnamed_saveablespython_positionsregistered_saverssaveable_factories
saver_namer?   rU   r!   r!   r"   gather_ops_or_named_saveables   sJ   



z0CheckpointPosition.gather_ops_or_named_saveablesc                 C   s   t | jpd}t| jjd j| }t s=| j	j
|d}|dur(|gi fS | j	j| ji }||v r=g ||| ifS |tj |d}t sM|||< g ||ifS )z9Creates a saveable using the _serialize_to_tensor method.rD   r   Nr?   )r	   get_saveable_namer(   _extract_saveable_namer<   r=   rH   r
   executing_eagerlyr   restore_ops_by_namer/   saveables_cacherl   r   rh   )r   rr   suffixsaveable_nameexisting_oprz   saveabler!   r!   r"   ri      s.   
z7CheckpointPosition._create_serialize_to_tensor_saveablec           	         s6  i }g }t  }| jjD ] t rd}n	| jj jd}|dur'|	| qt
 fdd|D r3q| jj}|du r>d}n|| ji  jd}t|dkrT|\}nd}|durf j|jvrfd}|| j= |du rt| |}|du r| jj| jg 	 j q|dur|g|| ji  j< || j< q||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   s    | ]	} j |V  qd S N)r?   
startswith).0r?   rU   r!   r"   	<genexpr>:  s    zICheckpointPosition._create_saveables_by_attribute_name.<locals>.<genexpr>r   r;   )setr<   r=   r
   rx   r   ry   r/   rH   rN   anyrz   r(   r?   r>   _get_saveable_from_factoryrk   rl   r   )	r   rr   ro   rn   created_compat_namesr}   rz   r~   saveable_listr!   r   r"   rj     sj   

z6CheckpointPosition._create_saveables_by_attribute_namec                 C   s<   |   rtd|  \}}}}|| jj|||d |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
ValueErrorrt   extendr   restore_saveables)r   r)   r*   tensor_saveablesrp   _r!   r!   r"   r*   p  s   zCheckpointPosition.restore_opsc                 C      | j S r   )r   r9   r!   r!   r"   r        zCheckpointPosition.checkpointc                 C   s   | j j| j S r   )r   r.   r   r9   r!   r!   r"   r(     s   zCheckpointPosition.trackablec                 C   s   | j jj| j S r   )r   object_graph_protonodesr   r9   r!   r!   r"   r<     s   zCheckpointPosition.object_protoc                 C   r   r   )r   r9   r!   r!   r"   r      r   zCheckpointPosition.proto_idc                 C   s   | j jS r   )r   restore_uidr9   r!   r!   r"   r     s   zCheckpointPosition.restore_uidc                 C   s
   t | jS r   )reprr<   r9   r!   r!   r"   __repr__  s   
zCheckpointPosition.__repr__c                 C   s0   | j jD ]}|jtjkr| jj|j   S qdS )zoThe shape of the VARIABLE_VALUE tensor.

    Returns:
      If found a TensorShape object, otherwise None.
    N)r<   r=   r?   r   r@   r   	shape_maprH   )r   rU   r!   r!   r"   value_shape  s
   zCheckpointPosition.value_shapec                 C   s   t | jjjS r   )boolr<   rc   r?   r9   r!   r!   r"   r        z(CheckpointPosition._has_registered_saverc              
   C   sf   |   r1| jjj}z
t| j| W |S  ty0 } zt|r"|d| _	W Y d}~|S d}~ww dS )z<Returns the registered saver name defined in the Checkpoint.TN)
r   r<   rc   r?   r   validate_restore_functionr(   r   get_strict_predicate_restorer   )r   rs   er!   r!   r"   r^     s   

z,CheckpointPosition.get_registered_saver_nameoptimizer_objectvariableslot_variable_id	slot_namereshard_callbackc                 C   sd   t | j|d}|dur|| |j||||jd}n|j|||d}|dur0||r0||fS dS )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    N)slot_variable_positionr   r   slot_variable_shape)r   r   r   )NN)r   r   r7    _create_or_restore_slot_variableshaper%   )r   r   r   r   r   r   r   slot_variabler!   r!   r"   create_slot_variable_position  s*   
z0CheckpointPosition.create_slot_variable_positionc                 C   s   t | j|dS )Nr   )r   r   )r   node_idr!   r!   r"   create_child_position  r   z(CheckpointPosition.create_child_positionc                 C   s   t | | jfg}g }i }g }t t}|rO| \}}| \}	}
}}||	 ||
 || |	 D ]\}}|| | q7t
|| t|| |s||jj||||d |S )z?Restore the bound Trackable and dependencies (may be deferred).r   )r_   dequer(   r`   ra   popleft_single_restorer   updateitems_queue_children_for_restoration_queue_slot_variablesr   r   )r   r)   visit_queuer*   r   rp   rq   current_positionr   r'   new_tensor_saveablesnew_python_positionsnew_registered_saversrs   trackable_mapr!   r!   r"   r&     s6   





z'CheckpointPosition._restore_descendantsc                 C   sV   | j }|  | j}|j|jkr|  \}}}}|j|_nd}i }d}i }||||fS )zRestores the trackable.r!   )r(   _maybe_initialize_trackabler   r   _update_uidrt   )r   r(   r   r*   r   rp   rq   r!   r!   r"   r     s   

z"CheckpointPosition._single_restorer   ))__name__
__module____qualname____doc__	__slots__r#   r+   r%   r   r   r7   r   r:   rB   r   strr   r   TensorrT   rt   ri   rj   r*   propertyr   r(   r<   r    r   r   r   r   r^   r   r   	Trackabler   r   r&   r   r!   r!   r!   r"   r   )   sd    

"


6>
Y





3
,r   c              	   C   s  | du rt dt|tst dt| }| }| D ]0\}}||vs.|jj| du r9t d| d| d|du sCt|t	j
sNt d| d| d	qt }| D ]\}}|jj| j}|jj| }	t|}
|
s|	jst|rt d
| d| d	qWt }t|	jd j||< t|d\}}t|d }t|	jt|krt dt| dt|	j d	t||}| ||< t|| }|r|st d
| d| d	|s|rt d
| d| d| d	t|	jt|| krt dt||  dt|	j d	|
st||  qWt }i ||< |	jD ]}|j}|j}|| | || |< q"t||  qWdS )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   re   ra   r   CheckpointViewdescendantsr   _object_graph_protor   r   r   r   ObjectIdentityDictionaryr=   r   !trackable_has_serialize_to_tensorrb   r   extract_object_namerH   r   !get_checkpoint_factories_and_keysgenerate_saveable_objectsr>   SaveableCompatibilityConverter_serialize_to_tensorsr   r   MultiDeviceSaverr+   r?   )	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	attributer?   rH   r!   r!   r"   restore_nodes/  s   










r   c                 C   s$   | | jj}|r||r|S d S r   )_checkpoint_adapterr   save_path_stringis_applicable)checkpoint_positionr(   adapterr!   r!   r"   _maybe_get_adapter  s   r   c                 C   s   | j }| }t| |}| jjD ]l}| jj|jd}|dur q| 	|j}|
|j|}|j}	|du ro|	dr>|	jj}
nt|	jpL|	jpL|	jpL|	d}
|
rn|j}|rd||j\}}|rd|| |j|g | q|j|dr||||f qdS )z>Queues the restoration of trackable's children or defers them.Nhas_checkpoint_valuesrc   )r(   )r(   _trackable_childrenr   r<   rA   r   r.   r/   r   r   _lookup_dependency
local_nameHasFieldr   r]   r   r=   slot_variablesmaybe_reshardr7   _deferred_dependenciesrl   rN   r%   )r   r   r(   trackable_childrenr   childcorrespondencechild_positionlocal_objectchild_proto	has_valuelocal_trackable_namer   r!   r!   r"   r     sT   



r    _DeferredSlotVariableRestorationoriginal_variabler   r   c           	   	   C   s  | j }| j}|j| jdD ]"}| ||j|j|j| 	 r | j
nd\}}|dur0|||f q|j| jdD ]E}|j|jd}|du rZ|j|jg t||j|jd q9t|dr~| |||j|j| 	 rn| j
nd\}}|dur~|||f q9dS )z&Queues slot variables for restoration.r!   Nr   r   )r(   r   deferred_slot_restorationspopr    r   r   r   r   r:   r   rN   slot_restorationsr.   r/   optimizer_idrl   r   hasattr)	r   r   r(   r   deferred_slot_restorationr   r   slot_restorationr   r!   r!   r"   r     sd   

r   c                 C   s$   t jd }| d | |t|  S )N/)r   OBJECT_ATTRIBUTES_NAMEindexr>   )rH   
search_keyr!   r!   r"   rw     s   
rw   c                 C   s   d}|j }|j}|| v r| | }|du r8|  D ]\}}||r7|dur)td|}t|j| }|| qt|rA||d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.ru   )r?   rH   r   r   r   rw   r-   callable)rr   rU   r   matched_factoryexpected_factory_namefactory_input_namefactory_namefactoryr!   r!   r"   r      s*   


r   )-r   r_   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   r1   tensorflow.python.saved_modelr   tensorflow.python.trackabler   r   r   r   !tensorflow.python.training.savingr   tensorflow.python.utilr   objectr   r   r   r   
namedtupler   r   rw   r   r!   r!   r!   r"   <module>   sH       
k	4;