
    BVh/                         d 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  edg        G d de             Zy)zManages a Checkpoint View.    N)trackable_object_graph_pb2)trackable_view)errors_impl)
tf_logging)base)py_checkpoint_reader)object_identity)	tf_exportztrain.CheckpointView)v1c                   4    e Zd ZdZd Zd Zd Zd Zd Zd Z	y)	CheckpointViewaa  Gathers and serializes a checkpoint view.

  This is for loading specific portions of a module from a
  checkpoint, and be able to compare two modules by matching components.

  Example usage:

  >>> class SimpleModule(tf.Module):
  ...   def __init__(self, name=None):
  ...     super().__init__(name=name)
  ...     self.a_var = tf.Variable(5.0)
  ...     self.b_var = tf.Variable(4.0)
  ...     self.vars = [tf.Variable(1.0), tf.Variable(2.0)]

  >>> root = SimpleModule(name="root")
  >>> root.leaf = SimpleModule(name="leaf")
  >>> ckpt = tf.train.Checkpoint(root)
  >>> save_path = ckpt.save('/tmp/tf_ckpts')
  >>> checkpoint_view = tf.train.CheckpointView(save_path)

  Pass `node_id=0` to `tf.train.CheckpointView.children()` to get the dictionary
  of all children directly linked to the checkpoint root.

  >>> for name, node_id in checkpoint_view.children(0).items():
  ...   print(f"- name: '{name}', node_id: {node_id}")
  - name: 'a_var', node_id: 1
  - name: 'b_var', node_id: 2
  - name: 'vars', node_id: 3
  - name: 'leaf', node_id: 4
  - name: 'root', node_id: 0
  - name: 'save_counter', node_id: 5

  c                 >   t        j                  |      }	 |j                  t        j                        }t        j                         }|j                  |       || _        y# t
        j                  $ r&}t        d| dt        j                   d      |d}~ww xY w)zConfigure the checkpoint view.

    Args:
      save_path: The path to the checkpoint.

    Raises:
      ValueError: If the save_path does not lead to a TF2 checkpoint.
    zThe specified checkpoint "zS" does not appear to be object-based (saved with TF2) since it is missing the key "zg". Likely it was created with the TF1 name-based saver and does not contain an object dependency graph.N)r   NewCheckpointReader
get_tensorr   OBJECT_GRAPH_PROTO_KEYr   NotFoundError
ValueErrorr   TrackableObjectGraphParseFromString_object_graph_proto)self	save_pathreaderobject_graph_stringnot_found_errorobject_graph_protos         \/home/dcms/DCMS/lib/python3.12/site-packages/tensorflow/python/checkpoint/checkpoint_view.py__init__zCheckpointView.__init__@   s     "55i@F"--d.I.IJ 5IIK&&':;1D $$ '	{ 3**+ ,RR
 s   A# #B6!BBc                     | j                   j                  |   j                  D ci c]  }|j                  |j                   c}S c c}w )zReturns all child trackables attached to obj.

    Args:
      node_id: Id of the node to return its children.

    Returns:
      Dictionary of all children attached to the object with name to node_id.
    )r   nodeschildren
local_namenode_id)r   r#   childs      r   r!   zCheckpointView.childrenX   sJ     --33G<EE 	%--'  s   Ac                 P    t        | j                         j                               S )z8Returns a list of trackables by node_id attached to obj.)list_descendants_with_pathskeys)r   s    r   descendantszCheckpointView.descendantsf   s!     ,,.33566    c                    i }t        j                  dg      }d|d<   |j                  d      }|r|j                         }| j                  j
                  |   }|j                  D ]  }|j                  dk(  s|j                  |j                         v r/|j                  |      }|j                  |j                         vr|j                  |j                         |dz   |j                  z   ||j                  <    |r|S )zReturns a dict of descendants by node_id and paths to node.

    The names returned by this private method are subject to change.
    r   root.)collectionsdequegetpopleftr   r    r!   r#   r(   appendr"   )r   all_nodes_with_pathsto_visitpathr#   objr$   s          r   r'   z&CheckpointView._descendants_with_pathsk   s       !%H$##A&D
  "g$$**73c<< L%==A2F2K2K2M!M
#''0== 4 9 9 ;;
//%--
(.2Sj5;K;K.KU]]+L   r*   c                 ~   t        |t        j                        st        d| dt	        |       d      i }||d<   t        j                  d|fg      }t               }t        j                  |      }|r|j                         \  }}|j                  |      }| j                  |      j                         D ]m  \  }	}
|
|v s|
dk(  r|	|v s|j                  |
      }|||	   ||
<   |j                  |
||	   f       G|||	   usOt        j                   d| d||	    d       o |j#                  |       |r|S )a>  Returns all matching trackables between CheckpointView and Trackable.

    Matching trackables represents trackables with the same name and position in
    graph.

    Args:
      obj: `Trackable` root.

    Returns:
      Dictionary containing all overlapping trackables that maps `node_id` to
      `Trackable`.

    Example usage:

    >>> class SimpleModule(tf.Module):
    ...   def __init__(self, name=None):
    ...     super().__init__(name=name)
    ...     self.a_var = tf.Variable(5.0)
    ...     self.b_var = tf.Variable(4.0)
    ...     self.vars = [tf.Variable(1.0), tf.Variable(2.0)]

    >>> root = SimpleModule(name="root")
    >>> leaf = root.leaf = SimpleModule(name="leaf")
    >>> leaf.leaf3 = tf.Variable(6.0, name="leaf3")
    >>> leaf.leaf4 = tf.Variable(7.0, name="leaf4")
    >>> ckpt = tf.train.Checkpoint(root)
    >>> save_path = ckpt.save('/tmp/tf_ckpts')
    >>> checkpoint_view = tf.train.CheckpointView(save_path)

    >>> root2 = SimpleModule(name="root")
    >>> leaf2 = root2.leaf2 = SimpleModule(name="leaf2")
    >>> leaf2.leaf3 = tf.Variable(6.0)
    >>> leaf2.leaf4 = tf.Variable(7.0)

    Pass `node_id=0` to `tf.train.CheckpointView.children()` to get the
    dictionary of all children directly linked to the checkpoint root.

    >>> checkpoint_view_match = checkpoint_view.match(root2).items()
    >>> for item in checkpoint_view_match:
    ...   print(item)
    (0, ...)
    (1, <tf.Variable 'Variable:0' shape=() dtype=float32, numpy=5.0>)
    (2, <tf.Variable 'Variable:0' shape=() dtype=float32, numpy=4.0>)
    (3, ListWrapper([<tf.Variable 'Variable:0' shape=() dtype=float32,
    numpy=1.0>, <tf.Variable 'Variable:0' shape=() dtype=float32, numpy=2.0>]))
    (6, <tf.Variable 'Variable:0' shape=() dtype=float32, numpy=1.0>)
    (7, <tf.Variable 'Variable:0' shape=() dtype=float32, numpy=2.0>)

    zExpected a Trackable, got z	 of type r-   r   zjInconsistent references when matching the checkpoint into this object graph. The referenced objects are: (z and z).)
isinstancer   	Trackabler   typer.   r/   setr   TrackableViewr1   r!   itemsr0   r2   loggingwarningadd)r   r6   overlapping_nodesr4   visitedviewcurrent_node_idcurrent_trackabletrackable_children
child_namechild_node_idcurrent_assignments               r   matchzCheckpointView.match   sn   d c4>>*3C5	$s)ANOOa   1c(,HeG'',D
+3+;+;+=(o(==):;'+}}_'E'K'K'M 9
#*mG#}'9
++044]C
'/A*/Mm,OO],>z,JKL ");J)GGoo()'
34B899& kk/"- . r*   c                 f   | j                  |      }g }g }| j                         D ]&  }||j                         vs|j                  |       ( t	        j
                  |      j                         D ]9  }|t        j                  |j                               vs)|j                  |       ; |||fS )a:  Returns diff between CheckpointView and Trackable.

    This method is intended to be used to compare the object stored in a
    checkpoint vs a live model in Python. For example, if checkpoint
    restoration fails the `assert_consumed()` or
    `assert_existing_objects_matched()` checks, you can use this to list out
    the objects/checkpoint nodes which were not restored.

    Example Usage:

    >>> class SimpleModule(tf.Module):
    ...   def __init__(self, name=None):
    ...     super().__init__(name=name)
    ...     self.a_var = tf.Variable(5.0)
    ...     self.b_var = tf.Variable(4.0)
    ...     self.vars = [tf.Variable(1.0), tf.Variable(2.0)]

    >>> root = SimpleModule(name="root")
    >>> leaf = root.leaf = SimpleModule(name="leaf")
    >>> leaf.leaf3 = tf.Variable(6.0, name="leaf3")
    >>> leaf.leaf4 = tf.Variable(7.0, name="leaf4")
    >>> ckpt = tf.train.Checkpoint(root)
    >>> save_path = ckpt.save('/tmp/tf_ckpts')
    >>> checkpoint_view = tf.train.CheckpointView(save_path)

    >>> root2 = SimpleModule(name="root")
    >>> leaf2 = root2.leaf2 = SimpleModule(name="leaf2")
    >>> leaf2.leaf3 = tf.Variable(6.0)
    >>> leaf2.leaf4 = tf.Variable(7.0)

    Pass `node_id=0` to `tf.train.CheckpointView.children()` to get the
    dictionary of all children directly linked to the checkpoint root.

    >>> checkpoint_view_diff = checkpoint_view.diff(root2)
    >>> checkpoint_view_match = checkpoint_view_diff[0].items()
    >>> for item in checkpoint_view_match:
    ...   print(item)
    (0, ...)
    (1, <tf.Variable 'Variable:0' shape=() dtype=float32, numpy=5.0>)
    (2, <tf.Variable 'Variable:0' shape=() dtype=float32, numpy=4.0>)
    (3, ListWrapper([<tf.Variable 'Variable:0' shape=() dtype=float32,
    numpy=1.0>, <tf.Variable 'Variable:0' shape=() dtype=float32, numpy=2.0>]))
    (6, <tf.Variable 'Variable:0' shape=() dtype=float32, numpy=1.0>)
    (7, <tf.Variable 'Variable:0' shape=() dtype=float32, numpy=2.0>)

    >>> only_in_checkpoint_view = checkpoint_view_diff[1]
    >>> print(only_in_checkpoint_view)
    [4, 5, 8, 9, 10, 11, 12, 13, 14]

    >>> only_in_trackable = checkpoint_view_diff[2]
    >>> print(only_in_trackable)
    [..., <tf.Variable 'Variable:0' shape=() dtype=float32, numpy=5.0>,
    <tf.Variable 'Variable:0' shape=() dtype=float32, numpy=4.0>,
    ListWrapper([<tf.Variable 'Variable:0' shape=() dtype=float32, numpy=1.0>,
    <tf.Variable 'Variable:0' shape=() dtype=float32, numpy=2.0>]),
    <tf.Variable 'Variable:0' shape=() dtype=float32, numpy=6.0>,
    <tf.Variable 'Variable:0' shape=() dtype=float32, numpy=7.0>,
    <tf.Variable 'Variable:0' shape=() dtype=float32, numpy=1.0>,
    <tf.Variable 'Variable:0' shape=() dtype=float32, numpy=2.0>]

    Args:
      obj: `Trackable` root.

    Returns:
      Tuple of (
      - Overlaps: Dictionary containing all overlapping trackables that maps
      `node_id` to `Trackable`, same as CheckpointView.match().
      - Only in CheckpointView: List of `node_id` that only exist in
      CheckpointView.
      - Only in Trackable: List of `Trackable` that only exist in Trackable.
      )

    )	rJ   r)   r(   r2   r   r<   r	   ObjectIdentitySetvalues)r   r6   rA   only_in_checkpoint_viewonly_in_trackabler#   	trackables          r   diffzCheckpointView.diff   s    V 

3 ##% 0	)..0	0&&w/0 $11#6BBD ,		/;;

"
"
$& 
&  +, 57HHHr*   N)
__name__
__module____qualname____doc__r   r!   r)   r'   rJ   rQ    r*   r   r   r      s*     D207
 .TlUIr*   r   )rU   r.   tensorflow.core.protobufr   tensorflow.python.checkpointr   tensorflow.python.frameworkr   tensorflow.python.platformr   r>   tensorflow.python.trackabler   tensorflow.python.trainingr   tensorflow.python.utilr	    tensorflow.python.util.tf_exportr
   objectr   rV   r*   r   <module>r`      sN       ? 7 3 < , ; 2 6 !b)PIV PI *PIr*   