§
    5P„jm‚  ã                  ó–  — 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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)m*Z*m+Z+ dd
l,m-Z-m.Z.m/Z/ er/ddl0Z0ddl1m2Z2m3Z3m4Z4 ddl$m5Z5m6Z6m7Z7m8Z8m9Z9  ede:e7         ¬¦  «        Z;g d¢Z<ej=        dk    rddini Z> ej?        dŒdddddœe>¤Ž G d„ dee)         ¦  «        ¦   «         Z@[> G d„ d¦  «        ZA eA¦   «         ZBdeCd<    e¦   «         ZDdeCd<   [AerJddlEmFZF  eFd¦  «        ZG ed¦  «        ZH eFd¦  «        ZI ed ¦  «        ZJ G d!„ d"eeGeHeIeJf         ¦  «        ZKd�d'„ZLed(d)œdŽd.„¦   «         ZMe	 d�d(d)œd�d1„¦   «         ZM	 d�d(d)œd‘d4„ZM eLeM¦  «        ed5œd’d=„¦   «         ZN[M[Le	 d�ddd>œd“dB„¦   «         ZOed”dC„¦   «         ZO	 d�ddd>œd•dF„ZOd–dG„ZPejQ        d—dK„¦   «         ZRd˜dO„ZSd™dR„ZTdšdU„ZUd›dY„ZVdœd[„ZWd�d_„ZXdžd`„ZYdŸdd„ZZd di„Z[dŸdj„Z\d dk„Z]d¡dm„Z^d¢dn„Z_d£dq„Z`d¤dt„Zad£du„Zbd¤dv„Zcd¥dz„Zdd¦d}„Zed§d€„Zfd¨d‚„Zgd©d†„Zhdªdˆ„Zi e:d¦  «         e@ e:d¦  «        eTeUe!e'jj        ¬‰¦  «        ek e@ekeVeWe"e'jl        ¬‰¦  «        em e@emeXeYe"e'jn        ¬‰¦  «        eo e@eoeZe[ee'jp        ¬‰¦  «        e e@eefege e'jq        ¬‰¦  «        e	 e@e	e^e_ee'jr        ¬‰¦  «        e
 e@e
e`eaee'js        ¬‰¦  «        e e@eedeee"e'jt        ¬‰¦  «        e( e@e(eheie#e'ju        ¬‰¦  «        i	ZvdŠeCd‹<    e@eoe\e]ee'jp        ¬‰¦  «        Zw e@e
ebecee'js        ¬‰¦  «        Zxd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)ÚChildrenÚMetaDataÚ
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_funcr1   zdataclasses.KW_ONLYÚ_zbuiltins.type[PyTreeEntry]Úpath_entry_typer   ÚkindÚ ÚstrÚ	namespaceN)Ú__name__Ú
__module__Ú__qualname__Ú__doc__Ú__annotations__ÚsysÚversion_infor   rA   r   ÚCUSTOMrB   rE   © ó    úT/root/disk_3tb/conda_envs/Huy-visual/lib/python3.11/site-packages/optree/registry.pyr:   r:   I   sŒ   € € € € € € àHÐHà&Ð&Ð&Ñ&Ø Ð Ð Ñ Ø$Ð$Ð$Ñ$à
Ô˜7Ò"Ð"ØÐÐÑà2;€OÐ;Ð;Ð;Ñ;Ø!Ô(€DÐ(Ð(Ð(Ñ(Ø€IÐÐÐÑÐÐrO   r:   c                  ó&   — e Zd ZU dZded<   dd„ZdS )	ÚGlobalNamespacerN   zClassVar[tuple[()]]Ú	__slots__ÚreturnrD   c               ó   — dS )Nz<GLOBAL NAMESPACE>rN   ©Úselfs    rP   Ú__repr__zGlobalNamespace.__repr__`   s   € Ø#Ð#rO   N)rT   rD   )rF   rG   rH   rS   rJ   rX   rN   rO   rP   rR   rR   ]   s;   € € € € € € Ø%'€IÐ'Ð'Ð'Ñ'ð$ð $ð $ð $ð $ð $rO   rR   rD   Ú__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.kwargsrT   r]   c               ó   — t           ‚©N©ÚNotImplementedError©rW   rb   rd   s      rP   Ú__call__z_CallableWithGet.__call__r   ó   € Ý%Ð%rO   ú
_GetP.argsú_GetP.kwargsr_   c               ó   — t           ‚rg   rh   rj   s      rP   Úgetz_CallableWithGet.getv   rl   rO   N)rb   rc   rd   re   rT   r]   )rb   rm   rd   rn   rT   r_   )rF   rG   rH   rk   rp   rN   rO   rP   ra   ra   q   s<   € € € € € ð	&ð 	&ð 	&ð 	&ð	&ð 	&ð 	&ð 	&ð 	&ð 	&rO   ra   rp   úCallable[_GetP, _GetT]rT   úDCallable[[Callable[_P, _T]], _CallableWithGet[_P, _T, _GetP, _GetT]]c               ó   ‡ — dˆ fd„}|S )NÚfuncúCallable[_P, _T]rT   ú&_CallableWithGet[_P, _T, _GetP, _GetT]c               ó   •— ‰| _         | S rg   )rp   )rt   rp   s    €rP   Ú	decoratorz_add_get.<locals>.decorator�   s   ø€ ØˆŒØˆrO   )rt   ru   rT   rv   rN   )rp   rx   s   ` rP   Ú_add_getry   z   s)   ø€ ðð ð ð ð ð ð ÐrO   rC   )rE   Úclsr;   rE   úPyTreeNodeRegistryEntry | Nonec              ó   — d S rg   rN   ©rz   rE   s     rP   Úpytree_node_registry_getr~   ˆ   s	   € ð &) SrO   ÚNoneú#dict[type, PyTreeNodeRegistryEntry]c              ó   — d S rg   rN   r}   s     rP   r~   r~   ‘   s	   € ð +.¨#rO   útype | NoneúDdict[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Ž  Look up 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.
    rC   NzExpected a class or None, got ú.ú$The namespace must be a string, got c                ó2   •— i | ]}|j         ‰v ¯|j        |“ŒS rN   )rE   r;   )Ú.0ÚhandlerÚ
namespacess     €rP   ú
<dictcomp>z,pytree_node_registry_get.<locals>.<dictcomp>ç   s5   ø€ ð ð ð àØÔ$¨
Ð2Ð2ð ”˜gà2Ð2Ð2rO   )rY   r   ÚinspectÚisclassÚ	TypeErrorÚ
isinstancerD   Ú	frozensetrZ   Ú_NODETYPE_REGISTRYÚvaluesÚ_CÚis_dict_insertion_orderedÚ&_DICT_INSERTION_ORDERED_REGISTRY_ENTRYÚdictÚ-_DEFAULTDICT_INSERTION_ORDERED_REGISTRY_ENTRYr   rp   r   r   r   )rz   rE   Úregistryr‰   rŠ   s       @rP   r~   r~   ›   s'  ø€ ðx Õ&Ð&Ð&Øˆ	àˆØ•zÐ!Ð!Ý” Ñ$Ô$ð "õ ÐA¸ÐAÐAÐAÑBÔBÐBÝ�i¥Ñ%Ô%ð 
ÝØA°9ÐAÐAÐAñ
ô 
ð 	
ð €{Ý 	¨2˜Ñ/Ô/ˆ
Ýð 	ð 	ðð ð ð å1×8Ò8Ñ:Ô:ðñ ô ˆHð	ð 	ð 	ñ 	ô 	ð 	ð 	ð 	ð 	ð 	ð 	øøøð 	ð 	ð 	ð 	õ Ô'¨	Ñ2Ô2ð 	RÝCˆH•T‰NÝ$QˆH•[Ñ!Øˆà�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)rA   r=   r<   r?   r>   útype[Collection[T]]rA   ú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 )	a3  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.

    .. versionadded:: 0.12.0
        The ``path_entry_type`` argument to specify the path entry type used in
        :meth:`PyTreeSpec.accessors` and :func:`tree_flatten_with_accessor`.
        If not provided, :class:`AutoEntry` will be used.

    Examples:
        >>> # Register 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 custom type into a namespace with accessor support
        >>> import types
        >>> # This can be whatever your container type is.
        >>> class MyContainer(types.SimpleNamespace):
        ...     pass
        >>> # (Optional) Define a custom path entry type for accessor support.
        >>> # Here we showcase how to define one. In practice, you can use the built-in ``GetAttrEntry``.
        >>> class MyContainerEntry(PyTreeEntry):
        ...     def __call__(self, obj):
        ...         return getattr(obj, self.entry)
        ...     def codify(self, node=''):
        ...         return f'{node}.{self.entry}'
        >>> register_pytree_node(  # doctest: +ELLIPSIS
        ...     MyContainer,
        ...     flatten_func=lambda ct: (
        ...         list(vars(ct).values()),
        ...         list(vars(ct).keys()),
        ...         list(vars(ct).keys()),
        ...     ),
        ...     unflatten_func=lambda keys, values: MyContainer(**dict(zip(keys, values))),
        ...     path_entry_type=MyContainerEntry,
        ...     namespace='mycontainer',
        ... )
        <class '...MyContainer'>

        >>> tree = {'config': MyContainer(lr=0.01, momentum=0.9), 'steps': 1000}

        >>> # Flatten without specifying the namespace
        >>> tree_flatten(tree)  # `MyContainer`s are leaf nodes
        ([MyContainer(lr=0.01, momentum=0.9), 1000], PyTreeSpec({'config': *, 'steps': *}))

        >>> # Flatten with the namespace
        >>> leaves, treespec = tree_flatten(tree, namespace='mycontainer')
        >>> leaves, treespec
        ([0.01, 0.9, 1000], PyTreeSpec({'config': CustomTreeNode(MyContainer[['lr', 'momentum']], [*, *]), 'steps': *}, namespace='mycontainer'))

        >>> # Custom ``entries`` are defined as attribute names
        >>> tree_paths(tree, namespace='mycontainer')
        [('config', 'lr'), ('config', 'momentum'), ('steps',)]

        >>> # Custom path entry type defines the pytree access behavior
        >>> accessors = tree_accessors(tree, namespace='mycontainer')
        >>> accessors[0].codify()
        "*['config'].lr"
        >>> accessors[0](tree)
        0.01

        >>> # Unflatten back to a copy of the original object
        >>> tree_unflatten(treespec, leaves)
        {'config': MyContainer(lr=0.01, momentum=0.9), 'steps': 1000}
    úExpected a class, got r…   ú(Expected a subclass of PyTreeEntry, got r†   rC   ú(The namespace cannot be an empty string.©rA   rE   N)rŒ   r�   rŽ   Ú
issubclassr   rY   r�   rD   Ú
ValueErrorrZ   r“   Úregister_noder:   r‘   )rz   r=   r?   rA   rE   Úregistration_keys         rP   r-   r-     s–  € õj Œ?˜3ÑÔð ;ÝÐ9°Ð9Ð9Ð9Ñ:Ô:Ð:ÝŒO˜OÑ,Ô,ð Yµ¸OÍ[Ñ1YÔ1Yð YÝÐWÀ?ÐWÐWÐWÑXÔXÐXØÕ*Ð*Ð*µ:¸iÍÑ3MÔ3MÐ*ÝÐM¸yÐ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] | Noneú2Callable[[CustomTreeNodeType], CustomTreeNodeType]c              ó   — d S rg   rN   ©rz   rA   rE   s      rP   r.   r.      s	   € ð :=¸rO   c              ó   — d S rg   rN   r¨   s      rP   r.   r.   ª  s	   € ð ˜rO   úCustomTreeNodeType | str | NoneúGCustomTreeNodeType | 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          ˆ fd„dD ¦   «         ¦  «        s¢t          ˆ fd„dD ¦   «         ¦  «        st	          ‰ ›d�¦  «        ‚t          j        ‰ j        ¦  «        d"d„¦   «         }t          t          j        t          ‰ j        d‰ j        ¦  «        ¦  «        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.
        TypeError: If the class does not define the required method pairs.
        ValueError: If the namespace is an empty string.
        ValueError: If the type is already registered in the registry.

    .. versionadded:: 0.12.0
        The ``TREE_PATH_ENTRY_TYPE`` class variable to specify the path entry type used in
        :meth:`PyTreeSpec.accessors` and :func:`tree_flatten_with_accessor`.
        If not provided, :class:`AutoEntry` will be used.

    .. versionadded:: 0.18.0
        Previously, this function looked for methods named ``tree_flatten`` and ``tree_unflatten``
        for the given class. Since version 0.18.0, it prefers methods named ``__tree_flatten__``
        and ``__tree_unflatten__`` instead. The old method names are still supported for
        backward compatibility, but it is recommended to use the new method names.
        The method resolution follows this priority:
        1. If both ``__tree_flatten__`` and ``__tree_unflatten__`` are defined, use them directly.
        2. If both ``tree_flatten`` and ``tree_unflatten`` are defined, wrap them as dunder methods.
        3. If neither complete pair is available, raise a :exc:`TypeError` suggesting the new method names.

    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)

        # Legacy style (still supported but not recommended)
        @register_pytree_node_class(namespace='legacy')
        class LegacyStyleMyList(UserList):
            def tree_flatten(self):
                # Implementation automatically wrapped as __tree_flatten__
                return self.data, None, None

            @classmethod
            def tree_unflatten(cls, metadata, children):
                # Implementation automatically wrapped as __tree_unflatten__
                return cls(*children)
    Nz?Cannot specify `namespace` when the first argument is a string.rC   rž   z<Must specify `namespace` when the first argument is a class.r†   rz   r+   rT   c               ó(   •— t          | ‰‰¬¦  «        S )NrŸ   )r.   )rz   rE   rA   s    €€rP   rx   z-register_pytree_node_class.<locals>.decorator'  s#   ø€ Ý-ØØ /Ø#ðñ ô ð rO   rœ   r…   ÚTREE_PATH_ENTRY_TYPEr�   c              3  óT   •K  — | ]"}t          t          ‰|d ¦  «        ¦  «        V — Œ#d S rg   ©ÚcallableÚgetattr©rˆ   Úmethodrz   s     €rP   ú	<genexpr>z-register_pytree_node_class.<locals>.<genexpr>8  sK   øè è € ð ð àõ 	•˜˜f dÑ+Ô+Ñ,Ô,ðð ð ð ð ð rO   )Ú__tree_flatten__Ú__tree_unflatten__c              3  óT   •K  — | ]"}t          t          ‰|d ¦  «        ¦  «        V — Œ#d S rg   r°   r³   s     €rP   rµ   z-register_pytree_node_class.<locals>.<genexpr>=  sH   øè è € ð 
ð 
Ø5;�H•W˜S &¨$Ñ/Ô/Ñ0Ô0ð
ð 
ð 
ð 
ð 
ð 
rO   )Útree_flattenÚtree_unflattenzh must define both `__tree_flatten__` and `__tree_unflatten__` methods for registration as a pytree node.rW   úCustomTreeNode[T]úQtuple[Children[T], MetaData] | tuple[Children[T], MetaData, Iterable[Any] | None]c               ó*   — |                       ¦   «         S rg   )r¹   rV   s    rP   r¶   z4register_pytree_node_class.<locals>.__tree_flatten__H  s   € ð
 ×$Ò$Ñ&Ô&Ð&rO   Ú__func__útype[CustomTreeNode[T]]Úmetadatar   ÚchildrenúChildren[T]c               ó.   — |                       ||¦  «        S rg   )rº   )rz   rÀ   rÁ   s      rP   r·   z6register_pytree_node_class.<locals>.__tree_unflatten__O  s   € ð ×%Ò% h°Ñ9Ô9Ð9rO   r¶   rŸ   )rz   r+   rT   r+   )rW   r»   rT   r¼   )rz   r¿   rÀ   r   rÁ   rÂ   rT   r»   )rY   r�   rD   r¡   rŽ   rŒ   r�   r²   r   r    r   ÚallÚ	functoolsÚwrapsr¹   Úclassmethodrº   r¶   r·   r-   r	   )rz   rA   rE   rx   r¶   r·   s   ```   rP   r.   r.   µ  sÈ  øøø€ ðD Õ Ð Ð ¥J¨sµCÑ$8Ô$8Ð ØÐ ÝÐ^Ñ_Ô_Ð_Ø�"Š9ˆ9ÝÐGÑHÔHÐHØ˜sˆˆˆYàÐÝÐWÑXÔXÐXØÕ*Ð*Ð*µ:¸iÍÑ3MÔ3MÐ*ÝÐL¸yÐLÐLÑMÔMÐMØ�B‚€ÝÐCÑDÔDÐDà
€{ð	ð 	ð 	ð 	ð 	ð 	ð 	ð ÐåŒ?˜3ÑÔð ;ÝÐ9°Ð9Ð9Ð9Ñ:Ô:Ð:ØÐÝ! #Ð'=½yÑIÔIˆÝŒO˜OÑ,Ô,ð Yµ¸OÍ[Ñ1YÔ1Yð YÝÐWÀ?ÐWÐWÐWÑXÔXÐXõ ð ð ð ð à@ðñ ô ñ ô ð $4õ
 ð 
ð 
ð 
ð 
Ø?að
ñ 
ô 
ñ 
ô 
ð 	õ Øð 5ð 5ð 5ñô ð õ 
Œ˜Ô)Ñ	*Ô	*ð	'ð 	'ð 	'ñ 
+Ô	*ð	'õ 
Ý	Œ� Ô!3°ZÀÔASÑTÔTÑ	UÔ	Uð	:ð 	:ð 	:ñ 
VÔ	Uñ 
Œð	:ð  0ˆÔØ!3ˆÔåØÝÐ'Ñ(Ô(ØÔØ'Øðñ ô ð ð €JrO   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†   rC   rž   N)rŒ   r�   rŽ   rY   r�   rD   r¡   rZ   r“   Úunregister_noder‘   Úpop)rz   rE   r£   s      rP   r/   r/   h  s3  € õD Œ?˜3ÑÔð ;ÝÐ9°Ð9Ð9Ð9Ñ:Ô:Ð:ØÕ*Ð*Ð*µ:¸iÍÑ3MÔ3MÐ*ÝÐM¸yÐ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 keep 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…   rC   rž   F)Úinherit_global_namespaceN)
rY   r�   rD   rŽ   r¡   rZ   r“   r”   Úset_dict_insertion_orderedrÌ   )rË   rE   Úprevs      rP   r0   r0   �  sñ  è è € ð: Õ*Ð*Ð*µ:¸iÍÑ3MÔ3MÐ*ÝÐM¸yÐMÐMÐMÑNÔNÐNØ�B‚€ÝÐCÑDÔDÐDØÕ&Ð&Ð&Øˆ	å	ð =ð =ÝÔ+¨IÐPUÐVÑVÔVˆÝ
Ô%¥d¨4¡j¤j°)Ñ<Ô<Ð<ð=ð =ð =ñ =ô =ð =ð =ð =ð =ð =ð =øøøð =ð =ð =ð =ð;Øˆˆˆåð 	;ð 	;ÝÔ)¨$°	Ñ:Ô:Ð:ð	;ð 	;ð 	;ñ 	;ô 	;ð 	;ð 	;ð 	;ð 	;ð 	;ð 	;ð 	;øøøð 	;ð 	;ð 	;ð 	;ð 	;ð 	;ø�_ð 	;ð 	;ÝÔ)¨$°	Ñ:Ô:Ð:ð	;ð 	;ð 	;ñ 	;ô 	;ð 	;ð 	;ð 	;ð 	;ð 	;ð 	;øøøð 	;ð 	;ð 	;ð 	;ð 	;øøø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    rP   Ú_sorted_itemsr×   Ì  s   € Ý˜e­°A©¬Ð7Ñ7Ô7Ð7rO   r@   útuple[tuple[()], None]c               ó   — dS )N)rN   NrN   )r@   s    rP   Ú_none_flattenrÚ   Ð  s   € Øˆ8rO   rÁ   úIterable[Any]c               ó~   — t          ¦   «         }t          t          |¦  «        |¦  «        |urt          d¦  «        ‚d S )NzExpected no children.)ÚobjectÚnextÚiterr¡   )r@   rÁ   Úsentinels      rP   Ú_none_unflattenrá   Ô  s=   € Ý‰xŒx€HÝ�D�‰NŒN˜HÑ%Ô%¨XÐ5Ð5ÝÐ0Ñ1Ô1Ð1ð 6Ð5rO   Útupútuple[T, ...]útuple[tuple[T, ...], None]c               ó
   — | d fS rg   rN   ©râ   s    rP   Ú_tuple_flattenrç   Ú  ó   € Ø�ˆ9ÐrO   úIterable[T]c               ó    — t          |¦  «        S rg   )Útuple©r@   rÁ   s     rP   Ú_tuple_unflattenrí   Þ  s   € Ý�‰?Œ?ÐrO   Úlstúlist[T]útuple[list[T], None]c               ó
   — | d fS rg   rN   )rî   s    rP   Ú_list_flattenrò   â  rè   rO   c               ó    — t          |¦  «        S rg   )Úlistrì   s     rP   Ú_list_unflattenrõ   æ  s   € Ý�‰>Œ>ÐrO   Údctúdict[KT, VT]ú/tuple[tuple[VT, ...], list[KT], tuple[KT, ...]]c               óˆ   — t          t          |                      ¦   «         ¦  «        ¦  «        \  }}|t          |¦  «        |fS rg   )r"   r×   rÒ   rô   ©rö   Úkeysr’   s      rP   Ú_dict_flattenrü   ê  s6   € Ý�-¨¯	ª	©¬Ñ4Ô4Ñ5Ô5�L€Dˆ&Ø•4˜‘:”:˜tÐ#Ð#rO   rû   úlist[KT]r’   úIterable[VT]c               ó<   — t          t          | |¦  «        ¦  «        S rg   ©r–   r    ©rû   r’   s     rP   Ú_dict_unflattenr  ï  ó   € Ý•˜˜vÑ&Ô&Ñ'Ô'Ð'rO   c               ón   — t          |                      ¦   «         ¦  «        \  }}|t          |¦  «        |fS rg   ©r"   rÒ   rô   rú   s      rP   Ú_dict_insertion_ordered_flattenr  ó  ó0   € õ ˜#Ÿ)š)™+œ+Ñ&Ô&�L€Dˆ&Ø•4˜‘:”:˜tÐ#Ð#rO   c               ó<   — t          t          | |¦  «        ¦  «        S rg   r   r  s     rP   Ú!_dict_insertion_ordered_unflattenr	  ÿ  r  rO   úOrderedDict[KT, VT]c               ón   — t          |                      ¦   «         ¦  «        \  }}|t          |¦  «        |fS rg   r  rú   s      rP   Ú_ordereddict_flattenr    r  rO   c               ó<   — t          t          | |¦  «        ¦  «        S rg   )r   r    r  s     rP   Ú_ordereddict_unflattenr    s   € Ý•x  fÑ-Ô-Ñ.Ô.Ð.rO   údefaultdict[KT, VT]úOtuple[tuple[VT, ...], tuple[Callable[[], VT] | None, list[KT]], tuple[KT, ...]]c               ó@   — t          | ¦  «        \  }}}|| j        |f|fS rg   )rü   Údefault_factory©rö   r’   Údict_metadataÚentriess       rP   Ú_defaultdict_flattenr    s-   € õ &3°3Ñ%7Ô%7Ñ"€FˆM˜7Ø�CÔ'¨Ð7¸Ð@Ð@rO   rÀ   ú!tuple[Callable[[], VT], list[KT]]c               óH   — | \  }}t          |t          ||¦  «        ¦  «        S rg   )r   r  ©rÀ   r’   r  r  s       rP   Ú_defaultdict_unflattenr    s(   € ð
 &.Ñ"€O�]Ý�­¸ÀvÑ(NÔ(NÑOÔOÐOrO   c               ó@   — t          | ¦  «        \  }}}|| j        |f|fS rg   )r  r  r  s       rP   Ú&_defaultdict_insertion_ordered_flattenr  (  s.   € õ &EÀSÑ%IÔ%IÑ"€FˆM˜7Ø�CÔ'¨Ð7¸Ð@Ð@rO   c               óH   — | \  }}t          |t          ||¦  «        ¦  «        S rg   )r   r	  r  s       rP   Ú(_defaultdict_insertion_ordered_unflattenr  4  s*   € ð
 &.Ñ"€O�]Ý�Õ(IÈ-ÐY_Ñ(`Ô(`ÑaÔaÐarO   Údeqúdeque[T]útuple[deque[T], int | None]c               ó   — | | j         fS rg   ©Úmaxlen)r  s    rP   Ú_deque_flattenr%  =  s   € Ø�”
ˆ?ÐrO   r$  ú
int | Nonec               ó$   — t          || ¬¦  «        S )Nr#  )r   )r$  rÁ   s     rP   Ú_deque_unflattenr(  A  s   € Ý� &Ð)Ñ)Ô)Ð)rO   úNamedTuple[T]ú)tuple[tuple[T, ...], type[NamedTuple[T]]]c               ó$   — | t          | ¦  «        fS rg   ©r;   ræ   s    rP   Ú_namedtuple_flattenr-  E  ó   € Ø•�S‘	”	ˆ>ÐrO   útype[NamedTuple[T]]c               ó   —  | |Ž S rg   rN   ©rz   rÁ   s     rP   Ú_namedtuple_unflattenr2  J  s   € Øˆ3�ˆ>ÐrO   ÚseqúStructSequence[T]ú-tuple[tuple[T, ...], type[StructSequence[T]]]c               ó$   — | t          | ¦  «        fS rg   r,  )r3  s    rP   Ú_structseq_flattenr7  N  r.  rO   útype[StructSequence[T]]c               ó   —  | |¦  «        S rg   rN   r1  s     rP   Ú_structseq_unflattenr:  R  s   € ð
 ˆ3ˆx‰=Œ=ÐrO   )rA   rB   z6dict[type | tuple[str, type], PyTreeNodeRegistryEntry]r‘   rN   )rp   rq   rT   rr   )rz   r;   rE   rD   rT   r{   rg   )rz   r   rE   rD   rT   r€   )rz   r‚   rE   rD   rT   rƒ   )r=   r<   r?   r>   rz   r™   rA   rš   rE   rD   rT   r™   )rz   r¤   rA   r¥   rE   r¤   rT   r¦   )rz   r+   rA   r¥   rE   rD   rT   r+   )rz   rª   rA   r¥   rE   r¤   rT   r«   )rz   r;   rE   rD   rT   r:   )rË   rÌ   rE   rD   rT   rÍ   )rÒ   rÓ   rT   rÔ   )r@   r   rT   rØ   )r@   r   rÁ   rÛ   rT   r   )râ   rã   rT   rä   )r@   r   rÁ   ré   rT   rã   )rî   rï   rT   rð   )r@   r   rÁ   ré   rT   rï   )rö   r÷   rT   rø   )rû   rý   r’   rþ   rT   r÷   )rö   r
  rT   rø   )rû   rý   r’   rþ   rT   r
  )rö   r  rT   r  )rÀ   r  r’   rþ   rT   r  )r  r   rT   r!  )r$  r&  rÁ   ré   rT   r   )râ   r)  rT   r*  )rz   r/  rÁ   ré   rT   r)  )r3  r4  rT   r5  )rz   r8  rÁ   ré   rT   r4  )yrI   Ú
__future__r   Ú
contextlibÚdataclassesrÅ   rŒ   rK   Ú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   r   r   Úoptree.utilsr    r!   r"   ÚbuiltinsÚcollections.abcr#   r$   r%   r&   r'   r(   r)   r*   r;   r+   Ú__all__rL   ÚSLOTSÚ	dataclassr:   rR   rY   rJ   rZ   Útyping_extensionsr[   r\   r]   r^   r_   ra   ry   r~   r-   r.   r/   Úcontextmanagerr0   r×   rÚ   rá   rç   rí   rò   rõ   rü   r  r  r	  r  r  r  r  r  r  r%  r(  r-  r2  r7  r:  ÚNONErë   ÚTUPLErô   ÚLISTr–   ÚDICTÚ
NAMEDTUPLEÚORDEREDDICTÚDEFAULTDICTÚDEQUEÚSTRUCTSEQUENCEr‘   r•   r—   rN   rO   rP   ú<module>rV     sk	  ðð -Ð ,Ð ,ð #Ð "Ð "Ð "Ð "Ð "à Ð Ð Ð Ø Ð Ð Ð Ø Ð Ð Ð Ø €€€Ø 
€
€
€
Ø 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à Ð Ð Ð Ð Ð ðð ð ð ð ð ð ð ð ð ð ð ð ð ð ð ðð ð ð ð ð ð ð ð ð ð ð ð ð ð ð ð ð ð >Ð =Ð =Ð =Ð =Ð =Ð =Ð =Ð =Ð =ð ð SØ€O€O€OØ?Ð?Ð?Ð?Ð?Ð?Ð?Ð?Ð?Ð?àPÐPÐPÐPÐPÐPÐPÐPÐPÐPÐPÐPÐPÐPð !˜Ð!5¸TÀ.Ô=QÐRÑRÔRÐðð ð €ð Ô+¨wÒ6Ð6ˆ�$ˆˆ¸B€ð €ÔÐK˜D t°¸TÐKÐKÀUÐKÐKðð ð ð ð ˜g aœjñ ô ñ LÔKðð 
ð$ð $ð $ð $ð $ñ $ô $ð $ð *˜/Ñ+Ô+Ð Ð +Ð +Ð +Ñ +Ø˜™œ€Ð Ð Ð Ñ Øð ð &Ø+Ð+Ð+Ð+Ð+Ð+à	ˆ�4‰Œ€BØ	ˆ�‰Œ€BØˆI�gÑÔ€EØˆG�GÑÔ€Eð&ð &ð &ð &ð &˜7 2 r¨5°%Ð#7Ô8ñ &ô &ð &ðð ð ð ð 
ð
 ð	)ð )ð )ð )ð )ñ 
„ð)ð 
àð.ð ð	.ð .ð .ð .ð .ñ 
„ð.ð ðhð ð	hð hð hð hð hð hðV 
€Ð
"Ñ#Ô#ð *3ðSð Sð Sð Sð Sñ $Ô#ðSðl ˜hð 
àð=ð 15Ø ð=ð =ð =ð =ð =ñ 
„ð=ð 
ðð ð ñ 
„ðð ,0ðpð 15Ø ðpð pð pð pð pð pðf28ð 28ð 28ð 28ðj Ôð+;ð +;ð +;ñ Ôð+;ð\8ð 8ð 8ð 8ðð ð ð ð2ð 2ð 2ð 2ðð ð ð ðð ð ð ðð ð ð ðð ð ð ð$ð $ð $ð $ð
(ð (ð (ð (ð	$ð 	$ð 	$ð 	$ð(ð (ð (ð (ð	$ð 	$ð 	$ð 	$ð/ð /ð /ð /ð	Að 	Að 	Að 	AðPð Pð Pð Pð	Að 	Að 	Að 	Aðbð bð bð bðð ð ð ð*ð *ð *ð *ðð ð ð ð
ð ð ð ðð ð ð ðð ð ð ð 	€Dˆ�J„JÐ'Ð'ØˆˆT‰
Œ
ØØØ#ØŒ_ðñ ô ð 
Ð"Ð"ØØØØ%ØÔðñ ô ð 	Ð
!Ð
!ØØØØ%ØŒ_ðñ ô ð 	Ð
!Ð
!ØØØØ$ØŒ_ðñ ô ð Ð'Ð'ØØØØ'ØÔ"ðñ ô ð Ð(Ð(ØØØØ$ØÔ#ðñ ô ð Ð(Ð(ØØØØ$ØÔ#ðñ ô ð 
Ð"Ð"ØØØØ%ØÔðñ ô ð Ð+Ð+ØØØØ+ØÔ&ðñ ô ðs@NÐ ð @ð @ð @ñ @ðF *AÐ)@ØØ#Ø%Ø Ø	Œð*ñ *ô *Ð &ð 1HÐ0GØØ*Ø,Ø Ø	Ô	ð1ñ 1ô 1Ð -Ð -Ð -rO   