a
    0Sic                     @   s  d 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 ejZejZejZejZedg dG dd deZG dd deZedddgZedg dG dd deZedg dG dd dejZG dd dejZ edg dZ!edg dd d! Z"ej#d"d# Z$ej#d$d% Z%ed&g dG d'd( d(eZ&dS ))z+An object-local variable management scheme.    N)context)dtypes)ops)control_flow_ops)	constants)saveable_object)tf_contextlib)tf_decorator)	tf_exportz(__internal__.tracking.TrackableReference)v1c                   @   sL   e Zd ZdZdZdd Zedd Zedd Zd	d
 Z	dd Z
dd ZdS )TrackableReferencea[  A named reference to a trackable object for use with the `Trackable` class.

  These references mark named `Trackable` dependencies of a `Trackable` object
  and should be created when overriding `Trackable._checkpoint_dependencies`.

  Attributes:
    name: The local name for this dependency.
    ref: The `Trackable` object being referenced.
  _name_refc                 C   s   || _ || _d S Nr   selfnameref r   \/var/www/html/django/DPS/env/lib/python3.9/site-packages/tensorflow/python/trackable/base.py__init__1   s    zTrackableReference.__init__c                 C   s   | j S r   )r   r   r   r   r   r   5   s    zTrackableReference.namec                 C   s   | j S r   r   r   r   r   r   r   9   s    zTrackableReference.refc                 c   s   | j V  | jV  d S r   r   r   r   r   r   r   __iter__=   s    zTrackableReference.__iter__c                 C   s   | j j d| j d| j dS )Nz(name=z, ref=))	__class____name__r   r   r   r   r   r   __repr__A   s    zTrackableReference.__repr__c                 C   sD   t |tr| j| jf|kS t |tr<| j|jko:| j|jkS dS d S )NF)
isinstancetupler   r   r   )r   or   r   r   __eq__D   s
    

zTrackableReference.__eq__N)r   
__module____qualname____doc__	__slots__r   propertyr   r   r   r   r#   r   r   r   r   r   #   s   


r   c                       s0   e Zd ZdZdZ fddZedd Z  ZS )WeakTrackableReferencez/TrackableReference that stores weak references.r   c                    s.   t | tjst|}tt| j||d d S )Nr   )r    weakrefr   superr)   r   r   r   r   r   r   Q   s    
zWeakTrackableReference.__init__c                 C   s   |   S r   r   r   r   r   r   r   V   s    zWeakTrackableReference.ref)	r   r$   r%   r&   r'   r   r(   r   __classcell__r   r   r,   r   r)   M   s
   r)   ZCheckpointInitialValueShardInfoshapeoffsetz4__internal__.tracking.CheckpointInitialValueCallablec                   @   s:   e Zd ZdZdd Zedd ZdddZed	d
 ZdS )CheckpointInitialValueCallablezoA callable object that returns a CheckpointInitialValue.

  See CheckpointInitialValue for more information.
  c                 C   s
   || _ d S r   _checkpoint_position)r   checkpoint_positionr   r   r   r   g   s    z'CheckpointInitialValueCallable.__init__c                 C   s   | j S r   r1   r   r   r   r   r3   j   s    z2CheckpointInitialValueCallable.checkpoint_positionNc                 C   s   t | j||dS )N)
shard_info)CheckpointInitialValuer2   )r   r.   dtyper4   r   r   r   __call__n   s    z'CheckpointInitialValueCallable.__call__c                 C   s   | j jS r   )r2   restore_uidr   r   r   r   r8   v   s    z*CheckpointInitialValueCallable.restore_uid)NNN)	r   r$   r%   r&   r   r(   r3   r7   r8   r   r   r   r   r0   `   s   

r0   z,__internal__.tracking.CheckpointInitialValuec                   @   s.   e Zd ZdZd	ddZdd Zedd ZdS )
r5   a+  Tensor wrapper for managing update UIDs in `Variables`.

  When supplied as an initial value, objects of this type let a `Variable`
  (`Variable`, `ResourceVariable`, etc.) know the UID of the restore the initial
  value came from. This allows deferred restorations to be sequenced in the
  order the user specified them, and lets us fall back on assignment if an
  initial value is not set (e.g. due to a custom getter interfering).

  See comments in _add_variable_with_custom_getter for more information about
  how `CheckpointInitialValue` is used.
  Nc                 C   sf   |rDd dd |D d }d dd t|j|jD }|| }nd}|t|it | _|| _d S )N c                 s   s   | ]}d | V  qdS )z%dNr   ).0dr   r   r   	<genexpr>       z2CheckpointInitialValue.__init__.<locals>.<genexpr>:c                 s   s   | ]\}}d ||f V  qdS )z%d,%dNr   )r:   r"   sr   r   r   r<      s    )joinzipr/   r.   Zvalue_tensorsVARIABLE_VALUE_KEYwrapped_valuer2   )r   r3   r.   r4   Zfull_shape_str
slice_specZshape_and_slicer   r   r   r      s    

zCheckpointInitialValue.__init__c                 C   s0   zt | j|W S  ty*   | | Y S 0 d S r   )getattrrD   AttributeError__getattribute__)r   attrr   r   r   __getattr__   s    z"CheckpointInitialValue.__getattr__c                 C   s   | j S r   r1   r   r   r   r   r3      s    z*CheckpointInitialValue.checkpoint_position)NN)r   r$   r%   r&   r   rJ   r(   r3   r   r   r   r   r5   {   s
   
r5   c                       s*   e Zd ZdZd fdd	Zdd Z  ZS )NoRestoreSaveablez4Embeds a tensor in a checkpoint with no restore ops.Nc                    s.   t j|d|||d}tt| ||g| d S )Nr@   )r6   device)r   SaveSpecr+   rK   r   )r   tensorr   r6   rL   specr,   r   r   r      s    
zNoRestoreSaveable.__init__c                 C   s   t  S r   )r   no_op)r   restored_tensorsrestored_shapesr   r   r   restore   s    zNoRestoreSaveable.restore)NN)r   r$   r%   r&   r   rS   r-   r   r   r,   r   rK      s   rK   _SlotVariableRestoration)Zoptimizer_idZslot_variable_idZ	slot_namez6__internal__.tracking.no_automatic_dependency_trackingc                    s    fdd}t j |dS )aS  Disables automatic dependency tracking on attribute assignment.

  Use to decorate any method of a Trackable object. Attribute assignment in
  that method will not add dependencies (also respected in Model). Harmless if
  used in a class which does not do automatic dependency tracking (which means
  it's safe to use in base classes which may have subclasses which also inherit
  from Trackable).

  Args:
    method: The method to decorate.

  Returns:
    A decorated method which sets and un-sets automatic dependency tracking for
    the object the method is called on (not thread safe).
  c                    s@   t | dd}d| _z  | g|R i |}W || _n|| _0 |S )N_self_setattr_trackingTF)rF   rU   )r   argskwargsprevious_valueresultmethodr   r   _method_wrapper   s    z9no_automatic_dependency_tracking.<locals>._method_wrapper)targetdecorator_func)r	   make_decorator)r[   r\   r   rZ   r    no_automatic_dependency_tracking   s    	r`   c                 c   s0   t | dd}d| _zdV  W || _n|| _0 dS )a  A context that disables manual dependency tracking for the given `obj`.

  Sometimes library methods might track objects on their own and we might want
  to disable that and do the tracking on our own. One can then use this context
  manager to disable the tracking the library method does and do your own
  tracking.

  For example:

  class TestLayer(tf.keras.Layer):
    def build():
      with no_manual_dependency_tracking_scope(self):
        var = self.add_variable("name1")  # Creates a var and doesn't track it
      self._track_trackable("name2", var)  # We track variable with name `name2`

  Args:
    obj: A trackable object.

  Yields:
    a scope in which the object doesn't track dependencies manually.
  _manual_trackingTFN)rF   ra   objrX   r   r   r   #no_manual_dependency_tracking_scope   s
    rd   c                 c   s0   t | dd}d| _zdV  W || _n|| _0 dS )a  A context that disables automatic dependency tracking when assigning attrs.

  Objects that inherit from Autotrackable automatically creates dependencies
  to trackable objects through attribute assignments, and wraps data structures
  (lists or dicts) with trackable classes. This scope may be used to temporarily
  disable this behavior. This works similar to the decorator
  `no_automatic_dependency_tracking`.

  Example usage:
  ```
  model = tf.keras.Model()
  model.arr1 = []  # Creates a ListWrapper object
  with no_automatic_dependency_tracking_scope(model):
    model.arr2 = []  # Creates a regular, untracked python list
  ```

  Args:
    obj: A trackable object.

  Yields:
    a scope in which the object doesn't track dependencies.
  _setattr_trackingTFN)rF   re   rb   r   r   r   &no_automatic_dependency_tracking_scope   s
    rf   z__internal__.tracking.Trackablec                   @   sB  e Zd ZdZedd Zejdd Zedd Zej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edd Zedd Zdd ZdejdddfddZd d! Zd:d"d#Zd$d% Zd&d' Zd(d) Zd*d+ Zd,d- Zd;d.d/Zed<d0d1Zd2d3 Z d4d5 Z!e"j#dfd6d7Z$d=d8d9Z%dS )>	Trackablea0  Base class for `Trackable` objects without automatic dependencies.

  This class has no __setattr__ override for performance reasons. Dependencies
  must be added explicitly. Unless attribute assignment is performance-critical,
  use `AutoTrackable` instead. Use `Trackable` for `isinstance`
  checks.
  c                 C   s   t | dsd| _| jS )NrU   T)hasattrrU   r   r   r   r   re   $  s    
zTrackable._setattr_trackingc                 C   s
   || _ d S r   )rU   r   valuer   r   r   re   *  s    c                 C   s   | j S r   _self_update_uidr   r   r   r   _update_uid.  s    zTrackable._update_uidc                 C   s
   || _ d S r   rk   ri   r   r   r   rm   2  s    c                 C   s   | j S r   +_self_unconditional_checkpoint_dependenciesr   r   r   r   &_unconditional_checkpoint_dependencies6  s    z0Trackable._unconditional_checkpoint_dependenciesc                 C   s   | j S r   )$_self_unconditional_dependency_namesr   r   r   r   _unconditional_dependency_names:  s    z)Trackable._unconditional_dependency_namesc                 C   s   | j S r   )_self_name_based_restoresr   r   r   r   _name_based_restores>  s    zTrackable._name_based_restoresc                 C   sJ   t | drdS g | _i | _i | _t | dr2tdd| _t | _i | _dS )zdInitialize dependency management.

    Not __init__, since most objects will forget to call it.
    ro   Nrl   zXInternal error: the object had an update UID set before its initialization code was run.)	rh   ro   rq   )_self_unconditional_deferred_dependenciesAssertionErrorrl   setrs   _self_saveable_object_factoriesr   r   r   r   _maybe_initialize_trackableF  s    

z%Trackable._maybe_initialize_trackablec                 C   s   dS )ab  String used to identify this object in a SavedModel.

    THIS FIELD HAS BEEN DEPRECATED IN FAVOR OF THE NAME REGISTERED WITH
    `register_serializable`.

    Generally, the object identifier is constant across objects of the same
    class, while the metadata field is used for instance-specific data.

    Returns:
      String object identifier.
    Z_generic_user_objectr   r   r   r   r   _object_identifierr  s    zTrackable._object_identifierc                 C   s   |S )z=If automatic dependency tracking is enabled, ignores `value`.r   ri   r   r   r   _no_dependency  s    zTrackable._no_dependencyc                 C   s.   | j | | j|jk r*||  |j| _dS )z=Restore the object's attributes from a name-based checkpoint.N)rs   addrl   r8   Zeager_restore)r   
checkpointr   r   r   _name_based_attribute_restore  s    
z'Trackable._name_based_attribute_restorec                 C   s   | j S )a   All dependencies of this object.

    May be overridden to include conditional dependencies.

    Returns:
      A list of `TrackableReference` objects indicating named
      `Trackable` dependencies which should be saved along with this
      object.
    rn   r   r   r   r   _checkpoint_dependencies  s    z"Trackable._checkpoint_dependenciesc                 C   s   | j S )a  A dictionary with deferred dependencies.

    Stores restorations for other Trackable objects on which this object
    may eventually depend. May be overridden by sub-classes (e.g. Optimizers use
    conditional dependencies based the current graph, and so need separate
    management of deferred dependencies too).

    Returns:
      A dictionary mapping from local name to a list of CheckpointPosition
      objects.
    )rv   r   r   r   r   _deferred_dependencies  s    z Trackable._deferred_dependenciesc                 C   s   | j |dS )zLook up a dependency by name.

    May be overridden to include conditional dependencies.

    Args:
      name: The local name of the dependency.

    Returns:
      A `Trackable` object, or `None` if no dependency by this name was
      found.
    N)rq   get)r   r   r   r   r   _lookup_dependency  s    zTrackable._lookup_dependencyNFc           
      K   s   |    t L t r(| j|d}nd}|durNt|trJ|j|jksN|}W d   n1 sb0    Y  |f ||||d|}	|rt|	t	r| j
|	||dS |	S dS )a  Restore-on-create for a variable be saved with this `Trackable`.

    If the user has requested that this object or another `Trackable` which
    depends on this object be restored from a checkpoint (deferred loading
    before variable object creation), `initializer` may be ignored and the value
    from the checkpoint used instead.

    Args:
      name: A name for the variable. Must be unique within this object.
      shape: The shape of the variable.
      dtype: The data type of the variable.
      initializer: The initializer to use. Ignored if there is a deferred
        restoration stored in the Trackable.
      getter: The getter to wrap which actually fetches the variable.
      overwrite: If True, disables unique name and type checks.
      **kwargs_for_getter: Passed to the getter.

    Returns:
      The new variable object.

    Raises:
      ValueError: If the variable name is not unique.
    r   N)r   r.   r6   initializer)r   	overwrite)rz   r   
init_scoper   executing_eagerly_preload_simple_restorationr    r0   r8   rg   _track_trackable)
r   r   r.   r6   r   getterr   Zkwargs_for_getterZcheckpoint_initializerZnew_variabler   r   r    _add_variable_with_custom_getter  s,    

	"z*Trackable._add_variable_with_custom_getterc                 C   sH   | j |d}|sdS |D ]}| s dS qt|dd d}t|dS )a!  Return a dependency's value for restore-on-create.

    Note the restoration is not deleted; if for some reason preload is called
    and then not assigned to the variable (for example because a custom getter
    overrides the initializer), the assignment will still happen once the
    variable is tracked (determined based on checkpoint.restore_uid).

    Args:
      name: The object-local name of the dependency holding the variable's
        value.

    Returns:
      An callable for use as a variable's initializer/initial_value, or None if
      one should not be set (either because there was no variable with this name
      in the checkpoint or because it needs more complex deserialization). Any
      non-trivial deserialization will happen when the variable object is
      tracked.
    r   Nc                 S   s   | j jS r   r~   r8   rS   r   r   r   <lambda>  r=   z7Trackable._preload_simple_restoration.<locals>.<lambda>)key)r3   )r   r   Zis_simple_variablemaxr0   )r   r   deferred_dependencies_listr3   r   r   r   r     s    z%Trackable._preload_simple_restorationc           	      C   s   |    t|ts&tdt| dt| dds6|S t||d}| |}|dur||ur|sptd| dt	| j
D ]\}\}}||krz|| j
|< qzn"|du r| j
| | j||d	 || j|< |S )
aA  Declare a dependency on another `Trackable` object.

    Indicates that checkpoints for this object should include variables from
    `trackable`.

    Variables in a checkpoint are mapped to `Trackable`s based on the names
    provided when the checkpoint was written. To avoid breaking existing
    checkpoints when modifying a class, neither variable names nor dependency
    names (the names passed to `_track_trackable`) may change.

    Args:
      trackable: A `Trackable` which this object depends on.
      name: A local name for `trackable`, used for loading checkpoints into the
        correct objects.
      overwrite: Boolean, whether silently replacing dependencies is OK. Used
        for __setattr__, where throwing an error on attribute reassignment would
        be inappropriate.

    Returns:
      `trackable`, for convenience when declaring a dependency and
      assigning to a member variable in one statement.

    Raises:
      TypeError: If `trackable` does not inherit from `Trackable`.
      ValueError: If another object is already tracked by this name.
    z[Trackable._track_trackable() can only be used to track objects of type Trackable. Got type .ra   Tr   Nz/Called Trackable._track_trackable() with name='zp', but a Trackable with this name is already declared as a dependency. Names must be unique (or overwrite=True).)r   	trackable)rz   r    rg   	TypeErrortyperF   r   r   
ValueError	enumeratero   append_handle_deferred_dependenciesrq   )	r   r   r   r   Znew_referenceZcurrent_objectindexold_name_r   r   r   r     s:    



zTrackable._track_trackablec                 C   sh   |    |   | j|d}t|dd ddD ]}|| q0t| jdd ddD ]}|| qTdS )a  Pop and load any deferred checkpoint restores into `trackable`.

    This method does not add a new dependency on `trackable`, but it does
    check if any outstanding/deferred dependencies have been queued waiting for
    this dependency to be added (matched based on `name`). If so,
    `trackable` and its dependencies are restored. The restorations are
    considered fulfilled and so are deleted.

    `_track_trackable` is more appropriate for adding a
    normal/unconditional dependency, and includes handling for deferred
    restorations. This method allows objects such as `Optimizer` to use the same
    restoration logic while managing conditional dependencies themselves, by
    overriding `_checkpoint_dependencies` and `_lookup_dependency` to change the
    object's dependencies based on the context it is saved/restored in (a single
    optimizer instance can have state associated with multiple graphs).

    Args:
      name: The name of the dependency within this object (`self`), used to
        match `trackable` with values saved in a checkpoint.
      trackable: The Trackable object to restore (inheriting from `Trackable`).
    r   c                 S   s   | j jS r   r   r   r   r   r   r   q  r=   z9Trackable._handle_deferred_dependencies.<locals>.<lambda>T)r   reversec                 S   s   | j S r   )r8   )r~   r   r   r   r   x  r=   N)rz   r   popsortedrS   rs   r   )r   r   r   r   r3   Zname_based_restorer   r   r   r   V  s    

z'Trackable._handle_deferred_dependenciesc                    s>   ddl m   r.d fdd	}d|iS tdi S dS )	a  Returns a dictionary of values to checkpoint with this object.

    NOTE: This method is deprecated, please use `_serialize_to_tensors` and
    `_restore_from_tensors` instead.

    Keys in the returned dictionary are local to this object and in a separate
    namespace from dependencies. Values may either be `SaveableObject` factories
    or variables easily converted to `SaveableObject`s (as in
    `tf.compat.v1.train.Saver`'s
    `var_list` constructor argument).

    `SaveableObjects` have a name set, which Trackable needs to generate
    itself. So rather than returning `SaveableObjects` directly, this method
    should return a dictionary of callables which take `name` arguments and
    return `SaveableObjects` with that name.

    If this object may also be passed to the global-name-based
    `tf.compat.v1.train.Saver`,
    the returned callables should have a default value for their name argument
    (i.e. be callable with no arguments).

    Returned values must be saved only by this object; if any value may be
    shared, it should instead be a dependency. For example, variable objects
    save their own values with the key `VARIABLE_VALUE_KEY`, but objects which
    reference variables simply add a dependency.

    Returns:
      The dictionary mapping attribute names to `SaveableObject` factories
      described above. For example:
      {VARIABLE_VALUE_KEY:
       lambda name="global_name_for_this_object":
       SaveableObject(name=name, ...)}
    r   )saveable_object_utilr@   c                    s     | S r   )ZTrackableSaveabler   r   r   r   r   create_saveable  s    zCTrackable._gather_saveables_for_checkpoint.<locals>.create_saveablery   N)r@   )!tensorflow.python.training.savingr   Z!trackable_has_serialize_to_tensorrF   )r   r   r   r   r    _gather_saveables_for_checkpoint|  s
    %
z*Trackable._gather_saveables_for_checkpointc                 C   s   t dS )a  Gathers tensors to save to the checkpoint.

    You should only override `_serialize_to_tensors` and `_restore_from_tensors`
    if you are defining a custom resource or variable with custom ops.

    Otherwise, please store the state of your trackable in `tf.Variable` objects
    and add them to Trackable object hierarchy using `setattr` (for subclasses
    of `AutoTrackable`) or overriding the `_trackable_children` method.

    For an example of a valid implementation of these two methods, please see
    `DenseHashTable`.

    **Invalid implementation**

    ````
    class NamedTrackable(Trackable):
      def __init__(self, name: str):
        self.name = name
      def _serialize_to_tensors(self):
        return {"name": self.name}
      def _restore_from_tensors(self, restored_tensors):
        self.name = restored_tensors["name"]
    ```

    In this example, `NamedTrackable` can be saved and restored from
    checkpoints, but is incompatible with SavedModel, which tries to convert
    the serialize/restore functions into tf.functions. This fails because
    attribute assignment (`self.attr = new_value`) is not graph-friendly.

    **Suggested fix**

    ```
    class NamedTrackable(Trackable):
      def __init__(self, name: str):
        self.name = tf.Variable(name)

      def _trackable_children(self):
        return {"name": self.name}
    ```

    If the `name` attribute should be saved to the checkpoint, then convert it
    a `tf.Variable`.

    Returns:
      A dictionary mapping names to tensors.
    NNotImplementedErrorr   r   r   r   _serialize_to_tensors  s    /zTrackable._serialize_to_tensorsc                 C   s   t dS )aU  Restores checkpointed values to this `Trackable`.

    Please see the documentation for `Trackable._serialize_to_tensors`.

    Args:
      restored_tensors: A dictionary mapping names to tensors. The keys to this
        dictionary matches the names passed to _serialize_to_tensors.

    Returns:
      An op that runs the restoration.
    Nr   )r   rQ   r   r   r   _restore_from_tensors  s    zTrackable._restore_from_tensorsc                 C   s   i i fS )a	  Makes new resource handle ops corresponding to existing resource tensors.

    Internal sub-classes can override this to inform model saving how to add new
    resource handle ops to the main GraphDef of a SavedModel (TF 1.x style
    graph), which allows session based APIs (e.g, C++ loader API) to interact
    with resources owned by this object.

    Args:
      save_options: A tf.saved_model.SaveOptions instance.

    Returns:
      A tuple of (object_map, resource_map):
        object_map: A dictionary mapping from objects that hold existing
          resource tensors to replacement objects created to hold the new
          resource tensors.
        resource_map: A dictionary mapping from existing resource tensors to
          newly created resource tensors.
    r   )r   save_optionsr   r   r   _map_resources  s    zTrackable._map_resourcesc                 K   s   ~~dS )aQ  Returns a proto of any type to be saved into the SavedModel.

    Trackable classes decorated with `register_serializable` should overwrite
    this method to save metadata for this object to the SavedModel. The proto
    returned by this function will be passed to `_deserialize_from_proto` in the
    form of a `google.protobuf.Any` proto.

    This data is only saved and used by the Python API. Existing C++ loading
    APIs such as `tensorflow::LoadSavedModel` will not read this field at all.

    Args:
      object_proto: A `SavedObject` proto that may be filled by this function.
        Only the core serializable types (Variable, Function, Constant, Asset)
        should modify this argument.
      **kwargs: Future keyword arguments passed to the object during saving.

    Returns:
      A proto that serializes this class's type.
    Nr   )r   object_protorW   r   r   r   _serialize_to_proto   s    zTrackable._serialize_to_protoc                 K   s   ~~~~~~~|  S )a	  Returns a new object restored by the SavedModel.

    Trackable classes decorated with `register_serializable` should overwrite
    this method to change how the object is loaded from SavedModel. By default,
    the object is initialized with no arguments.

    Example:

    ```
    def _serialize_to_proto(self, **unused_kwargs):
      return Message(name="a")

    @classmethod
    def _deserialize_from_proto(cls, proto, **unused_kwargs):
      if proto.Is(Message.DESCRIPTOR):
        unpacked = Message()
        proto.Unpack(unpacked)
        return cls(unpacked.name)
      else:
        return cls()
    ```

    This function is only used by the Python API. C++ and TensorFlow Serving do
    not have access to your registered class and cannot execute any of the
    non-tf.functions attached to the Python class. However, all signatures and
    tf.functions are still accessible.

    **Avoid creating duplicate trackables**

    SavedModel is saved by recursively gathering all of the trackables and their
    children. SavedModel loading reverses those steps by creating all
    trackables, then reconnecting the children trackables to their parents using
    `Trackable._add_trackable_child`.

    That means that if `_deserialize_from_proto` calls the `__init__` function,
    which creates all of the children trackables, then those children end up
    being created *twice*.

    To avoid this, structure your code so that Trackables are not created
    when deserialized from SavedModel:

    ```
    @register_serializable()
    class Serializable(trackable):
      def __init __(self, from_proto=False):
        create_non_trackable_objects()
        if not from_proto:
          create_variables_and_other_trackables()

      def _deserialize_from_proto(cls, **kwargs):
        return cls(from_proto=True)

      def _add_trackable_child(self, name, value):
        self.__setattr__(name, value)
    ```

    Args:
      proto: A `google.protobuf.Any` proto read from the `SavedModel`.
      dependencies: A dictionary mapping names to dependencies (see
        `_deserialization_dependencies`)
      object_proto: The `SavedObject` proto for this object.
      export_dir: The `SavedModel` directory
      asset_file_def: The `MetaGraphDef`'s `asset_file_def` field.
      operation_attributes: Dictionary mapping nodes to attribute from the
        imported `GraphDef`.
      **kwargs: Future keyword arguments passed to the object when loading.

    Returns:
      A new object.
    r   )clsprotodependenciesr   Z
export_dirZasset_file_defZoperation_attributesrW   r   r   r   _deserialize_from_proto  s    O
z!Trackable._deserialize_from_protoc                 C   s   | j ||dd dS )a  Restores a connection between trackables when loading from SavedModel.

    SavedModel stores both the object metadata and its list of children. When
    loading, this function is used along with `_deserialize_from_proto` to load
    objects from the SavedModel: First, all saved objects are created with
    `_deserialize_from_proto`. After that is complete, the children are
    connected using `_add_trackable_child`.

    **Example**

    `tf.Module`, `tf.keras.Model` and Keras layers use `__setattr__` to track
    children. This is why users can call `model.v = tf.Variable(...)`, and the
    variable will be automatically saved to the checkpoint. The implementation
    of this method for the listed objects is:

    ```
    def _add_trackable_child(self, name, value):
      self.__setattr__(name, value)
    ```

    Args:
      name: The name of the connection between the parent and child `Trackable`.
      value: The child `Trackable` object.
    T)r   N)r   )r   r   rj   r   r   r   _add_trackable_childl  s    zTrackable._add_trackable_childc                 C   s   ~i S )an  Returns a dictionary containing `Trackables` that this object depends on.

    Dependencies define the order to serialize and deserialize objects in the
    SavedModel. For example:

    class A(Trackable):
      b = B()
      def _deserialization_dependencies(self, children):
        return {'b': self.b}

    class B(Trackable):
      pass

    We say that object `a=A()` depends on `a.b`.

    Dependencies are guaranteed to be serialized and deserialized before the
    object depending on them. The following methods use dependencies:
      - `_deserialize_from_proto` [loading]

    SavedModel loads with the bottom-up approach, by first creating all objects
    in the order defined by the dependencies, then connecting the children.

    Unlike `_trackable_children`, this function does not define the
    `SavedObjectGraph`. It only changes the order in which things are
    saved/loaded. Therefore, if there are dependencies that are not in the
    `SavedObjectGraph`, saving will fail.

    Args:
      children: Dict returned from `_trackable_children`.

    Returns:
      A dictionary mapping names to `Trackable`.
    r   )r   childrenr   r   r   _deserialization_dependencies  s    "z'Trackable._deserialization_dependenciesc                 K   s   ~~~|    dd | jD S )a  Returns this object's `Trackable` attributes.

    This method is used to build the object graph (or the object hierarchy,
    in pickling terms) for checkpoint save/restore, and `SavedModel` export.

    Override this method to define the children of this instance. Please read
    the implementation restrictions:

    **Rule 1: All children must be convertable to `Trackable`.**

    Must pass `isinstance` check or `converter.convert_to_trackable`.

    **Rule 2: [Checkpoint-only] Do not create new objects.**

    When saving to a `SavedModel`, this method is called *exactly once* for each
    `Trackable` in the object graph. When saving or restoring from a checkpoint,
    this method may be called *multiple times*. Thus, this method may create
    new Trackables when `save_type == SaveType.SAVEDMODEL` but not when
    `save_type == SaveType.CHECKPOINT`.

    When saving to `SavedModel`, new `Trackable` children can be created to save
    non-Trackable attributes to the `SavedModel`. In the example below, `hyper`
    is a regular python float hyperparameter. To save this value, a new Variable
    is created to store the value of `hyper`:

    ```
    def __init__(self):
      self.hyper = 1e-5

    def _trackable_children(self, save_type, **unused_kwargs):
      # Correct implementation
      children = {}
      if format == 'saved_model':
        children['hyper'] = tf.Variable(self.hyper)
      return children
    ```

    An incorrect implementation of `_trackable_children` is shown below. This
    function would cause failures when loading the checkpoint, and calling
    `load_status.assert_consumed()` or
    `load_status.assert_existing_objects_matched`. If you want a value to be
    saved in the checkpoint, hyper must be defined as a `tf.Variable` from the
    start.

    ```
    def _trackable_children(self, save_type, **unused_kwargs):
      # Incorrect implementation
      return {'hyper': tf.Variable(self.hyper)}
    ```

    **Rule 3: [`SavedModel`-only] Watch out for un-traced tf.functions.**

    At the begining of `_trackable_children`, always call
    `get_concrete_function()` for any `tf.function` that has an input signature.

    When `tf.functions` are saved to `SavedModel`, any `tf.functions` that have
    an input signature and has never been called is traced at export time in
    order to copy the op graph into the `SavedModel`. `tf.functions` that are
    traced for the first time are allowed to create new state:


    ```
    @tf.function(input_signature=[]):
    def fn(self);
      if self.v is None:
        self.v = tf.Variable(1.)
      return self.v
    ```

    A problem occurs when there is a `Trackable` that returns `fn` as one of its
    children and `self.v` has not been created yet. When `fn` is traced,
    `self.v` is added to the `Trackable`, but `SavedModel` does not see this
    modification since the `Trackable`'s children have already been gathered.

    Therefore, as a precaution, call `get_concrete_function()` at the very
    start of `_trackable_children` to ensure that the function is traced:


    ```
    def _trackable_children(self):
      self.fn.get_concrete_function()
      return {"v": self.v, "fn": self.fn}
    ```

    Args:
      save_type: A string, can be 'savedmodel' or 'checkpoint'. Defaults to
        SaveType.CHECKPOINT.
      cache: May be `None`, or a dictionary. When `save_type == savedmodel`, a
        new cache is created at the start of the SavedModel export, and shared
        between all `Trackables` in the same object graph. This cache may be
        used for advanced saving functionality.
      **kwargs: Additional kwargs that may be added at a later time.

    Returns:
      Dictionary mapping names to child trackables.
    c                 S   s   i | ]\}}||qS r   r   )r:   r   r   r   r   r   
<dictcomp>  r=   z1Trackable._trackable_children.<locals>.<dictcomp>)rz   r   )r   	save_typecacherW   r   r   r   _trackable_children  s    dzTrackable._trackable_childrenc                 K   s0   ~|  |\}}|| || t| S )a  Creates a copy of this object's tensors onto SavedModel graph.

    Needs to be overridden if the class contains tensors that must be saved
    into the graph. This method should update the `object_map` and `tensor_map`
    dictionaries.

    This method is called on all nodes in the Trackable Graph (generated by
    `_trackable_children`). The nodes are traversed in the order defined by
    `_deserialization_dependencies`

    All usages of _map_resources should be migrated to this method.

    Args:
      object_map: A dictionary that maps original Trackables to the copied
        Trackables. This only needs to be updated if the object is a
        tf.function, or if the copied tensors are necessary for checkpointing
        this object.
      tensor_map: Dictionary mapping original tensors to copied tensors.
      options: A `tf.saved_model.SaveOptions` object.
      **kwargs: Additional kwargs that may be added at a later time.

    Returns:
      Flat list of original tensors that have been copied.
    )r   updatelistkeys)r   Z
object_mapZ
tensor_mapoptionsrW   Zself_object_mapZself_tensor_mapr   r   r   _export_to_saved_model_graph  s
    

z&Trackable._export_to_saved_model_graph)F)N)NNNNNN)NNN)&r   r$   r%   r&   r(   re   setterrm   rp   rr   rt   r`   rz   r{   r|   r   r   r   r   r   float32r   r   r   r   r   r   r   r   r   classmethodr   r   r   SaveType
CHECKPOINTr   r   r   r   r   r   rg     sr   







+



E$
7&01
      S&
j   rg   )'r&   collectionsr*   tensorflow.python.eagerr   tensorflow.python.frameworkr   r   tensorflow.python.opsr   tensorflow.python.trackabler   r   r   tensorflow.python.utilr   r	    tensorflow.python.util.tf_exportr
   ZOBJECT_GRAPH_PROTO_KEYrC   ZOBJECT_CONFIG_JSON_KEYr   objectr   r)   
namedtupleZ	ShardInfor0   Tensorr5   SaveableObjectrK   rT   r`   contextmanagerrd   rf   rg   r   r   r   r   <module>   sL   
)

$




