
    $Sh^L                       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Zddl	m
Z ddl	mZ ddl	mZ ddlmZ ddlmZ dd	lmZ dd
lmZmZ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&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z, ddl-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3 ddl4m5Z5 ddl6m7Z7 ddl6m8Z8m9Z9 ddl:m;Z;m<Z<m=Z=m>Z>m?Z?m@Z@mAZAmBZBmCZCmDZDmEZE g dZFe9ZGdeHd<    e(d          ZI e(d          ZJ e(d          ZK e(d          ZL e(d          ZM e0d          ZN e(de!de f                   ZOeeI         ZPdeHd<   e&e         ZQdeHd<   e, G d de'eI                               ZR eSe)eTeUf                   ZV	 dd lmWZW n# eX$ r dMd$ZWY nw xY w G d% d&e%eI                   ZY G d' d(          ZZ G d) d*e'eI                   Z[ G d+ d,e'eI                   Z\dNd/Z] e]e7j^                  dOd3            Z^ e]e7j_                  dPd5            Z_ e]e7j`                  dQd8            Z` e]e7ja                  dRd;            Za e(d<d=>          Zb G d? d@eS          Zce* G dA dBeebdf         ecC                      ZdedZedeHdD<   [c e]e7jf                  dOdE            Zf e]e7jg                  dPdF            Zge7jh        ZhdGeHdH<    e]e7ji                  dQdI            Zi eS eSejj                  jk                  ZldJeHdK<    e]e7jm                  dRdL            Zm[WdS )SzTyping utilities for OpTree.    )annotationsN)dict)list)tuple)OrderedDict)defaultdict)deque)
CollectionHashable	ItemsViewIterableIteratorKeysViewSequence
ValuesView)AnyCallableClassVarFinal
ForwardRefGenericOptionalProtocolTypeVarUnionfinal
get_originruntime_checkable)
NamedTupleNever	ParamSpecSelf	TypeAliasTypeAliasType)WeakKeyDictionary)
PyTreeKind
PyTreeSpec)	AutoEntryDataclassEntryFlattenedEntryGetAttrEntryGetItemEntryMappingEntryNamedTupleEntryPyTreeAccessorPyTreeEntrySequenceEntryStructSequenceEntry).r'   	PyTreeDefr&   PyTreePyTreeTypeVarCustomTreeNodeChildrenMetaDataFlattenFuncUnflattenFuncr0   r,   r+   r*   r(   r1   r-   r.   r2   r)   r/   is_namedtupleis_namedtuple_classis_namedtuple_instancenamedtuple_fieldsis_structseqis_structseq_classis_structseq_instancestructseq_fieldsTSUKTVTPFr   r   TupleListDictr   r   DefaultDictDequeStructSequencer#   r3   rC   rD   rE   rF   rG   rH   rI   .)boundr7   r8   c                  2    e Zd ZdZddZedd
            ZdS )r6   z0The abstract base class for custom pytree nodes.returnQtuple[Children[T], MetaData] | tuple[Children[T], MetaData, Iterable[Any] | None]c                   dS )z:Flatten the custom pytree node into children and metadata.N selfs    S/var/www/html/movieo_spanner_bot/venv/lib/python3.11/site-packages/optree/typing.pytree_flattenzCustomTreeNode.tree_flatten             metadatar8   childrenChildren[T]r"   c                   dS )z@Unflatten the children and metadata into the custom pytree node.NrU   )clsr\   r]   s      rX   tree_unflattenzCustomTreeNode.tree_unflatten   rZ   r[   N)rR   rS   )r\   r8   r]   r^   rR   r"   )__name__
__module____qualname____doc__rY   classmethodra   rU   r[   rX   r6   r6      sX        ::
I 
I 
I 
I O O O [O O Or[   r6   )	_tp_cachefuncCallable[P, T]rR   c               t     t          j                   t          j                   d fd            }|S )	NargsP.argskwargsP.kwargsrR   rC   c                 F    	  | i |S # t           $ r  | i |cY S w xY wN	TypeError)rk   rm   cachedrh   s     rX   innerz_tp_cache.<locals>.inner   sS    -vt.v... - - -tT,V,,,,,-s      rk   rl   rm   rn   rR   rC   )	functools	lru_cachewraps)rh   rt   rs   s   ` @rX   rg   rg      sS    $T**				- 	- 	- 	- 	- 	- 
		- r[   c                      e Zd ZU dZdZded<    e            Zded<    ej	                    Z
ded<   ed-d            Zd.dZd/dZd0dZd1dZd2dZd3dZd4d Zd5d!Zd5d"Zd6d7d&Zd8d(Zd9d*Zd:d,Zd#S );r4   a  Generic PyTree type.

    >>> import torch
    >>> TensorTree = PyTree[torch.Tensor]
    >>> TensorTree  # doctest: +IGNORE_WHITESPACE
    typing.Union[torch.Tensor,
                 tuple[ForwardRef('PyTree[torch.Tensor]'), ...],
                 list[ForwardRef('PyTree[torch.Tensor]')],
                 dict[typing.Any, ForwardRef('PyTree[torch.Tensor]')],
                 collections.deque[ForwardRef('PyTree[torch.Tensor]')],
                 optree.typing.CustomTreeNode[ForwardRef('PyTree[torch.Tensor]')]]
    rU   ClassVar[tuple[()]]	__slots__zSClassVar[WeakKeyDictionary[TypeAliasType, tuple[type | TypeAliasType, str | None]]]__instances__zClassVar[threading.Lock]__instance_lock__itemetype[T] | TypeAliasType | tuple[type[T] | TypeAliasType] | tuple[type[T] | TypeAliasType, str | None]rR   r$   c                   t          |t                    s|df}t          |          dk    r|d         df}n-t          |          dk    rt          | j         d|d          |\  }}|/t          |t
                    st          | j         d|d          t          |t                    r^t          |          t          u rH| j	        5  	 || j
        v r|cddd           S n# t          $ r Y nw xY wddd           n# 1 swxY w Y   |t          |          }nt          |t                    r t          | j         d|j         d          }nt          |t                    rb|j        d	k    r|j        }n4	 |j         d|j         }n!# t           $ r |j         d|j         }Y nw xY wt          | j         d| d          }nt          | j         d|d          }t          |t"          |d
f         t$          |         t&          t(          |f         t*          |         t,          |         f         }| j	        5  ||f| j
        |<   ddd           n# 1 swxY w Y   |S )z.Instantiate a PyTree type with the given type.N   r      zS[...] only supports a tuple of 2 items, a parameter and a string of type name, got .[]builtins.)
isinstancer   lenrr   rb   str
_UnionTyper   r   r}   r|   r   r   typerc   rd   AttributeErrorrJ   rK   rL   r   rN   r6   )r`   r~   paramnamerecurse_reftypenamepytree_aliass          rX   __class_getitem__zPyTree.__class_getitem__   s    $&& 	 $<Dt99>>GT?DDYY!^^< H H>BH H H   tJtS$9$9< H H>BH H H  
 eZ(( 	Z->->%-G-G&   111$       1    D	               $T**KKw'' 	C$%H%Hu~%H%H%HIIKKt$$ 
	C:-- -F"'"2IIU5GIIHH% F F F"'"2EEU^EEHHHF$%B%Bx%B%B%BCCKK$%A%Au%A%A%ABBK+s"#k!"+;')
 " 	< 	</4dmCl+	< 	< 	< 	< 	< 	< 	< 	< 	< 	< 	< 	< 	< 	< 	<sZ   D
C'&D'
C41D3C44DD
D>F F.-F. II Ir    c                    t          d          )zProhibit instantiation.z*Cannot instantiate special typing classes.rq   r`   s    rX   __new__zPyTree.__new__  s    DEEEr[   rk   r   rm   c                    t          d          Prohibit subclassing.z'Cannot subclass special typing classes.rq   r`   rk   rm   s      rX   __init_subclass__zPyTree.__init_subclass__      ABBBr[   keyPyTree[T] | Tc                   t           z!Emulate collection-like behavior.NotImplementedErrorrW   r   s     rX   __getitem__zPyTree.__getitem__      !!r[   r   r   c                   t           )z Emulate dataclass-like behavior.r   )rW   r   s     rX   __getattr__zPyTree.__getattr__!  r   r[   Any | Tboolc                   t           r   r   r   s     rX   __contains__zPyTree.__contains__%  r   r[   intc                   t           r   r   rV   s    rX   __len__zPyTree.__len__)  r   r[   Iterator[PyTree[T] | T | Any]c                   t           r   r   rV   s    rX   __iter__zPyTree.__iter__-  r   r[   c                   t           zEmulate sequence-like behavior.r   r   s     rX   indexzPyTree.index1  r   r[   c                   t           r   r   r   s     rX   countzPyTree.count5  r   r[   NdefaultT | Nonec                   t           zEmulate mapping-like behavior.r   )rW   r   r   s      rX   getz
PyTree.get9  r   r[   KeysView[Any]c                   t           r   r   rV   s    rX   keyszPyTree.keys=  r   r[   ValuesView[PyTree[T] | T]c                   t           r   r   rV   s    rX   valueszPyTree.valuesA  r   r[   ItemsView[Any, PyTree[T] | T]c                   t           r   r   rV   s    rX   itemszPyTree.itemsE  r   r[   )r~   r   rR   r$   rR   r    rk   r   rm   r   rR   r    )r   r   rR   r   )r   r   rR   r   )r   r   rR   r   )rR   r   )rR   r   )r   r   rR   r   rp   )r   r   r   r   rR   r   )rR   r   )rR   r   )rR   r   )rb   rc   rd   re   r{   __annotations__r%   r|   	threadingLockr}   rg   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rU   r[   rX   r4   r4      s          &(I'''' 	      3A).2B2BBBBB= = = Y=~F F F FC C C C" " " "" " " "" " " "" " " "" " " "" " " "" " " "" " " " "" " " "" " " "" " " " " "r[   r4   c                  2    e Zd ZdZedd            ZddZdS )r5   a  Type variable for PyTree.

    >>> import torch
    >>> TensorTree = PyTreeTypeVar('TensorTree', torch.Tensor)
    >>> TensorTree  # doctest: +IGNORE_WHITESPACE
    typing.Union[torch.Tensor,
                 tuple[ForwardRef('TensorTree'), ...],
                 list[ForwardRef('TensorTree')],
                 dict[typing.Any, ForwardRef('TensorTree')],
                 collections.deque[ForwardRef('TensorTree')],
                 optree.typing.CustomTreeNode[ForwardRef('TensorTree')]]
    r   r   r   type | TypeAliasTyperR   r$   c               ~    t          |t                    st          | j         d|d          t          ||f         S )zEInstantiate a PyTree type variable with the given name and parameter.z* only supports a string of type name, got r   )r   r   rr   rb   r4   )r`   r   r   s      rX   r   zPyTreeTypeVar.__new__Y  sH     $$$ 	bs|``W[```aaaeTk""r[   rk   r   rm   r    c                    t          d          r   rq   r   s      rX   r   zPyTreeTypeVar.__init_subclass__`  r   r[   N)r   r   r   r   rR   r$   r   )rb   rc   rd   re   rg   r   r   rU   r[   rX   r5   r5   K  sX          # # # Y#C C C C C Cr[   r5   c                  4    e Zd ZdZej        dd            ZdS )	r9   z*The type stub class for flatten functions.	containerCollection[T]rR   rS   c                   dS )z1Flatten the container into children and metadata.NrU   )rW   r   s     rX   __call__zFlattenFunc.__call__h  rZ   r[   N)r   r   rR   rS   rb   rc   rd   re   abcabstractmethodr   rU   r[   rX   r9   r9   e  sB        44@ @ @ @ @ @r[   r9   c                  4    e Zd ZdZej        d
d            Zd	S )r:   z,The type stub class for unflatten functions.r\   r8   r]   r^   rR   r   c                   dS )z<Unflatten the children and metadata back into the container.NrU   )rW   r\   r]   s      rX   r   zUnflattenFunc.__call__t  rZ   r[   N)r\   r8   r]   r^   rR   r   r   rU   r[   rX   r:   r:   q  sB        66K K K K K Kr[   r:   cxx_implementation*Callable[[Callable[P, T]], Callable[P, T]]c                    d fd}|S )a^  Decorator to override the Python implementation with the C++ implementation.

    >>> @_override_with_(any)
    ... def my_any(iterable):
    ...     for elem in iterable:
    ...         if elem:
    ...             return True
    ...     return False
    ...
    >>> my_any([False, False, True, False, False, True])  # run at C speed
    True
    python_implementationri   rR   c               d    t          j        |           dfd            }|_        | |_        |S )	Nrk   rl   rm   rn   rR   rC   c                      | i |S rp   rU   )rk   rm   r   s     rX   wrappedz1_override_with_.<locals>.wrapper.<locals>.wrapped  s    %%t6v666r[   ru   )rv   rx   __cxx_implementation____python_implementation__)r   r   r   s     rX   wrapperz _override_with_.<locals>.wrapper  sN    	.	/	/	7 	7 	7 	7 	7 
0	/	7 *<&,A)r[   )r   ri   rR   ri   rU   )r   r   s   ` rX   _override_with_r   y  s(    "      Nr[   objobject | typer   c               l    t          | t                    r| nt          |           }t          |          S )zSReturn whether the object is an instance of namedtuple or a subclass of namedtuple.)r   r   r<   r   r`   s     rX   r;   r;     s0     C&&
5##DIICs###r[   objectc               :    t          t          |                     S )z7Return whether the object is an instance of namedtuple.)r<   r   r   s    rX   r=   r=     s     tCyy)))r[   r`   r   c               R   t          | t                    ot          | t                    o}t          t	          | dd          t                    oYt          d | j        D                       o;t          t	          | dd                    ot          t	          | dd                    S )z5Return whether the class is a subclass of namedtuple._fieldsNc              3  B   K   | ]}t          |          t          u V  d S rp   )r   r   ).0fields     rX   	<genexpr>z&is_namedtuple_class.<locals>.<genexpr>  s-      <<uUs"<<<<<<r[   _make_asdict)r   r   
issubclassr   getattrallr   callabler   s    rX   r<   r<     s     	3 	4sE""	4wsIt44e<<	4 <<<<<<<		4
 WS'40011	4 WS)T2233r[   tuple | type[tuple]tuple[str, ...]c                   t          | t                    r%| }t          |          st          d|d          n1t          |           }t          |          st          d| d          |j        S )z'Return the field names of a namedtuple.z,Expected a collections.namedtuple type, got r   z9Expected an instance of collections.namedtuple type, got )r   r   r<   rr   r   r   s     rX   r>   r>     s     #t b"3'' 	US3SSSTTT	U 3ii"3'' 	b`X[```aaa;r[   _T_coT)	covariantc                  "    e Zd ZdZddZdd	Zd
S )StructSequenceMetaz-The metaclass for PyStructSequence stub type.subclassr   rR   r   c                    t          |          S )ad  Return whether the class is a PyStructSequence type.

        >>> import time
        >>> issubclass(time.struct_time, StructSequence)
        True
        >>> class MyTuple(tuple):
        ...     n_fields = 2
        ...     n_sequence_fields = 2
        ...     n_unnamed_fields = 0
        >>> issubclass(MyTuple, StructSequence)
        False
        )r@   )r`   r   s     rX   __subclasscheck__z$StructSequenceMeta.__subclasscheck__  s     "(+++r[   instancer   c                    t          |          S )zReturn whether the object is a PyStructSequence instance.

        >>> import sys
        >>> isinstance(sys.float_info, StructSequence)
        True
        >>> isinstance((1, 2), StructSequence)
        False
        )rA   )r`   r   s     rX   __instancecheck__z$StructSequenceMeta.__instancecheck__  s     %X...r[   N)r   r   rR   r   )r   r   rR   r   )rb   rc   rd   re   r   r  rU   r[   rX   r   r     sB        77, , , ,	/ 	/ 	/ 	/ 	/ 	/r[   r   c                  R    e Zd ZU dZdZded<   ded<   ded<   ded<   ddZdddZdS )rO   z<A generic type stub for CPython's ``PyStructSequence`` type.rU   rz   r{   zFinal[ClassVar[int]]n_fieldsn_sequence_fieldsn_unnamed_fieldsrR   r    c                    t          d          )r   z4type 'StructSequence' is not an acceptable base typerq   r   s    rX   r   z StructSequence.__init_subclass__  s    NOOOr[   .sequenceIterable[_T_co]r   dict[str, Any]r"   c                   t           )z.Create a new :class:`StructSequence` instance.r   )r`   r  r   s      rX   r   zStructSequence.__new__  r   r[   Nr   ).)r  r  r   r	  rR   r"   )rb   rc   rd   re   r{   r   r   r   rU   r[   rX   rO   rO     s         FF%'I''''""""++++****P P P P
" " " " " " "r[   rO   )	metaclass	structseqc               l    t          | t                    r| nt          |           }t          |          S )z\Return whether the object is an instance of PyStructSequence or a class of PyStructSequence.)r   r   r@   r   s     rX   r?   r?     s0     C&&
5##DIICc"""r[   c               :    t          t          |                     S )z=Return whether the object is an instance of PyStructSequence.)r@   r   r   s    rX   rA   rA     s     d3ii(((r[   r   Py_TPFLAGS_BASETYPEc                  t          | t                    r| j        t          fk    rt          t	          | dd          t
                    rt          t	          | dd          t
                    rt          t	          | dd          t
                    rgt          j                    dk    r3	 t          j	        d| f           n# t          t          f$ r Y dS w xY wd	S t          | j        t          z             S d	S )
z8Return whether the class is a class of PyStructSequence.r  Nr  r  PyPyr   )basesTF)r   r   	__bases__r   r   r   platformr   types	new_classAssertionErrorrr   r   	__flags__r  r   s    rX   r@   r@     s    	3= MeX%%wsJ55s;; & ws$7>>DD & ws$6==sCC	 & )++v55
3&99999"I.   tt5(;;<<<<5s   +C CCz type[types.MemberDescriptorType]StructSequenceFieldTypec                  t          | t                    r%| }t          |          st          d|d          n1t          |           }t          |          st          d| d          t	          j                    dk    rBd t          |                                          D             }t          ||j	                  }n+d t          |                                          D             }t          |d|j                           S )	z-Return the field names of a PyStructSequence.z&Expected a PyStructSequence type, got r   z3Expected an instance of PyStructSequence type, got r  c                N    i | ]"\  }}t          |t                    ||j        #S rU   )r   r  r   r   r   members      rX   
<dictcomp>z$structseq_fields.<locals>.<dictcomp>7  sA     
 
 
f&"9::
&,
 
 
r[   )r   c                B    g | ]\  }}t          |t                    |S rU   )r   r  r  s      rX   
<listcomp>z$structseq_fields.<locals>.<listcomp>>  s=     
 
 
f&"9::

 
 
r[   N)r   r   r@   rr   r  r   varsr   sortedr   r   r  )r   r`   indices_by_namefieldss       rX   rB   rB   *  s-    #t \!#&& 	OMSMMMNNN	O 3ii!#&& 	\ZRUZZZ[[[%''611
 
 $S		 1 1
 
 

 _-@AAA
 
 $S		 1 1
 
 

 /#//0111r[   )rh   ri   rR   ri   )r   ri   rR   r   )r   r   rR   r   )r   r   rR   r   )r`   r   rR   r   )r   r   rR   r   )nre   
__future__r   r   rv   r  sysr   r  r   r   rL   r   rK   r   rJ   collectionsr   r   rM   r	   rN   collections.abcr
   r   r   r   r   r   r   r   typingr   r   r   r   r   r   r   r   r   r   r   r   r   typing_extensionsr   r    r!   r"   r#   r$   weakrefr%   	optree._C_Cr&   r'   optree.accessorsr(   r)   r*   r+   r,   r-   r.   r/   r0   r1   r2   __all__r3   r   rC   rD   rE   rF   rG   rH   rI   r7   r8   r6   r   r   r   r   rg   ImportErrorr4   r5   r9   r:   r   r;   r=   r<   r>   r   r   rO   r  r?   rA   r  r@   version_infomajorr  rB   rU   r[   rX   <module>r3     s   # " " " " " " " " 



      



      ! ! ! ! ! ! ! ! ! ! ! ! # # # # # # # # # # # # 2 2 2 2 2 2 & & & & & &	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	                                             & % % % % %       , , , , , , , ,                         / / /d "	 ! ! ! !GCLLGCLLGCLLWT]]WT]]IcNNGCxS)*** qk ! ! ! !x( ( ( ( ( O O O O OXa[ O O O( T%S/""
                I" I" I" I" I"WQZ I" I" I"ZC C C C C C C C4	@ 	@ 	@ 	@ 	@(1+ 	@ 	@ 	@K K K K KHQK K K K   < !""$ $ $ #"$ *++* * * ,+*
 '((
 
 
 )(
 %&&
 
 
 '&
 	4(((/ / / / / / / /D " " " " "U5#:&2D " " " "& &	 % % % % !!# # # "!# )**) ) ) +*) 1  1 1 1 1 &''   ('. =ADcFVAWAWA]<^<^  ^ ^ ^ ^ $%%2 2 2 &%26 IIs   "E) )	E54E5