
    ¯wgN                     R   d Z ddlZddlZddlZddlmZmZmZmZm	Z	m
Z
mZmZmZmZ ddlmZ ddlZddlmZ ddlmc mZ ddlmZ g dZ ed      Z ed	      Z ed
      Z ed      ZeZeZeZeegeee   ef   f   Zeee   egef   Z eeee   gef   Z!eZ"eege"f   Z#ee"gef   Z$eedf   Z%eegeeeeef      ef   f   Z&de de!fdZ'ddddddee   dede de	e(   de	e#   de	e$   de	e&   ddfdZ) ede*      dddddee   dede de	e(   de	e#   de	e$   ddfd       Z+dddddee   dede de	e(   de	e#   de	e$   ddfdZ,	 dadede	eege-f      deee   ef   fd Z.d!ee   d"edefd#Z/	 dadede	eege-f      dee   fd$Z0	 dadede	eege-f      dee   fd%Z1	 dadede	eege-f      defd&Z2dd'dedef   ded(ede	eege-f      def
d)Z3dd'dedef   ded(ede	eege-f      def
d*Z4eee   ee   f   Z5eee   ee   ee   f   Z6ejn                  d+k\  reee   eee   df   ejp                  f   Z9neee   eee   df   f   Z9eeeef   gef   Z:eeeeef   gef   Z;eegef   Z<eegef   Z=eegeegef   f   Z>e
d,e5eef   de>e:eeef      fd-       Z?e
d,e6eeef   de>e;eeeef      fd.       Z?e
d,ee   de>e<eef      fd/       Z?e
d,e9de>e=e      fd0       Z?e
d,eege-f   de>e=e      fd1       Z?d,ee9eege-f   f   de>e=e      fd2Z?e
	 dad,ee   de<eef   dede	eege-f      def
d3       Z@e
	 dad,e5eef   de:eeef   dede	eege-f      def
d4       Z@e
	 dad,e6eeef   de;eeeef   dede	eege-f      def
d5       Z@e
	 dad,eege-f   de=e   dede	eege-f      def
d6       Z@	 dad,ee9eege-f   f   de=e   dede	eege-f      def
d7Z@e
	 dad,ee   de<eef   dede	eege-f      def
d8       ZAe
	 dad,e5eef   de:eeef   dede	eege-f      def
d9       ZAe
	 dad,e6eeef   de;eeeef   dede	eege-f      def
d:       ZAe
	 dad,eege-f   de=e   dede	eege-f      def
d;       ZA	 dad,ee9eege-f   f   de=e   dede	eege-f      def
d<ZA	 dad=eege-f   dede	eege-f      de-fd>ZB	 dad=eege-f   dede	eege-f      de-fd?ZCe
	 dad@ee   d=e<ee-f   dede	eege-f      de-f
dA       ZDe
	 dad@e5eef   d=e:eee-f   dede	eege-f      de-f
dB       ZDe
	 dad@e6eeef   d=e;eeee-f   dede	eege-f      de-f
dC       ZD	 dad@e9d=e=e-   dede	eege-f      de-f
dDZDe
	 dad@ee   d=e<ee-f   dede	eege-f      de-f
dE       ZEe
	 dad@e5eef   d=e:eee-f   dede	eege-f      de-f
dF       ZEe
	 dad@e6eeef   d=e;eeee-f   dede	eege-f      de-f
dG       ZE	 dad@e9d=e=e-   dede	eege-f      de-f
dHZE	 dadIedJede	eege-f      dee   fdKZF	 daded"ede	eege-f      de	ee      fdLZGdad"edMe	eH   de(fdNZIdOe(defdPZJ G dQ dR      ZKd"ede(fdSZL G dT dU eMe            ZN G dV dWeeNX      ZO	 dadede	eege-f      deeee%ef      ef   fdYZP	 dadede	eege-f      deee%ef      fdZZQdd'dedef   ded(ede	eege-f      def
d[ZRd\e%de(fd]ZSd^ed\e%defd_ZTd`e_U        ej                  D ]  \  ZWZX e,eWi eX  y)ba  
Contains utility functions for working with nested python data structures.

A *pytree* is Python nested data structure. It is a tree in the sense that
nodes are Python collections (e.g., list, tuple, dict) and the leaves are
Python values. Furthermore, a pytree should not contain reference cycles.

pytrees are useful for working with nested collections of Tensors. For example,
one can use `tree_map` to map a function over all Tensors inside some nested
collection of Tensors and `tree_leaves` to get a flat list of all Tensors
inside some nested collection. pytrees are helpful for implementing nested
collection support for PyTorch APIs.
    N)
AnyCallableIterableListOptionaloverloadTupleTypeTypeVarUnion)
deprecated)
PyTreeSpec)KeyEntry)PyTreeContextFlattenFuncUnflattenFuncDumpableContextToDumpableContextFnFromDumpableContextFnTreeSpecLeafSpeckeystrkey_getregister_pytree_nodetree_flattentree_flatten_with_pathtree_unflatten	tree_itertree_leavestree_leaves_with_pathtree_structuretree_maptree_map_with_path	tree_map_tree_map_onlytree_map_only_tree_alltree_anytree_all_onlytree_any_onlytreespec_dumpstreespec_loadstreespec_pprintTSUR.funcreturnc                 h     t        j                         dt        dt        dt        f fd       }|S )Nargskwargsr4   c                  &     t        |       i |S N)reversed)r6   r7   r3   s     \/home/mcse/projects/flask/flask-venv/lib/python3.12/site-packages/torch/utils/_cxx_pytree.pywrappedz_reverse_args.<locals>.wrapped^   s    Xd^.v..    )	functoolswrapsr   )r3   r<   s   ` r;   _reverse_argsr@   ]   s:    __T/s /c /c / / Nr=   )serialized_type_nameto_dumpable_contextfrom_dumpable_contextflatten_with_keys_fncls
flatten_fnunflatten_fnrA   rB   rC   rD   c                z    |t        d      t        | |||||       ddlm} |j                  | |||||       y)a  Register a container-like type as pytree node.

    Args:
        cls (type): A Python type to treat as an internal pytree node.
        flatten_fn (callable): A function to be used during flattening, taking an instance of
            ``cls`` and returning a pair, with (1) an iterable for the children to be flattened
            recursively, and (2) some hashable auxiliary data to be stored in the treespec and to be
            passed to the ``unflatten_fn``.
        unflatten_fn (callable): A function taking two arguments: the auxiliary data that was
            returned by ``flatten_fn`` and stored in the treespec, and the unflattened children.
            The function should return an instance of ``cls``.
        serialized_type_name (str, optional): A keyword argument used to specify the fully
            qualified name used when serializing the tree spec.
        to_dumpable_context (callable, optional): An optional keyword argument to custom specify how
            to convert the context of the pytree to a custom json dumpable representation. This is
            used for json serialization, which is being used in :mod:`torch.export` right now.
        from_dumpable_context (callable, optional): An optional keyword argument to custom specify
            how to convert the custom json dumpable representation of the context back to the
            original context. This is used for json deserialization, which is being used in
            :mod:`torch.export` right now.

    Example::

        >>> # xdoctest: +SKIP
        >>> # Registry a Python type with lambda functions
        >>> register_pytree_node(
        ...     set,
        ...     lambda s: (sorted(s), None, None),
        ...     lambda children, _: set(children),
        ... )
    N-KeyPaths are not yet supported in cxx_pytree.rA   rB   rC      )_pytree)NotImplementedError_private_register_pytree_node rL   )rE   rF   rG   rA   rB   rC   rD   pythons           r;   r   r   e   s[    R '!"QRR!1/3 $
((1/3 ) r=   z`torch.utils._cxx_pytree._register_pytree_node` is deprecated. Please use `torch.utils._cxx_pytree.register_pytree_node` instead.)categoryrJ   c                &    t        | |||||       y)a  Register a container-like type as pytree node for the C++ pytree only.

    The ``namespace`` argument is used to avoid collisions that occur when different libraries
    register the same Python type with different behaviors. It is recommended to add a unique prefix
    to the namespace to avoid conflicts with other libraries. Namespaces can also be used to specify
    the same class in different namespaces for different use cases.

    .. warning::
        For safety reasons, a ``namespace`` must be specified while registering a custom type. It is
        used to isolate the behavior of flattening and unflattening a pytree node type. This is to
        prevent accidental collisions between different libraries that may register the same type.

    Args:
        cls (type): A Python type to treat as an internal pytree node.
        flatten_fn (callable): A function to be used during flattening, taking an instance of
            ``cls`` and returning a pair, with (1) an iterable for the children to be flattened
            recursively, and (2) some hashable auxiliary data to be stored in the treespec and to be
            passed to the ``unflatten_fn``.
        unflatten_fn (callable): A function taking two arguments: the auxiliary data that was
            returned by ``flatten_fn`` and stored in the treespec, and the unflattened children.
            The function should return an instance of ``cls``.
        serialized_type_name (str, optional): A keyword argument used to specify the fully
            qualified name used when serializing the tree spec.
        to_dumpable_context (callable, optional): An optional keyword argument to custom specify how
            to convert the context of the pytree to a custom json dumpable representation. This is
            used for json serialization, which is being used in :mod:`torch.export` right now.
        from_dumpable_context (callable, optional): An optional keyword argument to custom specify
            how to convert the custom json dumpable representation of the context back to the
            original context. This is used for json deserialization, which is being used in
            :mod:`torch.export` right now.
    rJ   N)rN   rE   rF   rG   rA   rB   rC   s         r;   _register_pytree_noderT      s    \ "1/3r=   c                t    t        j                  |       s#t        j                  | |t        |      d       yy)zThis is an internal function that is used to register a pytree node type
    for the C++ pytree only. End-users should use :func:`register_pytree_node`
    instead.
    torch)	namespaceN)optreeis_structseq_classr   r@   rS   s         r;   rN   rN      s6     $$S)##,'		
 *r=   treeis_leafc                 4    t        j                  | |dd      S )a  Flatten a pytree.

    See also :func:`tree_unflatten`.

    The flattening order (i.e., the order of elements in the output list) is deterministic,
    corresponding to a left-to-right depth-first tree traversal.

    >>> tree = {'b': (2, [3, 4]), 'a': 1, 'c': None, 'd': 5}
    >>> tree_flatten(tree)
    ([1, 2, 3, 4, None, 5], PyTreeSpec({'a': *, 'b': (*, [*, *]), 'c': *, 'd': *}, NoneIsLeaf))
    >>> tree_flatten(1)
    ([1], PyTreeSpec(*, NoneIsLeaf))
    >>> tree_flatten(None)
    ([None], PyTreeSpec(*, NoneIsLeaf))

    For unordered dictionaries, :class:`dict` and :class:`collections.defaultdict`, the order is
    dependent on the **sorted** keys in the dictionary. Please use :class:`collections.OrderedDict`
    if you want to keep the keys in the insertion order.

    >>> from collections import OrderedDict
    >>> tree = OrderedDict([('b', (2, [3, 4])), ('a', 1), ('c', None), ('d', 5)])
    >>> tree_flatten(tree)
    ([2, 3, 4, 1, None, 5], PyTreeSpec(OrderedDict({'b': (*, [*, *]), 'a': *, 'c': *, 'd': *}), NoneIsLeaf))

    Args:
        tree (pytree): A pytree to flatten.
        is_leaf (callable, optional): An extra leaf predicate function that will be called at each
            flattening step. The function should have a single argument with signature
            ``is_leaf(node) -> bool``. If it returns :data:`True`, the whole subtree being treated
            as a leaf. Otherwise, the default pytree registry will be used to determine a node is a
            leaf or not. If the function is not specified, the default pytree registry will be used.

    Returns:
        A pair ``(leaves, treespec)`` where the first element is a list of leaf values and the
        second element is a treespec representing the structure of the pytree.
    TrV   r[   none_is_leafrW   )rX   r   rZ   r[   s     r;   r   r      s$    P 	 r=   leavestreespecc                 ~    t        |t              st        dt        |       d      t	        j
                  ||       S )ad  Reconstruct a pytree from the treespec and the leaves.

    The inverse of :func:`tree_flatten`.

    >>> tree = {'b': (2, [3, 4]), 'a': 1, 'c': None, 'd': 5}
    >>> leaves, treespec = tree_flatten(tree)
    >>> tree == tree_unflatten(leaves, treespec)
    True

    Args:
        leaves (iterable): The list of leaves to use for reconstruction. The list must match the
            number of leaves of the treespec.
        treespec (TreeSpec): The treespec to reconstruct.

    Returns:
        The reconstructed pytree, containing the ``leaves`` placed in the structure described by
        ``treespec``.
    z^tree_unflatten(values, spec): Expected `spec` to be instance of TreeSpec but got item of type .)
isinstancer   	TypeErrortyperX   r   )r`   ra   s     r;   r   r   &  sF    & h)--1(^,<A?
 	
   622r=   c                 4    t        j                  | |dd      S )al  Get an iterator over the leaves of a pytree.

    See also :func:`tree_flatten`.

    >>> tree = {'b': (2, [3, 4]), 'a': 1, 'c': None, 'd': 5}
    >>> list(tree_iter(tree))
    [1, 2, 3, 4, None, 5]
    >>> list(tree_iter(1))
    [1]
    >>> list(tree_iter(None))
    [None]

    Args:
        tree (pytree): A pytree to flatten.
        is_leaf (callable, optional): An extra leaf predicate function that will be called at each
            flattening step. The function should have a single argument with signature
            ``is_leaf(node) -> bool``. If it returns :data:`True`, the whole subtree being treated
            as a leaf. Otherwise, the default pytree registry will be used to determine a node is a
            leaf or not. If the function is not specified, the default pytree registry will be used.

    Returns:
        An iterator over the leaf values.
    TrV   r]   )rX   r   r_   s     r;   r   r   A  s#    6 	 r=   c                 4    t        j                  | |dd      S )aD  Get the leaves of a pytree.

    See also :func:`tree_flatten`.

    >>> tree = {'b': (2, [3, 4]), 'a': 1, 'c': None, 'd': 5}
    >>> tree_leaves(tree)
    [1, 2, 3, 4, None, 5]
    >>> tree_leaves(1)
    [1]
    >>> tree_leaves(None)
    [None]

    Args:
        tree (pytree): A pytree to flatten.
        is_leaf (callable, optional): An extra leaf predicate function that will be called at each
            flattening step. The function should have a single argument with signature
            ``is_leaf(node) -> bool``. If it returns :data:`True`, the whole subtree being treated
            as a leaf. Otherwise, the default pytree registry will be used to determine a node is a
            leaf or not. If the function is not specified, the default pytree registry will be used.

    Returns:
        A list of leaf values.
    TrV   r]   )rX   r    r_   s     r;   r    r    d  s#    6 	 r=   c                 4    t        j                  | |dd      S )a  Get the treespec for a pytree.

    See also :func:`tree_flatten`.

    >>> tree = {'b': (2, [3, 4]), 'a': 1, 'c': None, 'd': 5}
    >>> tree_structure(tree)
    PyTreeSpec({'a': *, 'b': (*, [*, *]), 'c': *, 'd': *}, NoneIsLeaf)
    >>> tree_structure(1)
    PyTreeSpec(*, NoneIsLeaf)
    >>> tree_structure(None)
    PyTreeSpec(*, NoneIsLeaf)

    Args:
        tree (pytree): A pytree to flatten.
        is_leaf (callable, optional): An extra leaf predicate function that will be called at each
            flattening step. The function should have a single argument with signature
            ``is_leaf(node) -> bool``. If it returns :data:`True`, the whole subtree being treated
            as a leaf. Otherwise, the default pytree registry will be used to determine a node is a
            leaf or not. If the function is not specified, the default pytree registry will be used.

    Returns:
        A treespec object representing the structure of the pytree.
    TrV   r]   )rX   r"   r_   s     r;   r"   r"     s#    6   	 r=   r[   restsc                :    t        j                  | |g||dddS )a  Map a multi-input function over pytree args to produce a new pytree.

    See also :func:`tree_map_`.

    >>> tree_map(lambda x: x + 1, {'x': 7, 'y': (42, 64)})
    {'x': 8, 'y': (43, 65)}
    >>> tree_map(lambda x: x is None, {'x': 7, 'y': (42, 64), 'z': None})
    {'x': False, 'y': (False, False), 'z': True}

    If multiple inputs are given, the structure of the tree is taken from the first input;
    subsequent inputs need only have ``tree`` as a prefix:

    >>> tree_map(lambda x, y: [x] + y, [5, 6], [[7, 9], [1, 2]])
    [[5, 7, 9], [6, 1, 2]]

    Args:
        func (callable): A function that takes ``1 + len(rests)`` arguments, to be applied at the
            corresponding leaves of the pytrees.
        tree (pytree): A pytree to be mapped over, with each leaf providing the first positional
            argument to function ``func``.
        rests (tuple of pytree): A tuple of pytrees, each of which has the same structure as
            ``tree`` or has ``tree`` as a prefix.
        is_leaf (callable, optional): An extra leaf predicate function that will be called at each
            flattening step. The function should have a single argument with signature
            ``is_leaf(node) -> bool``. If it returns :data:`True`, the whole subtree being treated
            as a leaf. Otherwise, the default pytree registry will be used to determine a node is a
            leaf or not. If the function is not specified, the default pytree registry will be used.

    Returns:
        A new pytree with the same structure as ``tree`` but with the value at each leaf given by
        ``func(x, *xs)`` where ``x`` is the value at the corresponding leaf in ``tree`` and ``xs``
        is the tuple of values at corresponding nodes in ``rests``.
    TrV   r]   )rX   r#   r3   rZ   r[   rk   s       r;   r#   r#     s6    N ?? 
  r=   c                :    t        j                  | |g||dddS )aT  Like :func:`tree_map`, but do an inplace call on each leaf and return the original tree.

    See also :func:`tree_map`.

    Args:
        func (callable): A function that takes ``1 + len(rests)`` arguments, to be applied at the
            corresponding leaves of the pytrees.
        tree (pytree): A pytree to be mapped over, with each leaf providing the first positional
            argument to function ``func``.
        rests (tuple of pytree): A tuple of pytrees, each of which has the same structure as
            ``tree`` or has ``tree`` as a prefix.
        is_leaf (callable, optional): An extra leaf predicate function that will be called at each
            flattening step. The function should have a single argument with signature
            ``is_leaf(node) -> bool``. If it returns :data:`True`, the whole subtree being treated
            as a leaf. Otherwise, the default pytree registry will be used to determine a node is a
            leaf or not. If the function is not specified, the default pytree registry will be used.

    Returns:
        The original ``tree`` with the value at each leaf is given by the side-effect of function
        ``func(x, *xs)`` (not the return value) where ``x`` is the value at the corresponding leaf
        in ``tree`` and ``xs`` is the tuple of values at values at corresponding nodes in ``rests``.
    TrV   r]   )rX   r%   rm   s       r;   r%   r%     s7    8  
  r=      
   __type_or_types_or_predc                      y r9    rr   s    r;   map_onlyrv         r=   c                      y r9   rt   ru   s    r;   rv   rv     rw   r=   c                      y r9   rt   ru   s    r;   rv   rv     rw   r=   c                      y r9   rt   ru   s    r;   rv   rv   "  rw   r=   c                      y r9   rt   ru   s    r;   rv   rv   '  rw   r=   c                 D    t         t        t        f      s-t        j                  dk\  r-t         t
        j                        rdt        dt        f fdnt               r nt        d      dt        t        gt        f   dt        t        gt        f   ffd}|S )a  
    Suppose you are writing a tree_map over tensors, leaving everything
    else unchanged.  Ordinarily you would have to write:

        def go(t):
            if isinstance(t, Tensor):
                return ...
            else:
                return t

    With this function, you only need to write:

        @map_only(Tensor)
        def go(t):
            return ...

    You can also directly use 'tree_map_only'
    ro   xr4   c                     t        |       S r9   rd   )r}   rr   s    r;   predzmap_only.<locals>.predF  s    a!899r=   z9Argument must be a type, a tuple of types, or a callable.r3   c                 `     t        j                         dt        dt        f fd       }|S )Nr}   r4   c                 (     |       r |       S | S r9   rt   )r}   r3   r   s    r;   r<   z*map_only.<locals>.wrapper.<locals>.wrappedO  s    AwAwHr=   )r>   r?   r/   r   )r3   r<   r   s   ` r;   wrapperzmap_only.<locals>.wrapperN  s3    			q 	S 	 
	
 r=   )rd   rf   tuplesysversion_infotypes	UnionTyper   boolcallablere   r   r/   )rr   r   r   s   ` @r;   rv   rv   ,  s    * )D%=9G#.@	:C 	:D 	: 
)	*&STThsCx( XseSj-A  Nr=   c                      y r9   rt   rr   r3   rZ   r[   s       r;   r&   r&   Z       r=   c                      y r9   rt   r   s       r;   r&   r&   d  r   r=   c                      y r9   rt   r   s       r;   r&   r&   n  r   r=   c                      y r9   rt   r   s       r;   r&   r&   x  r   r=   c                 <    t         t        |       |      ||      S Nrj   )r#   rv   r   s       r;   r&   r&     s!     5H45d;T7SSr=   c                      y r9   rt   r   s       r;   r'   r'     r   r=   c                      y r9   rt   r   s       r;   r'   r'     r   r=   c                      y r9   rt   r   s       r;   r'   r'     r   r=   c                      y r9   rt   r   s       r;   r'   r'     r   r=   c                 <    t         t        |       |      ||      S r   )r%   rv   r   s       r;   r'   r'     s!     6X56t<dGTTr=   r   c                 F    t        ||      }t        t        | |            S r   )r   allmapr   rZ   r[   	flat_argss       r;   r(   r(     "    
 $0Is4#$$r=   c                 F    t        ||      }t        t        | |            S r   )r   anyr   r   s       r;   r)   r)     r   r=   __type_or_typesc                      y r9   rt   r   r   rZ   r[   s       r;   r*   r*     r   r=   c                      y r9   rt   r   s       r;   r*   r*     r   r=   c                      y r9   rt   r   s       r;   r*   r*     r   r=   c                 J     t        ||      }t         fd|D              S )Nrj   c              3   H   K   | ]  }t        |      s |        y wr9   r   .0r}   r   r   s     r;   	<genexpr>z tree_all_only.<locals>.<genexpr>       L1Z?-KtAwL   "")r   r   r   r   rZ   r[   r   s   ``   r;   r*   r*     "     $0IL	LLLr=   c                      y r9   rt   r   s       r;   r+   r+     r   r=   c                      y r9   rt   r   s       r;   r+   r+      r   r=   c                      y r9   rt   r   s       r;   r+   r+   
  r   r=   c                 J     t        ||      }t         fd|D              S )Nrj   c              3   H   K   | ]  }t        |      s |        y wr9   r   r   s     r;   r   z tree_any_only.<locals>.<genexpr>  r   r   )r   r   r   s   ``   r;   r+   r+     r   r=   prefix_tree	full_treec                 6    t        j                  | ||dd      S )a  Return a list of broadcasted leaves in ``prefix_tree`` to match the number of leaves in ``full_tree``.

    If a ``prefix_tree`` is a prefix of a ``full_tree``, this means the ``full_tree`` can be
    constructed by replacing the leaves of ``prefix_tree`` with appropriate **subtrees**.

    This function returns a list of leaves with the same size as ``full_tree``. The leaves are
    replicated from ``prefix_tree``. The number of replicas is determined by the corresponding
    subtree in ``full_tree``.

    >>> broadcast_prefix(1, [1, 2, 3])
    [1, 1, 1]
    >>> broadcast_prefix([1, 2, 3], [1, 2, 3])
    [1, 2, 3]
    >>> broadcast_prefix([1, 2, 3], [1, 2, 3, 4])
    Traceback (most recent call last):
        ...
    ValueError: list arity mismatch; expected: 3, got: 4; list: [1, 2, 3, 4].
    >>> broadcast_prefix([1, 2, 3], [1, 2, (3, 4)])
    [1, 2, 3, 3]
    >>> broadcast_prefix([1, 2, 3], [1, 2, {'a': 3, 'b': 4, 'c': (None, 5)}])
    [1, 2, 3, 3, 3, 3]

    Args:
        prefix_tree (pytree): A pytree with the same structure as a prefix of ``full_tree``.
        full_tree (pytree): A pytree with the same structure as a suffix of ``prefix_tree``.
        is_leaf (callable, optional): An extra leaf predicate function that will be called at each
            flattening step. The function should have a single argument with signature
            ``is_leaf(node) -> bool``. If it returns :data:`True`, the whole subtree being treated
            as a leaf. Otherwise, the default pytree registry will be used to determine a node is a
            leaf or not. If the function is not specified, the default pytree registry will be used.

    Returns:
        A list of leaves in ``prefix_tree`` broadcasted to match the number of leaves in ``full_tree``.
    TrV   r]   )rX   broadcast_prefix)r   r   r[   s      r;   r   r     s'    N "" r=   c                     t        |t              sJ t        dg|j                  z  |      }	 t	        | ||      S # t
        $ r Y y w xY w)Nr   rj   )rd   r   r   
num_leavesr   
ValueError)rZ   ra   r[   r   s       r;   _broadcast_to_and_flattenr   V  sS    
 h)))sX%8%88(CIiAA s   < 	AAprotocolc                     t        | t              st        dt        |        d      ddlm}m}  |t        dg| j                  z  |             } |||      S )z&Serialize a treespec to a JSON string.zVtreespec_dumps(spec): Expected `spec` to be instance of TreeSpec but got item of type rc   rK   )r"   r,   r   )r   )	rd   r   re   rf   rL   r"   r,   r   r   )ra   r   _tree_structure_treespec_dumpsorig_treespecs        r;   r,   r,   c  sa    h)--1(^,<A?
 	

 $NA39L9L3Lh$WXM=8<<r=   
serializedc                 j    ddl m}m}  ||       } |dg|j                  z  |      }t	        |      }|S )z*Deserialize a treespec from a JSON string.rK   )r   r-   r   )rL   r   r-   r   r"   )r   _tree_unflatten_treespec_loadsr   
dummy_treera   s         r;   r-   r-   s  s;    
 $J/M !}'?'?!?OJj)HOr=   c                       e Zd ZdefdZy)
_DummyLeafr4   c                      y)N*rt   )selfs    r;   __repr__z_DummyLeaf.__repr__  s    r=   N)__name__
__module____qualname__strr   rt   r=   r;   r   r     s    # r=   r   c                     t        t        | j                        D cg c]  }t                c}|       }t	        |      S c c}w r9   )r   ranger   r   repr)ra   _r   s      r;   r.   r.     s<    $X%8%89:!:J 
 	;s   Ac                       e Zd ZdedefdZy)LeafSpecMetainstancer4   c                 F    t        |t              xr |j                         S r9   )rd   r   r[   )r   r   s     r;   __instancecheck__zLeafSpecMeta.__instancecheck__  s    (H-D(2B2B2DDr=   N)r   r   r   objectr   r   rt   r=   r;   r   r     s    E& ET Er=   r   c                       e Zd ZddZy)r   c                 .    t        j                  d      S )NT)r^   )rX   treespec_leaf)rE   s    r;   __new__zLeafSpec.__new__  s    ##66r=   N)r4   r   )r   r   r   r   rt   r=   r;   r   r     s    7r=   r   )	metaclassc                     t        d      )a  Flattens a pytree like :func:`tree_flatten`, but also returns each leaf's key path.

    Args:
        tree: a pytree to flatten. If it contains a custom type, that type must be
            registered with an appropriate `tree_flatten_with_path_fn` when registered
            with :func:`register_pytree_node`.
        is_leaf: An extra leaf predicate function that will be called at each
            flattening step. The function should have a single argument with signature
            ``is_leaf(node) -> bool``. If it returns :data:`True`, the whole subtree being treated
            as a leaf. Otherwise, the default pytree registry will be used to determine a node is a
            leaf or not. If the function is not specified, the default pytree registry will be used.
    Returns:
        A tuple where the first element is a list of (key path, leaf) pairs, and the
        second element is a :class:`TreeSpec` representing the structure of the flattened
        tree.
    rI   rM   r_   s     r;   r   r     s    ( M
NNr=   c                     t        d      )a8  Gets the leaves of a pytree like ``tree_leaves`` and returns each leaf's key path.

    Args:
        tree: a pytree. If it contains a custom type, that type must be
            registered with an appropriate `tree_flatten_with_path_fn` when registered
            with :func:`register_pytree_node`.
        is_leaf: An extra leaf predicate function that will be called at each
            flattening step. The function should have a single argument with signature
            ``is_leaf(node) -> bool``. If it returns :data:`True`, the whole subtree being treated
            as a leaf. Otherwise, the default pytree registry will be used to determine a node is a
            leaf or not. If the function is not specified, the default pytree registry will be used.
    Returns:
        A list of (key path, leaf) pairs.
    rI   r   r_   s     r;   r!   r!     s    $ M
NNr=   c                    t        d      )a  Like :func:`tree_map`, but the provided callable takes an additional key path argument.

    Args:
        func: A function that takes ``2 + len(rests)`` arguments, to be applied at the
            corresponding leaves of the pytrees. The first positional argument
            to ``func`` is the key path of the leaf in question. The second
            positional argument is the value of the leaf.
        tree: A pytree to be mapped over, with each leaf providing the first positional
            argument to function ``func``.
        rests: A tuple of pytrees, each of which has the same structure as
            ``tree`` or has ``tree`` as a prefix.
        is_leaf: An extra leaf predicate function that will be called at each
            flattening step. The function should have a single argument with signature
            ``is_leaf(node) -> bool``. If it returns :data:`True`, the whole subtree being treated
            as a leaf. Otherwise, the default pytree registry will be used to determine a node is a
            leaf or not. If the function is not specified, the default pytree registry will be used.

    Returns
        A new pytree with the same structure as ``tree`` but with the value at each leaf given by
        ``func(keypath, x, *xs)`` where ``keypath`` is the key path at the
        corresponding leaf in ``tree``, ``x`` is the value at that leaf, and
        ``xs`` is the tuple of values at corresponding nodes in ``rests``.
    rI   r   rm   s       r;   r$   r$     s    : M
NNr=   kpc                     t        d      )z9Given a key path, return a pretty-printed representation.rI   r   )r   s    r;   r   r         
M
NNr=   objc                     t        d      )zAGiven an object and a key path, return the value at the key path.rI   r   )r   r   s     r;   r   r     r   r=   Tr9   )Y__doc__r>   r   r   typingr   r   r   r   r   r   r	   r
   r   r   typing_extensionsr   rX   r   torch.utils._pytreeutilsrL   r   __all__r/   r0   r1   r2   r   r   r   r   r   OpTreeUnflattenFuncr   r   r   KeyPathFlattenWithKeysFuncr@   r   r   FutureWarningrT   rN   r   r   r   r   r    r"   r#   r%   Type2Type3r   r   TypeAnyFn2Fn3FnFnAny	MapOnlyFnrv   r&   r'   r(   r)   r*   r+   r   r   intr,   r-   r   r.   rf   r   r   r   r!   r$   r   r   _cxx_pytree_imported_cxx_pytree_pending_importsr6   r7   rt   r=   r;   <module>r      s    
    )   % % ( F CLCLCLCL 	xtCy''9!::;(3-169:#7?@ y/9:  /!2G!;< 
#
xtE(C-4H/I3/N)OOP  *=  +/9==A:>>	c>>  >
 #3-> ""56> $$9:> ##67> 
>B I +/9==A0	c00  0
 #3-0 ""560 $$9:0 
0
0p +/9==A
	c

  

 #3-
 ""56
 $$9:
 

4 37-
-hx~./- 49h-`38C= 3H 3 3: 37 
 hx~./  c] J 37 
 hx~./  
#Y J 37 
 hx~./   N 37	.
38
.
. . hx~./	.
 .j 37	#
38
#
# # hx~./	#
 #L 	d1gtAwd1gtAwQ'(wDIuT#Y^4eooEFGDIuT#Y^445Gad}a aAg"#qc1f#aS(C5#:../	
 
eAqDk iAq#I6O  
 
eAq!Gn 3q!QPS|CT9U  
 
d1g )Bq#vJ2G  

 
g )E#J2G  
 
hud{&; 	%PS*@U  
+"7HcUD[,A#AB+uSz+\ 

 37	!!W
QV*  hx~./	
  
 

 37	"1a4[
aCi.  hx~./	
  
 

 37	"1a7^
aAsl
  hx~./	
  
 

 37	%seTk2
*  hx~./	
  
 37	T"7HcUD[,A#ABT
*T T hx~./	T
 T 

 37	!!W
QV*  hx~./	
  
 

 37	"1a4[
aCi.  hx~./	
  
 

 37	"1a7^
aAsl
  hx~./	
  
 

 37	%seTk2
*  hx~./	
  
 37	U"7HcUD[,A#ABU
*U U hx~./	U
 U 37%
C5$;
%
% hx~./% 
	% 37%
C5$;
%
% hx~./% 
	% 

 37	!W
QW+  hx~./	
 
 
 

 37	1a4[
aDj/  hx~./	
 
 
 

 37	1a7^
aAtm
  hx~./	
 
 
 37	MM
+M M hx~./	M
 
M 

 37	!W
QW+  hx~./	
 
 
 

 37	1a4[
aDj/  hx~./	
 
 
 

 37	1a7^
aAtm
  hx~./	
 
 
 37	MM
+M M hx~./	M
 
M 37--- hx~./- 
#Y	-v 37



 hx~./
 d3i	
=X =# =# = 
s 
x 
 
h 3 E4> E
7x< 7 37O
Ohx~./O 4gsl#$h./O2 37O
Ohx~./O 
%
O2 37	O
38
O
O O hx~./	O
 O@Ow O3 O
O O' Oc O
  $ 77 3LD&!42623r=   