
    $Shv                       U d Z ddlmZ ddlZddlZddlZddlZddlmZm	Z	m
Z
mZ ddlmZmZ ddlmZ ddlmZmZmZmZmZmZmZmZ ddlmZ ddlmZmZmZm Z m!Z!m"Z" dd	l#m$Z$m%Z%m&Z&m'Z'm(Z( dd
l)m*Z*m+Z+m,Z, er/ddl-Z-ddl.m/Z/m0Z0m1Z1 ddl#m2Z2m3Z3m4Z4m5Z5m6Z6  ede7e4                   Z8g dZ9ej:        dk    rddini Z; ej<        dddddde; G d dee&                               Z=[; G d d          Z> e>            Z?de@d<    e            ZAde@d<   [>erJddlBmCZC  eCd          ZD ed          ZE eCd          ZF ed           ZG G d! d"eeDeEeFeGf                   ZHdd'ZIed(d)dd.            ZJe	 dd(d)dd1            ZJ	 dd(d)dd4ZJ eIeJ          ed5dd=            ZK[J[Ie	 dddd>ddB            ZLeddC            ZL	 dddd>ddFZLddGZMejN        ddK            ZOddOZPddRZQddUZRddYZSdd[ZTdd_ZUdd`ZVdddZWddiZXddjZYddkZZddmZ[ddnZ\ddqZ]ddtZ^dduZ_ddvZ`ddzZadd}ZbddZcddZdddZeddZf e7d           e= e7d          eQeRe e$jg                  eh e=eheSeTe!e$ji                  ej e=ejeUeVe!e$jk                  el e=eleWeXee$jm                  e e=eecedee$jn                  e e=ee[e\ee$jo                  e	 e=e	e]e^ee$jp                  e
 e=e
eaebe!e$jq                  e% e=e%eeefe"e$jr                  i	Zsde@d<    e=eleYeZee$jm                  Zt e=e	e_e`ee$jp                  ZudS )z&Registry for custom pytree node types.    )annotationsN)OrderedDictdefaultdictdeque
namedtuple)
itemgettermethodcaller)Lock)TYPE_CHECKINGAnyCallableClassVarGeneric
NamedTupleTypeVaroverload)	AutoEntryMappingEntryNamedTupleEntryPyTreeEntrySequenceEntryStructSequenceEntry)
PyTreeKindStructSequenceTis_namedtuple_classis_structseq_class)safe_ziptotal_order_sortedunzip2)
Collection	GeneratorIterable)KTVTCustomTreeNodeFlattenFuncUnflattenFuncCustomTreeNodeType)bound)register_pytree_noderegister_pytree_node_classunregister_pytree_nodedict_insertion_ordered   
   slotsT)initrepreqfrozenc                      e Zd ZU dZded<   ded<   ded<   ej        dk    rd	ed
<   eZded<   e	j
        Zded<   dZded<   dS )PyTreeNodeRegistryEntryz>A dataclass that stores the information of a pytree node type.zbuiltins.type[Collection[T]]typeFlattenFunc[T]flatten_funcUnflattenFunc[T]unflatten_funcr/   zdataclasses.KW_ONLY_zbuiltins.type[PyTreeEntry]path_entry_typer   kind str	namespaceN)__name__
__module____qualname____doc____annotations__sysversion_infor   r?   r   CUSTOMr@   rC        U/var/www/html/movieo_spanner_bot/venv/lib/python3.11/site-packages/optree/registry.pyr8   r8   @   s         HH&&&&    $$$$
7""2;O;;;;!(D((((IrM   r8   c                  &    e Zd ZU dZded<   ddZdS )	GlobalNamespacerL   zClassVar[tuple[()]]	__slots__returnrB   c                   dS )Nz<GLOBAL NAMESPACE>rL   )selfs    rN   __repr__zGlobalNamespace.__repr__W   s    ##rM   N)rR   rB   )rD   rE   rF   rQ   rH   rU   rL   rM   rN   rP   rP   T   s;         %'I''''$ $ $ $ $ $rM   rP   rB   __GLOBAL_NAMESPACEr
   __REGISTRY_LOCK)	ParamSpec_P_T_GetP_GetTc                      e Zd ZddZddZdS )_CallableWithGetargs_P.argskwargs	_P.kwargsrR   rZ   c                   t           NNotImplementedErrorrT   r_   ra   s      rN   __call__z_CallableWithGet.__call__i       %%rM   
_GetP.args_GetP.kwargsr\   c                   t           rd   re   rg   s      rN   getz_CallableWithGet.getm   ri   rM   N)r_   r`   ra   rb   rR   rZ   )r_   rj   ra   rk   rR   r\   )rD   rE   rF   rh   rm   rL   rM   rN   r^   r^   h   s<        	& 	& 	& 	&	& 	& 	& 	& 	& 	&rM   r^   rm   Callable[_GetP, _GetT]rR   DCallable[[Callable[_P, _T]], _CallableWithGet[_P, _T, _GetP, _GetT]]c                    d fd}|S )NfuncCallable[_P, _T]rR   &_CallableWithGet[_P, _T, _GetP, _GetT]c                   | _         | S rd   )rm   )rq   rm   s    rN   	decoratorz_add_get.<locals>.decoratorx   s    rM   )rq   rr   rR   rs   rL   )rm   ru   s   ` rN   _add_getrv   q   s)          rM   rA   )rC   clsr9   rC   PyTreeNodeRegistryEntry | Nonec                  d S rd   rL   rw   rC   s     rN   pytree_node_registry_getr{      s	     &)SrM   None#dict[type, PyTreeNodeRegistryEntry]c                  d S rd   rL   rz   s     rN   r{   r{      s	     +.#rM   type | NoneDdict[type, PyTreeNodeRegistryEntry] | PyTreeNodeRegistryEntry | Nonec                 |t           u rd}| 0| t          ur't          j        |           st	          d| d          t          |t                    st	          d|d          | t          |dh          t          5  fdt          
                                D             }ddd           n# 1 swxY w Y   t          j        |          rt          |t          <   t          |t           <   |S |dk    r t                              || f          }||S t          j        |          r | t          u rt          S | t           u rt          S t                              |           }||S t%          |           rt                              t&                    S t)          |           rt                              t                    S dS )a  Lookup the pytree node registry.

    >>> register_pytree_node.get()  # doctest: +IGNORE_WHITESPACE,ELLIPSIS
    {
        <class 'NoneType'>: PyTreeNodeRegistryEntry(
            type=<class 'NoneType'>,
            flatten_func=<function ...>,
            unflatten_func=<function ...>,
            path_entry_type=<class 'optree.PyTreeEntry'>,
            kind=<PyTreeKind.NONE: 2>,
            namespace=''
        ),
        <class 'tuple'>: PyTreeNodeRegistryEntry(
            type=<class 'tuple'>,
            flatten_func=<function ...>,
            unflatten_func=<function ...>,
            path_entry_type=<class 'optree.SequenceEntry'>,
            kind=<PyTreeKind.TUPLE: 3>,
            namespace=''
        ),
        <class 'list'>: PyTreeNodeRegistryEntry(
            type=<class 'list'>,
            flatten_func=<function ...>,
            unflatten_func=<function ...>,
            path_entry_type=<class 'optree.SequenceEntry'>,
            kind=<PyTreeKind.LIST: 4>,
            namespace=''
        ),
        ...
    }
    >>> register_pytree_node.get(defaultdict)  # doctest: +IGNORE_WHITESPACE,ELLIPSIS
    PyTreeNodeRegistryEntry(
        type=<class 'collections.defaultdict'>,
        flatten_func=<function ...>,
        unflatten_func=<function ...>,
        path_entry_type=<class 'optree.MappingEntry'>,
        kind=<PyTreeKind.DEFAULTDICT: 8>,
        namespace=''
    )
    >>> register_pytree_node.get(frozenset)  # frozenset is considered as a leaf node
    None

    Args:
        cls (type or None, optional): The class of the pytree node to retrieve. If not provided, all
            the registered pytree nodes in the namespace are returned.
        namespace (str, optional): The namespace of the registry to retrieve. If not provided, the
            global namespace is used.

    Returns:
        If the ``cls`` is not provided, a dictionary of all the registered pytree nodes in the
        namespace is returned. If the ``cls`` is provided, the corresponding registry entry is
        returned if the ``cls`` is registered as a pytree node. Otherwise, :data:`None` is returned,
        i.e., the ``cls`` is represented as a leaf node.
    rA   NzExpected a class or None, got .$The namespace must be a string, got c                2    i | ]}|j         v |j        |S rL   )rC   r9   ).0handler
namespacess     rN   
<dictcomp>z,pytree_node_registry_get.<locals>.<dictcomp>   s5       $
22 g222rM   )rV   r   inspectisclass	TypeError
isinstancerB   	frozensetrW   _NODETYPE_REGISTRYvalues_Cis_dict_insertion_ordered&_DICT_INSERTION_ORDERED_REGISTRY_ENTRYdict-_DEFAULTDICT_INSERTION_ORDERED_REGISTRY_ENTRYr   rm   r   r   r   )rw   rC   registryr   r   s       @rN   r{   r{      s'   x &&&	z!!$$ " AAAABBBi%% 
A9AAA
 
 	
 {	2//
 	 	   188::  H	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 '	22 	RCHTN$QH[!B$(()S)9::N	#I.. A$;;99+@@ $$S))G# 6!%%n5553 2!%%j1114s   &B33B7:B7)r?   r;   r:   r=   r<   type[Collection[T]]r?   type[PyTreeEntry]c              "   t          j        |           st          d| d          t          j        |          rt          |t                    st          d|d          |t
          ur(t          |t                    st          d|d          |dk    rt          d          |t
          u r| }d}n|| f}t          5  t          j        | ||||           t          | ||||          t          |<   ddd           n# 1 swxY w Y   | S )	a  Extend the set of types that are considered internal nodes in pytrees.

    See also :func:`register_pytree_node_class` and :func:`unregister_pytree_node`.

    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_func (callable): A function to be used during flattening, taking an instance of ``cls``
            and returning a triple or optionally a pair, with (1) an iterable for the children to be
            flattened recursively, and (2) some hashable metadata to be stored in the treespec and
            to be passed to the ``unflatten_func``, and (3) (optional) an iterable for the tree path
            entries to the corresponding children. If the entries are not provided or given by
            :data:`None`, then `range(len(children))` will be used.
        unflatten_func (callable): A function taking two arguments: the metadata that was returned
            by ``flatten_func`` and stored in the treespec, and the unflattened children. The
            function should return an instance of ``cls``.
        path_entry_type (type, optional): The type of the path entry to be used in the treespec.
            (default: :class:`AutoEntry`)
        namespace (str): A non-empty string that uniquely identifies the namespace of the type registry.
            This is used to isolate the registry from other modules that might register a different
            custom behavior for the same type.

    Returns:
        The same type as the input ``cls``.

    Raises:
        TypeError: If the input type is not a class.
        TypeError: If the path entry class is not a subclass of :class:`PyTreeEntry`.
        TypeError: If the namespace is not a string.
        ValueError: If the namespace is an empty string.
        ValueError: If the type is already registered in the registry.

    Examples:
        >>> # Registry a Python type with lambda functions
        >>> register_pytree_node(
        ...     set,
        ...     lambda s: (sorted(s), None, None),
        ...     lambda _, children: set(children),
        ...     namespace='set',
        ... )
        <class 'set'>

        >>> # Register a Python type into a namespace
        >>> import torch
        >>> register_pytree_node(
        ...     torch.Tensor,
        ...     flatten_func=lambda tensor: (
        ...         (tensor.cpu().detach().numpy(),),
        ...         {'dtype': tensor.dtype, 'device': tensor.device, 'requires_grad': tensor.requires_grad},
        ...     ),
        ...     unflatten_func=lambda metadata, children: torch.tensor(children[0], **metadata),
        ...     namespace='torch2numpy',
        ... )
        <class 'torch.Tensor'>

        >>> # doctest: +SKIP
        >>> tree = {'weight': torch.ones(size=(1, 2)).cuda(), 'bias': torch.zeros(size=(2,))}
        >>> tree
        {'weight': tensor([[1., 1.]], device='cuda:0'), 'bias': tensor([0., 0.])}

        >>> # Flatten without specifying the namespace
        >>> tree_flatten(tree)  # `torch.Tensor`s are leaf nodes
        ([tensor([0., 0.]), tensor([[1., 1.]], device='cuda:0')], PyTreeSpec({'bias': *, 'weight': *}))

        >>> # Flatten with the namespace
        >>> tree_flatten(tree, namespace='torch2numpy')
        (
            [array([0., 0.], dtype=float32), array([[1., 1.]], dtype=float32)],
            PyTreeSpec(
                {
                    'bias': CustomTreeNode(Tensor[{'dtype': torch.float32, 'device': device(type='cpu'), 'requires_grad': False}], [*]),
                    'weight': CustomTreeNode(Tensor[{'dtype': torch.float32, 'device': device(type='cuda', index=0), 'requires_grad': False}], [*])
                },
                namespace='torch2numpy'
            )
        )

        >>> # Register the same type with a different namespace for different behaviors
        >>> def tensor2flatparam(tensor):
        ...     return [torch.nn.Parameter(tensor.reshape(-1))], tensor.shape, None
        ...
        ... def flatparam2tensor(metadata, children):
        ...     return children[0].reshape(metadata)
        ...
        ... register_pytree_node(
        ...     torch.Tensor,
        ...     flatten_func=tensor2flatparam,
        ...     unflatten_func=flatparam2tensor,
        ...     namespace='tensor2flatparam',
        ... )
        <class 'torch.Tensor'>

        >>> # Flatten with the new namespace
        >>> tree_flatten(tree, namespace='tensor2flatparam')
        (
            [
                Parameter containing: tensor([0., 0.], requires_grad=True),
                Parameter containing: tensor([1., 1.], device='cuda:0', requires_grad=True)
            ],
            PyTreeSpec(
                {
                    'bias': CustomTreeNode(Tensor[torch.Size([2])], [*]),
                    'weight': CustomTreeNode(Tensor[torch.Size([1, 2])], [*])
                },
                namespace='tensor2flatparam'
            )
        )
    Expected a class, got r   (Expected a subclass of PyTreeEntry, got r   rA   (The namespace cannot be an empty string.r?   rC   N)r   r   r   
issubclassr   rV   r   rB   
ValueErrorrW   r   register_noder8   r   )rw   r;   r=   r?   rC   registration_keys         rN   r+   r+      s   ~ ?3 ;9999:::OO,, YO[1Y1Y YW?WWWXXX***:i3M3M*MyMMMNNNBCDDD &&&		%s+	 
 

	
 	
 	
 0G+0
 0
 0
+,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 Js   5DDDr   
str | Nonetype[PyTreeEntry] | None2Callable[[CustomTreeNodeType], CustomTreeNodeType]c                  d S rd   rL   rw   r?   rC   s      rN   r,   r,     s	     :=rM   c                  d S rd   rL   r   s      rN   r,   r,     s	     rM   CustomTreeNodeType | str | NoneGCustomTreeNodeType | Callable[[CustomTreeNodeType], CustomTreeNodeType]c                 | t           u st          | t                    r+t          d          | dk    rt          d          d| c} t          d          t           ur't          t                    st	          d          dk    rt          d          | 	dfd
}|S t          j        |           st	          d| d          t          | dt                    t          j                  rt          t                    st	          dd          t          | t          d          | j                   | S )a
  Extend the set of types that are considered internal nodes in pytrees.

    See also :func:`register_pytree_node` and :func:`unregister_pytree_node`.

    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, optional): A Python type to treat as an internal pytree node.
        path_entry_type (type, optional): The type of the path entry to be used in the treespec.
            (default: :class:`AutoEntry`)
        namespace (str, optional): A non-empty string that uniquely identifies the namespace of the
            type registry. This is used to isolate the registry from other modules that might
            register a different custom behavior for the same type.

    Returns:
        The same type as the input ``cls`` if the argument presents. Otherwise, return a decorator
        function that registers the class as a pytree node.

    Raises:
        TypeError: If the path entry class is not a subclass of :class:`PyTreeEntry`.
        TypeError: If the namespace is not a string.
        ValueError: If the namespace is an empty string.
        ValueError: If the type is already registered in the registry.

    This function is a thin wrapper around :func:`register_pytree_node`, and provides a
    class-oriented interface:

    .. code-block:: python

        @register_pytree_node_class(namespace='foo')
        class Special:
            TREE_PATH_ENTRY_TYPE = GetAttrEntry

            def __init__(self, x, y):
                self.x = x
                self.y = y

            def tree_flatten(self):
                return ((self.x, self.y), None, ('x', 'y'))

            @classmethod
            def tree_unflatten(cls, metadata, children):
                return cls(*children)

        @register_pytree_node_class('mylist')
        class MyList(UserList):
            TREE_PATH_ENTRY_TYPE = SequenceEntry

            def tree_flatten(self):
                return self.data, None, None

            @classmethod
            def tree_unflatten(cls, metadata, children):
                return cls(*children)
    Nz?Cannot specify `namespace` when the first argument is a string.rA   r   z<Must specify `namespace` when the first argument is a class.r   rw   r)   rR   c               (    t          |           S )Nr   )r,   )rw   rC   r?   s    rN   ru   z-register_pytree_node_class.<locals>.decorator  s#    - /#   rM   r   r   TREE_PATH_ENTRY_TYPEr   tree_flattenr   )rw   r)   rR   r)   )rV   r   rB   r   r   r   r   getattrr   r   r   r+   r	   tree_unflatten)rw   r?   rC   ru   s    `` rN   r,   r,     s   L    JsC$8$8  ^___"99GHHHsYWXXX***:i3M3M*LyLLMMMBCDDD
{	 	 	 	 	 	 	 ?3 ;9999:::!#'=yIIOO,, YO[1Y1Y YW?WWWXXX^$$'    JrM   c                 t          j        |           st          d| d          |t          ur(t	          |t
                    st          d|d          |dk    rt          d          |t          u r| }d}n|| f}t          5  t          j	        | |           t                              |          cddd           S # 1 swxY w Y   dS )a  Remove a type from the pytree node registry.

    See also :func:`register_pytree_node` and :func:`register_pytree_node_class`.

    This function is the inverse operation of function :func:`register_pytree_node`.

    Args:
        cls (type): A Python type to remove from the pytree node registry.
        namespace (str): The namespace of the pytree node registry to remove the type from.

    Returns:
        The removed registry entry.

    Raises:
        TypeError: If the input type is not a class.
        TypeError: If the namespace is not a string.
        ValueError: If the namespace is an empty string.
        ValueError: If the type is a built-in type that cannot be unregistered.
        ValueError: If the type is not found in the registry.

    Examples:
        >>> # Register a Python type with lambda functions
        >>> register_pytree_node(
        ...     set,
        ...     lambda s: (sorted(s), None, None),
        ...     lambda _, children: set(children),
        ...     namespace='temp',
        ... )
        <class 'set'>

        >>> # Unregister the Python type
        >>> unregister_pytree_node(set, namespace='temp')
    r   r   r   rA   r   N)r   r   r   rV   r   rB   r   rW   r   unregister_noder   pop)rw   rC   r   s      rN   r-   r-   %  s3   D ?3 ;9999:::***:i3M3M*MyMMMNNNBCDDD &&&		%s+	 8 8
3	***!%%&6778 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8s   /CC
CmodeboolGenerator[None]c            #  @  K   |t           ur(t          |t                    st          d|d          |dk    rt	          d          |t           u rd}t
          5  t          j        |d          }t          j        t          |           |           ddd           n# 1 swxY w Y   	 dV  t
          5  t          j        ||           ddd           dS # 1 swxY w Y   dS # t
          5  t          j        ||           ddd           w # 1 swxY w Y   w xY w)a  Context manager to temporarily set the dictionary sorting mode.

    This context manager is used to temporarily set the dictionary sorting mode for a specific
    namespace. The dictionary sorting mode is used to determine whether the keys of a dictionary
    should be sorted or keeping the insertion order when flattening a pytree.

    >>> tree = {'b': (2, [3, 4]), 'a': 1, 'c': None, 'd': 5}
    >>> tree_flatten(tree)  # doctest: +IGNORE_WHITESPACE
    (
        [1, 2, 3, 4, 5],
        PyTreeSpec({'a': *, 'b': (*, [*, *]), 'c': None, 'd': *})
    )
    >>> with dict_insertion_ordered(True, namespace='some-namespace'):  # doctest: +IGNORE_WHITESPACE
    ...     tree_flatten(tree, namespace='some-namespace')
    (
        [2, 3, 4, 1, 5],
        PyTreeSpec({'b': (*, [*, *]), 'a': *, 'c': None, 'd': *}, namespace='some-namespace')
    )

    .. warning::
        The dictionary sorting mode is a global setting and is **not thread-safe**. It is
        recommended to use this context manager in a single-threaded environment.

    Args:
        mode (bool): The dictionary sorting mode to set.
        namespace (str): The namespace to set the dictionary sorting mode for.
    r   r   rA   r   F)inherit_global_namespaceN)
rV   r   rB   r   r   rW   r   r   set_dict_insertion_orderedr   )r   rC   prevs      rN   r.   r.   Z  s     : ***:i3M3M*MyMMMNNNBCDDD&&&		 = =+IPUVVV
%d4jj)<<<= = = = = = = = = = = = = = =; 	; 	;)$	:::	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	;_ 	; 	;)$	:::	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	;sT   9B  B$'B$,C' 7CC!C'D/DDDDDDitemsIterable[tuple[KT, VT]]list[tuple[KT, VT]]c               >    t          | t          d                    S )Nr   )key)r   r   )r   s    rN   _sorted_itemsr     s    eA7777rM   r>   tuple[tuple[()], None]c                   dS )N)rL   NrL   )r>   s    rN   _none_flattenr     s    8rM   childrenIterable[Any]c               ~    t                      }t          t          |          |          |urt          d          d S )NzExpected no children.)objectnextiterr   )r>   r   sentinels      rN   _none_unflattenr     s=    xxHDNNH%%X550111 65rM   tuptuple[T, ...]tuple[tuple[T, ...], None]c               
    | d fS rd   rL   r   s    rN   _tuple_flattenr         9rM   Iterable[T]c                    t          |          S rd   )tupler>   r   s     rN   _tuple_unflattenr     s    ??rM   lstlist[T]tuple[list[T], None]c               
    | d fS rd   rL   )r   s    rN   _list_flattenr     r   rM   c                    t          |          S rd   )listr   s     rN   _list_unflattenr     s    >>rM   dctdict[KT, VT]/tuple[tuple[VT, ...], list[KT], tuple[KT, ...]]c                   t          t          |                                                     \  }}|t          |          |fS rd   )r    r   r   r   r   keysr   s      rN   _dict_flattenr     s6    -		4455LD&4::t##rM   r   list[KT]r   Iterable[VT]c               <    t          t          | |                    S rd   r   r   r   r   s     rN   _dict_unflattenr         v&&'''rM   c               n    t          |                                           \  }}|t          |          |fS rd   r    r   r   r   s      rN   _dict_insertion_ordered_flattenr     0     #))++&&LD&4::t##rM   c               <    t          t          | |                    S rd   r   r   s     rN   !_dict_insertion_ordered_unflattenr     r   rM   OrderedDict[KT, VT]c               n    t          |                                           \  }}|t          |          |fS rd   r   r   s      rN   _ordereddict_flattenr     r   rM   c               <    t          t          | |                    S rd   )r   r   r   s     rN   _ordereddict_unflattenr     s    xf--...rM   defaultdict[KT, VT]Otuple[tuple[VT, ...], tuple[Callable[[], VT] | None, list[KT]], tuple[KT, ...]]c               @    t          |           \  }}}|| j        |f|fS rd   )r   default_factoryr   r   r   entriess       rN   _defaultdict_flattenr     s-     *#..FD'C'.77rM   metadata!tuple[Callable[[], VT], list[KT]]c               H    | \  }}t          |t          ||                    S rd   )r   r   r   r   r   r   s       rN   _defaultdict_unflattenr    s(    
 %OTf(E(EFFFrM   c               @    t          |           \  }}}|| j        |f|fS rd   )r   r   r   s       rN   &_defaultdict_insertion_ordered_flattenr    s-     <C@@FD'C'.77rM   c               H    | \  }}t          |t          ||                    S rd   )r   r   r  s       rN   (_defaultdict_insertion_ordered_unflattenr    s*    
 %OT(I$PV(W(WXXXrM   deqdeque[T]tuple[deque[T], int | None]c                   | | j         fS rd   maxlen)r  s    rN   _deque_flattenr    s    
?rM   r  
int | Nonec               $    t          ||           S )Nr  )r   )r  r   s     rN   _deque_unflattenr    s    &))))rM   NamedTuple[T])tuple[tuple[T, ...], type[NamedTuple[T]]]c               $    | t          |           fS rd   r9   r   s    rN   _namedtuple_flattenr        S		>rM   type[NamedTuple[T]]c                    | | S rd   rL   rw   r   s     rN   _namedtuple_unflattenr    s    3>rM   seqStructSequence[T]-tuple[tuple[T, ...], type[StructSequence[T]]]c               $    | t          |           fS rd   r  )r  s    rN   _structseq_flattenr    r  rM   type[StructSequence[T]]c                    | |          S rd   rL   r  s     rN   _structseq_unflattenr"    s    
 3x==rM   )r?   r@   z6dict[type | tuple[str, type], PyTreeNodeRegistryEntry]r   rL   )rm   rn   rR   ro   )rw   r9   rC   rB   rR   rx   rd   )rw   r|   rC   rB   rR   r}   )rw   r   rC   rB   rR   r   )r;   r:   r=   r<   rw   r   r?   r   rC   rB   rR   r   )rw   r   r?   r   rC   r   rR   r   )rw   r)   r?   r   rC   rB   rR   r)   )rw   r   r?   r   rC   r   rR   r   )rw   r9   rC   rB   rR   r8   )r   r   rC   rB   rR   r   )r   r   rR   r   )r>   r|   rR   r   )r>   r|   r   r   rR   r|   )r   r   rR   r   )r>   r|   r   r   rR   r   )r   r   rR   r   )r>   r|   r   r   rR   r   )r   r   rR   r   )r   r   r   r   rR   r   )r   r   rR   r   )r   r   r   r   rR   r   )r   r   rR   r   )r   r   r   r   rR   r   )r  r  rR   r	  )r  r  r   r   rR   r  )r   r  rR   r  )rw   r  r   r   rR   r  )r  r  rR   r  )rw   r   r   r   rR   r  )vrG   
__future__r   
contextlibdataclassesr   rI   collectionsr   r   r   r   operatorr   r	   	threadingr
   typingr   r   r   r   r   r   r   r   	optree._Cr   optree.accessorsr   r   r   r   r   r   optree.typingr   r   r   r   r   optree.utilsr   r   r    builtinscollections.abcr!   r"   r#   r$   r%   r&   r'   r(   r9   r)   __all__rJ   SLOTS	dataclassr8   rP   rV   rH   rW   typing_extensionsrX   rY   rZ   r[   r\   r^   rv   r{   r+   r,   r-   contextmanagerr.   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r  r  r  r  r  r  r"  NONEr   TUPLEr   LISTr   DICT
NAMEDTUPLEORDEREDDICTDEFAULTDICTDEQUESTRUCTSEQUENCEr   r   r   rL   rM   rN   <module>r>     s(	   - , , # " " " " "          



 C C C C C C C C C C C C - - - - - - - -       a a a a a a a a a a a a a a a a a a a a                      a ` ` ` ` ` ` ` ` ` ` ` ` ` = = = = = = = = = =  SOOO??????????PPPPPPPPPPPPPP !!5T.=QRRR   +w66$B KDtTKKUKK    gaj   LK 
$ $ $ $ $ $ $ $ */++  + + + +      &++++++	4B	BIgEGGE& & & & &72r5%#78 & & &    

 	) ) ) ) ) 
) 
. 	. . . . . 
. h 	h h h h h hV 

"## *3] ] ] ] ] $#]@ h 
= 15 = = = = = 
= 
   
 ,0m 15 m m m m m m`28 28 28 28j +; +; +; +;\8 8 8 8   2 2 2 2            $ $ $ $
( ( ( (	$ 	$ 	$ 	$( ( ( (	$ 	$ 	$ 	$/ / / /	8 	8 	8 	8G G G G	8 	8 	8 	8Y Y Y Y   * * * *   
          	DJJ''T

#_   
""%   	
!
!%_   	
!
!$_   '''"   (($#   (($#   
""%   +++&  s@N  @ @ @ @F *A)@#% 	* * * & 1H0G*, 		1 1 1 - - -rM   