
    BVhD*                     <   d 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 g a G d
 d      Zej$                  d        Zd Z G d de      Z G d dej.                  e      Z ed       G d de             Z G d de      Zy)z7Definitions for resource-type trackable object classes.    N)context)def_function)ops)tensor)base)tf_contextlib)	tf_exportc                   2    e Zd ZdZdgZd Zed        Zd Zy)ResourceTrackerz*An object that tracks a list of resources.
_resourcesc                     g | _         y Nr   selfs    T/home/dcms/DCMS/lib/python3.12/site-packages/tensorflow/python/trackable/resource.py__init__zResourceTracker.__init__&   s	    DO    c                     | j                   S r   r   r   s    r   	resourceszResourceTracker.resources)   s    ??r   c                 :    | j                   j                  |       y r   )r   append)r   resources     r   add_resourcezResourceTracker.add_resource-   s    OO8$r   N)	__name__
__module____qualname____doc__	__slots__r   propertyr   r    r   r   r   r   !   s*    2n)  %r   r   c              #   p   K   t        t              }t        j                  |        	 d |ay# |aw xY ww)a  A context to manage resource trackers.

  Use this in order to collect up all resources created within a block of code.
  Example usage:

  ```python
  resource_tracker = ResourceTracker()
  with resource_tracker_scope(resource_tracker):
    resource = TrackableResource()

  assert resource_tracker.resources == [resource]

  Args:
    resource_tracker: The passed in ResourceTracker object

  Yields:
    A scope in which the resource_tracker is active.
  N)list_RESOURCE_TRACKER_STACKr   )resource_trackerolds     r   resource_tracker_scoper'   1   s6     * 	$%#  !12"	!cs   %6/ 636c                       fd}|S )z"To avoid capturing loop variables.c                       g| i |S r   r!   )argskwargscaptured_gettercaptured_previouss     r   getterz_make_getter.<locals>.getterQ   s    ,>t>v>>r   r!   )r,   r-   r.   s   `` r   _make_getterr/   N   s    ? 
-r   c                       e Zd ZdZd Zy)_ResourceMetaclassz!Metaclass for CapturableResource.c                       fdfd}t        j                         j                  }| j                            D ]  }t	        ||      }  ||i |S )Nc                 `    | J  j                   g|i |} |j                  |i | |S r   )__new__r   )next_creatorakwobjclss       r   default_resource_creatorz=_ResourceMetaclass.__call__.<locals>.default_resource_creator\   sA    !!!CKK&a&2&ccllAjr   c                       d g| i |S r   r!   )r6   r7   r:   s     r   <lambda>z-_ResourceMetaclass.__call__.<locals>.<lambda>b   s    '?'Oq'OB'O r   )r   get_default_graph_resource_creator_stack_resource_typer/   )r9   r*   r+   previous_getterresource_creator_stackr.   r:   s   `     @r   __call__z_ResourceMetaclass.__call__Z   s`     PO 224LL(););)=> >$V_=o> D+F++r   N)r   r   r   r   rB   r!   r   r   r1   r1   W   s
    ),r   r1   c                        e Zd ZdZddZed        Zed        Zej                  d        Zd Z
ed        Zej                  d        Zd	 Zd
 Zed        Zd Zej"                  j$                  f fd	Zd Z xZS )CapturableResourceaz  Holds a Tensor which a tf.function can capture.

  `CapturableResource`s are discovered by traversing the graph of object
  attributes, e.g. during `tf.saved_model.save`. They are excluded from the
  scope-based tracking of `TrackableResource`; generally things that require
  initialization should inherit from `TrackableResource` instead of
  `CapturableResource` directly.
  c                     d| _         || _        t        j                         rt        j                  | _        yt        j                         j                  | _        y)ad  Initialize the `CapturableResource`.

    Args:
      device: A string indicating a required placement for this resource,
        e.g. "CPU" if this resource must be created on a CPU device. A blank
        device allows the user to place resource creation, so generally this
        should be blank unless the resource only makes sense on one device.
    N)	_resource_handle_value_resource_devicer   executing_eagerly
eager_moder   r=   
as_default_self_destruction_context)r   devices     r   r   zCapturableResource.__init__t   sJ     #'D"D%779 	"""$// 	"r   c                     | j                   S r   )r   )r9   s    r   r?   z!CapturableResource._resource_type   s    <<r   c                 8    t        | dt        j                        S )NrK   )getattr
contextlibsuppressr   s    r   _destruction_contextz'CapturableResource._destruction_context   s    44&&( (r   c                     || _         y r   )rK   )r   destruction_contexts     r   rR   z'CapturableResource._destruction_context   s
    %8D"r   c                     t        d      )z*A function that creates a resource handle.z3TrackableResource._create_resource not implemented.)NotImplementedErrorr   s    r   _create_resourcez#CapturableResource._create_resource   s    
 - . .r   c                     | j                   S r   )rF   r   s    r   _resource_handlez#CapturableResource._resource_handle   s    &&&r   c                     t        |t        j                  t        j                  f      rt        j                  |       |_        || _        y r   )	
isinstancer   Tensorr   EagerTensorweakrefref_parent_trackablerF   )r   values     r   rY   z#CapturableResource._resource_handle   s2    %&--9: 'D 1e"'Dr   c                      y)z3A function that initializes the resource. Optional.Nr!   r   s    r   _initializezCapturableResource._initialize       r   c                      y)z0A function that destroys the resource. Optional.Nr!   r   s    r   _destroy_resourcez$CapturableResource._destroy_resource   rd   r   c                     | j                   It        j                  | j                        5  | j	                         | _         ddd       | j                   S | j                   S # 1 sw Y   | j                   S xY w)z:Returns the resource handle associated with this Resource.N)rY   r   rL   rG   rW   r   s    r   resource_handlez"CapturableResource.resource_handle   sf     $::d++, 8 $ 5 5 78   4   8   s   A""A6c                    t        j                   |       }t        j                  | j                        5  |j	                         }ddd       |_        ||| <   ||| j                  <   | j                  gS # 1 sw Y   1xY w)zFor implementing `Trackable`.N)copyr   rL   rG   rW   rY   rh   )r   
object_map
tensor_mapunused_kwargsnew_objnew_resources         r   _export_to_saved_model_graphz/CapturableResource._export_to_saved_model_graph   sw     iioG	D))	* 0--/l0+GJt'3Jt##$  !!0 0s   A66A?c                     t           |fi |}|dk(  rrt        j                  g d       fd       }t        j                  g d       fd       }t        j                  g d       fd       }|j	                  |||d       |S )N
savedmodelF)input_signature	autographc                  (    j                         } | S r   )rW   )r   r   s    r   _creatorz8CapturableResource._trackable_children.<locals>._creator   s    ((*r   c                  &     j                          yN   )rc   r   s   r   _initializerz<CapturableResource._trackable_children.<locals>._initializer   s    r   c                  &     j                          yrx   )rf   r   s   r   
_destroyerz:CapturableResource._trackable_children.<locals>._destroyer   s     r   )rW   rc   rf   )super_trackable_childrenr   functionupdate)r   	save_typer+   childrenrv   rz   r|   	__class__s   `      r   r~   z&CapturableResource._trackable_children   s    w*9??HL R5A B R5A B R5A B oo&%) 	
 Or   c                     	 | j                         5  | j                          d d d        y # 1 sw Y   y xY w# t        $ r Y y w xY wr   )rR   rf   	Exceptionr   s    r   __del__zCapturableResource.__del__   sM     $$& ! 	 ! ! !   s#   8 ,8 58 8 	AA )r   r   r   r   r   classmethodr?   r    rR   setterrW   rY   rc   rf   rh   rp   r   SaveType
CHECKPOINTr~   r   __classcell__r   s   @r   rD   rD   j   s    1   ( (
 9 9.
 ' ' ( (
		 ! !" +/--*B*B 2r   rD   )	metaclassz*saved_model.experimental.TrackableResourcec                   $     e Zd ZdZd fd	Z xZS )TrackableResourceai  Holds a Tensor which a tf.function can capture.

  A TrackableResource is most useful for stateful Tensors that require
  initialization, such as `tf.lookup.StaticHashTable`. `TrackableResource`s
  are discovered by traversing the graph of object attributes, e.g. during
  `tf.saved_model.save`.

  A TrackableResource has three methods to override:

  * `_create_resource` should create the resource tensor handle.
  * `_initialize` should initialize the resource held at `self.resource_handle`.
  * `_destroy_resource` is called upon a `TrackableResource`'s destruction
    and should decrement the resource's ref count. For most resources, this
    should be done with a call to `tf.raw_ops.DestroyResourceOp`.

  Example usage:

  >>> class DemoResource(tf.saved_model.experimental.TrackableResource):
  ...   def __init__(self):
  ...     super().__init__()
  ...     self._initialize()
  ...   def _create_resource(self):
  ...     return tf.raw_ops.VarHandleOp(dtype=tf.float32, shape=[2])
  ...   def _initialize(self):
  ...     tf.raw_ops.AssignVariableOp(
  ...         resource=self.resource_handle, value=tf.ones([2]))
  ...   def _destroy_resource(self):
  ...     tf.raw_ops.DestroyResourceOp(resource=self.resource_handle)
  >>> class DemoModule(tf.Module):
  ...   def __init__(self):
  ...     self.resource = DemoResource()
  ...   def increment(self, tensor):
  ...     return tensor + tf.raw_ops.ReadVariableOp(
  ...         resource=self.resource.resource_handle, dtype=tf.float32)
  >>> demo = DemoModule()
  >>> demo.increment([5, 1])
  <tf.Tensor: shape=(2,), dtype=float32, numpy=array([6., 2.], dtype=float32)>
  c                 ^    t         D ]  }|j                  |         t        |   |       y)ac  Initialize the `TrackableResource`.

    Args:
      device: A string indicating a required placement for this resource,
        e.g. "CPU" if this resource must be created on a CPU device. A blank
        device allows the user to place resource creation, so generally this
        should be blank unless the resource only makes sense on one device.
    rL   N)r$   r   r}   r   )r   rL   r%   r   s      r   r   zTrackableResource.__init__  s3     4 *##D)*	GF#r   r   )r   r   r   r   r   r   r   s   @r   r   r      s    %N$ $r   r   c                   :     e Zd ZdZd fd	Zed        Zd Z xZS )RestoredResourcezRestored SavedResource.c                 &    t         |   |       y )Nr   )r}   r   )r   rL   r   s     r   r   zRestoredResource.__init__%  s    	GF#r   c                 t     | |j                   j                        }|j                  d      }|||_        |S )Nr   rW   )r   rL   getrW   )r9   object_protodependenciesrm   r8   resource_creators         r   _deserialize_from_protoz(RestoredResource._deserialize_from_proto(  s=    
\**11
2C#''(:;#-cJr   c                     t        | ||       t        |t        j                        r.t        |t        j
                        s| j                  ||       y y y r   )setattrr[   r   	Trackabler   Function_track_trackable)r   namera   s      r   _add_trackable_childz%RestoredResource._add_trackable_child0  sF    D$5$..)ul334
E4( 5 	*r   r   )	r   r   r   r   r   r   r   r   r   r   s   @r   r   r   "  s$    $  )r   r   )r   rP   rj   r^   tensorflow.python.eagerr   r   tensorflow.python.frameworkr   r   tensorflow.python.trackabler   tensorflow.python.utilr    tensorflow.python.util.tf_exportr	   r$   r   contextmanagerr'   r/   typer1   r   rD   r   r   r!   r   r   <module>r      s    >    + 0 + . , 0 6  % %  " "8, ,&|3E |~ 784$* 4$ 94$p)( )r   