
    BVhU-                        d Z ddlZddl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 eej0                  ej2                  f   Zeeef   Z ej.                  d       ej:                  d       G d d                    Z ej.                  d       G d dej>                               Z dee   dee   deddfdZ!y)z6Data structures and utilities for checkpoint sharding.    N)HashableMutableMappingSequence)device)dtypes)tensor)tensor_shape)tensor_spec)	variables)base)saveable_object)	tf_exportz"train.experimental.ShardableTensorT)frozenc                   $   e Zd ZU dZej
                  ed<   ej                  ed<   e	j                  ed<   ej                  ed<   eed<   ej                  ed<   ej"                  j$                  ed<   eed	<   ej(                  ed
<   defdZdefdZy)ShardableTensora  Tensor wrapper containing data necessary for sharding.

  The tensor representation used as inputs to pre-made and custom
  `tf.train.experiemental.ShardingCallback`s, which can be specified using the
  `experimental_sharding_callback` option in `tf.train.CheckpointOptions`.

  _tensor_save_specr   dtyper   nameshape
slice_speccheckpoint_key	trackablereturnc                     t        | j                  | j                  t        | j                        | j
                  f      S N)hashr   r   strr   r   selfs    c/home/dcms/DCMS/lib/python3.12/site-packages/tensorflow/python/checkpoint/sharding/sharding_util.py__hash__zShardableTensor.__hash__<   s-    DJJDKK(8$:M:MNOO    c                    d| j                   j                   d| j                  d| j                  d| j                  d| j
                  d| j                  d| j                  d| j                  d	| j                  d
| j                  S )N
z:
  _tensor_save_spec=z

  tensor=z	
  dtype=z

  device=z
  name=z	
  shape=z
  slice_spec=z
  checkpoint_key=z
  trackable=)	__class____name__r   r   r   r   r   r   r   r   r   r   s    r    __repr__zShardableTensor.__repr__?   s    (() *##'#9#9"< = 'zzn % 'ii] #zzn % OO. /  $ 3 36 7>>,	. 	/r"   N)r&   
__module____qualname____doc__r   SaveSpec__annotations__
tensor_libTensorr   DType
device_lib
DeviceSpecr   r	   TensorShaper   VariableSaveSliceInfor   	Trackableintr!   r'    r"   r    r   r   (   s     %---


	


)		!	!!  ...^^P P
/ 
/r"   r   z#train.experimental.ShardingCallbackc                       e Zd ZdZeej                  defd              Zej                  de	e
   de	e   fd       ZdefdZy)ShardingCallbacka  Checkpoint sharding callback function, along with a text description.

  A callback function wrapper that will be executed to determine how tensors
  will be split into shards when the saver writes the checkpoint shards to disk.

  The callback takes a list of `tf.train.experimental.ShardableTensor`s as input
  (as well as any kwargs defined by the `tf.train.experimental.ShardingCallback`
  subclass), and organizes the input tensors into different shards. Tensors are
  first organized by device task (see `tf.DeviceSpec`), then the callback will
  be called for each collection of tensors.

  There are a few restrictions to keep in mind when creating a custom callback:
    - Tensors must not be removed from the checkpoint.
    - Tensors must not be reshaped.
    - Tensor dtypes must not change.
    - Tensors within a shard must belong to the same task.
  Validation checks will be performed after the callback function is executed to
  ensure these restrictions aren't violated.

  Here's an example of a simple custom callback:

  ```
  # Place all tensors in a single shard.
  class AllInOnePolicy(tf.train.experimental.ShardingCallback):
    @property
    def description(self):
      return "Place all tensors in a single shard."

    def __call__(self, shardable_tensors):
      tensors = {}
      for shardable_tensor in shardable_tensors:
        tensor = shardable_tensor.tensor_save_spec.tensor
        checkpoint_key = shardable_tensor.checkpoint_key
        slice_spec = shardable_tensor.slice_spec

        tensors.set_default(checkpoint_key, {})[slice_spec] = tensor
      return [tensors]

  ckpt.save(
      "path",
      options=tf.train.CheckpointOptions(
          experimental_sharding_callback=AllInOnePolicy()))
  ```

  The `description` attribute is used to identify the callback and to aid
  debugging during saving and restoration.

  To take in kwargs, simply define the constructor and pass them in:

  ```
  class ParameterPolicy(tf.train.experimental.ShardingCallback):
    def __init__(self, custom_param):
      self.custom_param = custom_param
    ...

  ckpt.save(
      "path",
      options=tf.train.CheckpointOptions(
          experimental_sharding_callback=ParameterPolicy(custom_param=...)))
  ```

  r   c                      y)z2Returns a text description of the sharding policy.Nr7   r   s    r    descriptionzShardingCallback.description   s     	r"   shardable_tensorsc                      y)z9Returns a list of shards for the given shardable tensors.Nr7   )r   r<   s     r    __call__zShardingCallback.__call__   s    
 	r"   c                 $   t        | j                        }t        |       j                         D ]^  \  }}t	        j
                  |      rt	        j                  |      r2|t        |      z  }t        |t              sQ|t        |      z  }` |S r   )	r   r;   varsitemsinspectismethod
isfunction
isinstancer   )r   hash_val	attr_nameattr_vals       r    r!   zShardingCallback.__hash__   s{    D$$%H#Dz//1 %	8x(G,>,>x,HDO#h)
d8n
$(	%
 Or"   N)r&   r(   r)   r*   propertyabcabstractmethodr   r;   r   r   Shardr>   r6   r!   r7   r"   r    r9   r9   L   sp    =~ 	3 	  	 	'8		 	 r"   r9   shardsr<   callback_descriptionr   c                    i }|D ]5  }|j                   |j                  |j                  i       |j                  <   7 t	               }| D ]{  }d}|j                         D ]b  \  }}	|	j                         D ]H  \  }
}|
j                         }
||
f|v rt        d| d| d|
 d      ||vrt        d| d| d|
 d      ||   |
   j                  }|j                  |k7  r%t        d| d| d|
 d| d	|j                   d      ||   |
   j                  }|j                  |k7  r%t        d
| d| d|
 d| d|j                   d      t        j                  j                  ||   |
   j                        j                  }t        j                  j                  |j                        j                  }||k7  rt        d| d| d|
 d| d| d      |t        ddd|j                  dd|
|d	      }nt        j                  j                  |j                        j                  }t        j                  j                  |j                        j                  }|<|:||k7  r5t        d| d|j                   d|j                   d| d| d|
 d| d      ||   |
= ||   s||= |j!                  ||
f       K e ~ |rBd}|j                         D ]  \  }}
|dz  }|d| dz  }|d|
 dz  } t        d| d|       y)z4Validates shards generated by the sharding_callback.NzAfter executing the checkpoint sharding callback, multiple tensors with the same checkpoint key and slice spec were found:
  callback_description: z
  checkpoint_key: z
  slice_spec: r$   zAfter executing the checkpoint sharding callback, a tensor not originally in the object graph was found in the checkpoint shards:
  callback_description: ztAfter executing the checkpoint sharding callback, a tensor was found with an altered shape:
  callback_description: z
  original tensor_shape: z
  new tensor_shape: ztAfter executing the checkpoint sharding callback, a tensor was found with an altered dtype:
  callback_description: z
  original tensor_dtype: z
  new tensor_dtype: zsAfter executing the checkpoint sharding callback, a tensor was found with an altered task:
  callback_description: z
  original tensor_task: z
  new tensor_task: )	r   r   r   r   r   r   r   r   r   zAfter executing the checkpoint sharding callback, tensors with different tasks were found in the same shard:
  callback_description: z!
  tensor #1:    checkpoint_key: z
    slice_spec: z
    task: z!
  tensor #2:    checkpoint_key:  z
  tensor:
z    checkpoint_key: z    slice_spec: zAfter executing the checkpoint sharding callback, tensors in the object graph were not found in the checkpoint shards:
  callback_description: )r   
setdefaultr   r   setrA   stripRuntimeErrorr   r   r0   r1   from_stringr   taskr   add)rM   r<   rN   unseen_tensor_dictshardable_tensorseen_tensor_setshard_tensorstask_tensorr   tensor_slice_dictr   shard_tensortarget_shapetarget_dtypetarget_taskshard_tensor_tasktask1task2tensors_infockpt_keys                       r    validate_shardsrg      s    + A *:)@)@ !!''


%
%'A E/ a:mK-:-@-@-B _:))&7&=&=&? ^:
"*l%%'
 J'?:) *>(> ?##1"2 3)l"./ / !33) *>(> ?##1"2 3)l"./ / *.9*EKK-))=(> ?##1"2 3)l +**6 8%%1%7%7$8<= = *.9*EKK-))=(> ?##1"2 3)l +**6 8%%1%7%7$8<= = !++77~.z:AACCG4 	&11==!!% 	+))=(> ?##1"2 3)l +))4 6$$5#6b:; ; ' $!((#+	+ ''33K4F4FGLL%''33L4G4GHMM%5#4%++?*@ A''2'A'A&B C##.#9#9": ;"G $''5&6 7##-, /"G2
'( ( ~.z:!.1 0^Z89}^:_:a:H L 2 8 8 : 8*m#l,XJb99l(B77l8 	##7"8.	  r"   )"r*   rJ   dataclassesrB   typingr   r   r   tensorflow.python.frameworkr   r0   r   r   r-   r	   r
   tensorflow.python.opsr   tensorflow.python.trackabler   !tensorflow.python.training.savingr   tensorflow.python.utilr   
TensorSpecr.   TensorSlicesr   rL   	dataclassr   ABCr9   rg   r7   r"   r    <module>rs      s   = 
   5 5 < . < 4 3 + , = , k44j6G6GGH 	sL() 9:d#/ / $ ;/D :;Usww U <Up{UO{0{ { 
	{r"   