
    Pg                        U d 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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ZddlZddlmZmZmZmZmZmZmZmZmZmZmZmZ ddlZddlZddlmc m Z! ddl"m#Z# ddl$m#Z%m&Z' ddl(m)Z)m*Z*m+Z+ ddl,m&Z& e	jZ                  dk\  Z.ee/   e0d	<   e	jZ                  d
k\  Z1ee/   e0d<   eeeedf   f   e0d<   e	jZ                  d
k\  rejd                  Z3ndZ3ee0d<   	 ddl4Z4e4jj                  Z5 ejp                         Z9de0d<   dZ:de/fdZ; G d d      Z< e<       Z= e>dd      D ]  Z?e= e@       de? <    de/fdZAdedeBfdZC G d d      ZD eD       ZEd ZFdfdeGfd ZHd! ZId" ZJde/fd#ZKdeeB   fd$ZLd% ZMd& ZNd' ZOd( ZP G d) d*      ZQd+ ZRd, ZS G d- d.ej                        ZUdgd/ZVd0 ZWd1 ZXd2 ZYde/fd3ZZde/fd4Z[de/fd5Z\de/fd6Z]d7 Z^d8 Z_dhd9Z`i aaeeBee   f   e0d:<   d;Zbd< Zcd= Zdd> Zed? Zfdhd@ZgdeeBeGf   fdAZhi aieeBeeBee   f   f   e0dB<   i ZjeeeBeBf   eGf   e0dC<   dD ZkdE Zlde/fdFZmde/fdGZnde/fdHZodI ZpdJ Zqde/fdKZrde/fdLZsej                  j                  j                         rddMlwmxZx ddNlmyZy de/fdOZzde/fdPZ{nde/fdQZ{dR Z|	 	 didSeej                  j                  j                     fdTZdUeBdVeeB   dWeedf   fdXZej                  dY        ZdhdZZde/fd[Zdhd\Zdhd]Zdhd^Zde/fd_Zde/fd`Z G da dbej                        Zdc ZdeeB   fddZe	jZ                  d
kD  ry eWej                  j                           eWej                  j"                          eWej                  j$                          eWej                  j&                         yy# e6$ r ddl7Z7e7jj                  Z5Y w xY w)jz
The weak_script annotation needs to be here instead of inside torch/jit/ so it
can be used in other places in torch/ (namely torch.nn) without running into
circular dependency problems
    N)AnyCallableDictFinal
ForwardRefget_args
get_originListOptionalTupleTypeUnion)_Await)r   Future)
fake_rangeget_source_lines_and_file	parse_def)r   )   	   IS_PY39_PLUSr   
   IS_PY310_PLUS.BuiltinUnionType LockTypez8weakref.WeakKeyDictionary[Callable, Dict[str, Callable]]boolean_dispatched__torch_jit_dataclassreturnc                     t        | d      xr< | j                  dv xr, t        |       t        u xs t	        | t        t                    S )N
__module__>   typingtyping_extensions)hasattrr!   r	   r   
isinstancetypeanns    Z/var/www/html/suriana-translation/venv/lib/python3.12/site-packages/torch/_jit_internal.pyis_finalr*   R   sF    \" 	GNN==	G_%ECe)E    c                       e Zd Zd Zy)BroadcastingListClsc                      y Nr   )selftypess     r)   __getitem__zBroadcastingListCls.__getitem__\   s    r+   N)__name__r!   __qualname__r2   r   r+   r)   r-   r-   [   s    r+   r-         BroadcastingListc                       y)a  
    Function that returns True when in compilation and False otherwise. This
    is useful especially with the @unused decorator to leave code in your
    model that is not yet TorchScript compatible.
    .. testcode::

        import torch

        @torch.jit.unused
        def unsupported_linear_op(x):
            return x

        def linear(x):
            if torch.jit.is_scripting():
                return torch.linear(x)
            else:
                return unsupported_linear_op(x)
    Fr   r   r+   r)   is_scriptingr9   g   s    & r+   c                 `   t        | d      r| j                  S t        | t        j                  j
                        r| j                  S t        | dd       r| j                  }n2t        | t        j                        r| j                  }nt        d      |dk(  rd}| j                  }|dk(  r| j                  S |t        d| d      t        j                  |      r$|j!                  d	d
      }|j!                  dd
      }|r|dk(  rd}nd|z   }d|v rt        d| d| d      |dz   |z   S )N_jit_override_qualnamer3   z)Could not get name of python class objectz<lambda>_lambdaztorch._classesz(Could not get qualified name for class 'z': __module__ can't be None.<_>__main__	__torch__z
__torch__..z': 'z' is not a valid identifier)r$   r;   r%   torch_CScriptFunctionqualified_namegetattrr3   enumEnumnameRuntimeErrorr!   package_mangling
is_mangledreplace)objmangle_namerJ   module_names       r)   _qualified_namerR   ~   sW    s,-)))#uxx../!!!sJ%||	C	#xxFGGz..K &&!!! 6tf =( (
 	
 "";/!))#s3!))#s3 *$%K '4K
d{6tf =v02
 	

 t##r+   c                       e Zd Zd Zd Zd Zy)SourceLoaderc                     i | _         y r/   contentr0   s    r)   __init__zSourceLoader.__init__   s	    r+   c                 "    || j                   |<   y r/   rV   )r0   fnsources      r)   cachezSourceLoader.cache   s    !Rr+   c                 8    | j                   j                  |      S r/   )rW   get)r0   r[   s     r)   
get_sourcezSourceLoader.get_source   s    ||##r+   N)r3   r!   r4   rY   r]   r`   r   r+   r)   rT   rT      s    "$r+   rT   c                 ^     fddt         t        t        f   ffdfd fdS )a_  
    Creates a resolution callback that will look up qualified names in an
    environment, starting with `lookup_base` for the base of any qualified
    names, then proceeding down the lookup chain with the resolved object.

    You should not use this directly, it should only be used from the other
    createResolutionCallbackFrom* functions.
    c                 z    d| v r+| j                  dd      \  }}t        ||      } ||      S t        ||       S )NrB      )maxsplit)splitrG   )rF   modulebaseremaining_piecesmodule_valuelookupInModules        r)   rj   z7createResolutionCallbackFromEnv.<locals>.lookupInModule   sM    . %3%9%9#%9%J"D""640L!"2LAA6>22r+   r   c                    d}|t        |       k  r"| |   dvr|dz  }|t        |       k  r| |   dvr| d | dk(  rd|fS  | d | j                         |      }|J d| d |         |t        |       k(  s| |   dk7  r||fS | |   dk(  sJ g }| |   dk7  r5d}|dz  } | |d  |      \  }}|j                  |       ||z  }| |   dk7  r5t        |      dkD  r|t        |         |dz   fS ||d      |dz   fS )	Nr   ),[]rc   z()r   zUnresolvable type rm   rn   )lenstripappendtuple)	exprrf   irg   partspart_lenpartrj   parseNestedExprs	          r)   rx   z8createResolutionCallbackFromEnv.<locals>.parseNestedExpr   sP   #d)mQ >FA #d)mQ >
 8tq5Ld2Ahnn.7@#5d2AhZ!@@D	>T!W^7NAw#~~1gnHFA,T!"Xv>ND(LLMA 1gn u:>e%q1u,,a>1q5((r+   c                 l    	  | |      \  }}|t        |       k(  sJ d       |S # t        $ r 	 Y y w xY w)Nz;whole expression was not parsed, falling back to c++ parser)ro   	Exception)rs   rf   value
len_parsedrx   s       r)   	parseExprz2createResolutionCallbackFromEnv.<locals>.parseExpr   s_    	 /f =E:"  MLM  L 	 	s   "& 
33c                      |       S r/   r   )rs   lookup_baser}   s    r)   <lambda>z1createResolutionCallbackFromEnv.<locals>.<lambda>  s    	$4 r+   )r   r   int)r   rj   r}   rx   s   `@@@r)   createResolutionCallbackFromEnvr      s)    3)sCx )8  54r+   	frames_upc                     t        j                         }d}|| dz   k  r|J |j                  }|dz  }|| dz   k  r|J |j                  |j                   G fdd      }t         |             S )a\  
    Creates a function which, given a string variable name,
    returns the value of the variable in the scope of the caller of
    the function which called createResolutionCallbackFromFrame (by default).

    This is used to enable access in-scope Python variables inside
    TorchScript fragments.

    frames_up is number of additional frames to go up on the stack.
    The default value is 0, which correspond to the frame of the caller
    of createResolutionCallbackFromFrame. Also for example, if frames_up is set
    to 1, then the frame of the caller's caller of createResolutionCallbackFromFrame
    will be taken.

    For example, the following program prints 2::

        def bar():
            cb = createResolutionCallbackFromFrame(1)
            print(cb("foo"))


        def baz():
            foo = 2
            bar()


        baz()
    r   rc   c                       e Zd Z fdZy).createResolutionCallbackFromFrame.<locals>.envc                 l    |v r|   S |v r|   S |t        t              v rt        t        |      S y r/   )dirbuiltinsrG   )r0   key	f_globalsf_localss     r)   __getattr__z:createResolutionCallbackFromFrame.<locals>.env.__getattr__<  sD    h}$	! ~%H%x-- &r+   Nr3   r!   r4   r   )r   r   s   r)   envr   ;  s    	.r+   r   )inspectcurrentframef_backr   r   r   )r   framert   r   r   r   s       @@r)   !createResolutionCallbackFromFramer     s    :   "E	A
i!m
   	Q i!m

 ~~HI. . +3511r+   c                     i }|j                  | j                         t        | j                  j                        D ]!  \  }}| j
                  |   j                  ||<   # |S )zC
    Get a dictionary of closed over variables from a function
    )update__globals__	enumerate__code__co_freevars__closure__cell_contents)r[   capturesindexcaptured_names       r)   get_closurer   G  s^     HOOBNN# )"++*A*A B F}"$.."7"E"EF Or+   c                 R    t        |        G fdd      }t         |             S )z
    Create a resolutionCallback by introspecting the function instead of
    looking up the stack for the enclosing scope
    c                       e Zd Z fdZy);createResolutionCallbackFromClosure.<locals>.closure_lookupc                     |v r|   S t        t        |      rt        t        |      S t        t        |      rt        t        |      S y r/   )r$   r"   rG   r   )r0   r   closures     r)   r   zGcreateResolutionCallbackFromClosure.<locals>.closure_lookup.__getattr__  sE    g~s|#%vs++3'x--r+   Nr   )r   s   r)   closure_lookupr     s    	r+   r   )r   r   )r[   r   r   s     @r)   #createResolutionCallbackFromClosurer     s(    
 "oG
 
 +>+;<<r+   c           
      n   t        |       ryt        j                  j                  t        t
        t        f}t        | |      ry| j                  }|D cg c].  }t        j                  t        | |d             rt        | |      0 }}|D cg c]  }t        |d       }}t        |      S c c}w c c}w )NFr   )is_ignored_fnrC   nnModulerr   listrz   
issubclass__dict__r   	isroutinerG   r$   all)clsignored_builtin_classesnamesrJ   fnsr[   has_codes          r)   can_compile_classr     s     S  %xxtYG#./LLE WS$56 	TC 
 366BJ'6H6x=
 7s   3B-B2c                     	 t        j                  |       }g }|j                  j	                         D ]0  \  }}|j
                  |j                  k(  s |j                  |       2 |S # t        $ r g cY S w xY w)aU  
    Gets names of all POSITIONAL_OR_KEYWORD arguments for callable `fn`.
    Returns an empty list when other types of arguments are present.

    This is used by `torch.jit.trace` to assign meaningful argument names to
    traced functions and modules.

    Args:
        fn: A callable.
    Returns:
        Argument names: List[str]
    )r   	signaturerz   
parametersitemskindPOSITIONAL_OR_KEYWORDrq   )r[   callable_signatureargument_namesrJ   params        r)   get_callable_argument_namesr     s    $..r2 N)44::< $e zzU888d#$   	s   A( (A65A6c                    t        | t        j                        r| j                  S t        | t        j                        r0dj                  t        | j                        | j                  g      S t        | t        j                        rLt        r| j                  n| j                  j                  }t        | j                         dt        |       dS t        | t        j                        r2dj                  | j                  D cg c]  }t        |       c}      S t        | t        j                        r| j                   S yc c}w )z
    Convert an AST node containing a type annotation to the string present in the source
    that represents the same annotation.
    rB   rm   rn   rl   N)r%   astNameid	Attributejoinget_annotation_strr{   attr	Subscriptr   slicer   eltsConstant)
annotationsubscript_sliceelts      r)   r   r     s    
 *chh'}}	J	.xx+J,<,<=zOPP	J	..:***
@P@P@V@V$Z%5%567q9KO9\8]]^__	J			*xxJOOLS+C0LMM	J	-""#$  Ms   
Ec                 B   t         j                  |       }|	 t        j                  |       }t        j
                  |       }|j                  j                         D ci c]R  \  }}|j                  t        j                  j                  ur't        |j                  t              s||j                  T }}}t        j                  t        j                   |            }t#        |j$                        dk7  s't        |j$                  d   t        j&                        st)        d|  d      |j$                  d   }i }	|j*                  j*                  D ]A  }
|
j                  rt-        |
j                        nd}|)|
j.                  }||v s:||   |	|<   C t-        |j0                        }|du}|j2                  }|t        j                  j                  uxr t        |t               }|r|r||	|<   |	S # t        $ r}t	        d|  d      |d}~ww xY wc c}}w )a  
    Get a dictionary containing type resolution mappings necessary to resolve types
    for the literal annotations on 'fn'. These are not considered to be closed-over by fn
    and must be obtained separately (e.g. using this function).

    Args:
        fn: A callable.
    Returns:
        A Dict[str, Any] containing a mapping from the literal annotations used on
        fn to the Python objects they refer to.
    NzFailed to get source for z using inspect.getsourcerc   r   z	Expected z to be a function)loaderr`   r   	getsourceOSErrorr   r   r   r   	Parameteremptyr%   strr   parsetextwrapdedentro   bodyFunctionDefrK   argsr   argreturnsreturn_annotation)r[   srcer   rJ   	parametername_to_typeafannotation_to_typer   arg_annotation_strarg_nameliteral_return_annotationvalid_literal_annotationr   valid_return_annotation_types                    r)   get_type_hint_capturesr     s     

B
C
{	##B'C !!"%I  )3399;D)w'8'8'>'>>9//5 	i"""L  			(//#&'A
166{az!&&)S__EYrd*;<==	q	A
 vv{{ L 36..s~~.d 	 %
 77|#5A(5K12#L, !3199 =8D!33!2!2!8!88 	3,c22 !  $@8I45A  	+B4/GH	s   G:  AH:	HHHc           	         | j                   D cg c]-  }t        j                  t        | |            rt        | |      / }}|D cg c]'  }t        j                  |      rt        |d      s&|) }}i |D ]6  }j                  t        |             j                  t        |             8 fd}|S c c}w c c}w )z
    This looks at all the methods defined in a class and pulls their closed-over
    variables into a dictionary and uses that to resolve variables.
    r   c                 8    | v r|    S t        t        | d       S r/   )rG   r   )r   r   s    r)   lookup_in_classz@createResolutionCallbackForClassMethods.<locals>.lookup_in_classN  s#    (?C= 8S$//r+   )	r   r   r   rG   	isbuiltinr$   r   r   r   )r   rJ   r   r[   r   r   s        @r)   'createResolutionCallbackForClassMethodsr   8  s     LLWS$/0 	TC  
X"7#4#4R#8WR=W2
XC
XH 4B(.r2340 + Ys   2B:B?#B?0B?c                 n     fd}j                    j                   j                   }|_         nRj                    j                   j                   }|_         n&j                   j                   d}nt        d      ||_         |||_        |||_         dt        |<   |S )z
    Dispatches to either of 2 script functions based on a boolean argument.
    In TorchScript, the boolean argument must be constant so that the correct
    function to use can be determined at compile time.
    c                  f    }|v r|   }nt        |       k  r|    }|r | i |S  | i |S r/   )ro   )r   kwargsdispatch_flag	arg_indexr   defaultif_falseif_trues      r)   r[   zboolean_dispatch.<locals>.fnf  sR    v"8,MT" OMD+F++T,V,,r+   Nz&only one function can have a docstring)r   r   r   r   r   )__doc__rK   r!   r3   r   )	r   r   r   r   r   rQ   	func_namer[   docs	   `````    r)   boolean_dispatchr   W  s    
- 
- 8#3#3#?				!goo&Aoo				!goo&=CDDBJ# r Ir+   c                   (    e Zd ZdZdZdZdZdZdZdZ	y)	FunctionModifierszn
    Used to denote the behavior of a function in TorchScript. See export() and
    ignore() for details.
    z:unused (ignored and replaced with raising of an exception)z>ignore (leave as a call to Python, cannot be torch.jit.save'd)z7export (compile this function even if nothing calls it)z>default (compile if called from a exported function / forward)zNif this method is not scripted, copy the python method onto the scripted modelzB_drop (function is fully ignored, declaration can be unscriptable)N)
r3   r!   r4   r   UNUSEDIGNOREEXPORTDEFAULTCOPY_TO_SCRIPT_WRAPPER_DROPr   r+   r)   r   r     s.    
 JFMFFFNGX  QEr+   r   c                 0    t         j                  | _        | S )a  
    This decorator indicates that a method on an ``nn.Module`` is used as an entry point into a
    :class:`ScriptModule` and should be compiled.

    ``forward`` implicitly is assumed to be an entry point, so it does not need this decorator.
    Functions and methods called from ``forward`` are compiled as they are seen
    by the compiler, so they do not need this decorator either.

    Example (using ``@torch.jit.export`` on a method):

    .. testcode::

        import torch
        import torch.nn as nn

        class MyModule(nn.Module):
            def implicitly_compiled_method(self, x):
                return x + 99

            # `forward` is implicitly decorated with `@torch.jit.export`,
            # so adding it here would have no effect
            def forward(self, x):
                return x + 10

            @torch.jit.export
            def another_forward(self, x):
                # When the compiler sees this call, it will compile
                # `implicitly_compiled_method`
                return self.implicitly_compiled_method(x)

            def unused_method(self, x):
                return x - 20

        # `m` will contain compiled methods:
        #     `forward`
        #     `another_forward`
        #     `implicitly_compiled_method`
        # `unused_method` will not be compiled since it was not called from
        # any compiled methods and wasn't decorated with `@torch.jit.export`
        m = torch.jit.script(MyModule())
    )r   r  _torchscript_modifierr[   s    r)   exportr	    s    T  177BIr+   c                    t        | t              rZ| }t        |j                  dt        j
                         |j                  r%t        |j                  dt        j
                         |S t        j
                  | _        | S )a  
    This decorator indicates to the compiler that a function or method should
    be ignored and replaced with the raising of an exception. This allows you
    to leave code in your model that is not yet TorchScript compatible and still
    export your model.

        Example (using ``@torch.jit.unused`` on a method)::

            import torch
            import torch.nn as nn


            class MyModule(nn.Module):
                def __init__(self, use_memory_efficient):
                    super().__init__()
                    self.use_memory_efficient = use_memory_efficient

                @torch.jit.unused
                def memory_efficient(self, x):
                    import pdb

                    pdb.set_trace()
                    return x + 10

                def forward(self, x):
                    # Use not-yet-scriptable memory efficient mode
                    if self.use_memory_efficient:
                        return self.memory_efficient(x)
                    else:
                        return x + 10


            m = torch.jit.script(MyModule(use_memory_efficient=False))
            m.save("m.pt")

            m = torch.jit.script(MyModule(use_memory_efficient=True))
            # exception raised
            m(torch.rand(100))
    r  )r%   propertysetattrfgetr   r   fsetr  )r[   props     r)   unusedr    sm    P "hII.0A0H0H	
 99		24E4L4L 077BIr+   c                   *    e Zd Zd ZdedededdfdZy)_IgnoreContextManagerc                      y r/   r   )r0   r   s     r)   rY   z_IgnoreContextManager.__init__      r+   exc_type	exc_value	tracebackr   Nc                      y r/   r   )r0   r  r  r  s       r)   __exit__z_IgnoreContextManager.__exit__
  r  r+   )r3   r!   r4   rY   r   r  r   r+   r)   r  r    s(        r+   r  c                 4    t               r }t        j                  |_        |S t	         t
              st        d        |j                  dd      }|rt        j                  dt               | n rt        j                  dt                fd}|S )a&  
    This decorator indicates to the compiler that a function or method should
    be ignored and left as a Python function. This allows you to leave code in
    your model that is not yet TorchScript compatible. If called from TorchScript,
    ignored functions will dispatch the call to the Python interpreter. Models with ignored
    functions cannot be exported; use :func:`@torch.jit.unused <torch.jit.unused>` instead.

    Example (using ``@torch.jit.ignore`` on a method)::

        import torch
        import torch.nn as nn


        class MyModule(nn.Module):
            @torch.jit.ignore
            def debugger(self, x):
                import pdb

                pdb.set_trace()

            def forward(self, x):
                x += 10
                # The compiler would normally try to compile `debugger`,
                # but since it is `@ignore`d, it will be left as a call
                # to Python
                self.debugger(x)
                return x


        m = torch.jit.script(MyModule())

        # Error! The call `debugger` cannot be saved since it calls into Python
        m.save("m.pt")

    Example (using ``@torch.jit.ignore(drop=True)`` on a method):

    .. testcode::

        import torch
        import torch.nn as nn

        class MyModule(nn.Module):
            @torch.jit.ignore(drop=True)
            def training_method(self, x):
                import pdb
                pdb.set_trace()

            def forward(self, x):
                if self.training:
                    self.training_method(x)
                return x

        m = torch.jit.script(MyModule())

        # This is OK since `training_method` is not saved, the call is replaced
        # with a `raise`.
        m.save("m.pt")

    .. testcleanup::

        import os
        os.remove('m.pt')
    zCArgument to @torch.jit.ignore must be a bool or a function but got drop_on_exportNzignore(drop_on_export=True) has been deprecated. TorchScript will now drop the function call on compilation. Use torch.jit.unused now. {})categoryzzignore(True) has been deprecated. TorchScript will now drop the function call on compilation. Use torch.jit.unused now. {}c                 d    rt         j                  | _        | S t         j                  | _        | S r/   )r   r   r  r  )r[   drops    r)   	decoratorzignore.<locals>.decoratorn  s0    '8'?'?B$ 	 (9'?'?B$	r+   )callabler   r  r  r%   boolrK   popwarningswarnFutureWarning)r  r   r[   r  r  s   `    r)   ignorer&    s    B ~ #4#;#; 	dD!""&)
 	
 ZZ 0$7N@"	
 	@"	
 r+   c                 0    t         j                  | _        | S r/   )r   r  r  r  s    r)   _dropr(  x  s    066BIr+   c                 0    t         j                  | _        | S r/   )r   r  r  r  s    r)   _copy_to_script_wrapperr*  }  s    0GGBIr+   c                     t        |       D ]D  }t        | |      st        | |      }t        |      s(t	        |      t
        j                  u sD y y)NTF)r   r$   rG   r   get_torchscript_modifierr   r  )modrJ   items      r)   module_has_exportsr/    sN    C  33%D~+D15F5M5MM  r+   c                 j    t        |       }|y|t        j                  u xs |t        j                  u S NF)r,  r   r   r  )r[   r   s     r)   should_dropr2    s7    #B'D|$+++Nt7H7N7N/NNr+   c                     t        |       }|t        j                  u xs& |t        j                  u xs |t        j                  u S r/   )r,  r   r   r  r  r[   r-  s     r)   r   r     sH    
"2
&C ''' 	*#***	*#)))r+   c                 <    t        |       }|t        j                  u S r/   )r,  r   r  r4  s     r)   _is_drop_fnr6    s    
"2
&C#))))r+   c                 N    t        t        j                  | |d       t              S )N)r   )r%   r   getattr_staticstaticmethodr   r[   s     r)   is_static_fnr;    s    g,,S"dC\RRr+   c                 B    t        j                  | |      j                  S r/   )r   r8  __func__r:  s     r)   get_static_fnr>    s    !!#r*333r+   c                     t        |       sy t        | d      r| j                  } t        | dt        j
                        S )Nr=  r  )r   r$   r=  rG   r   r  r  s    r)   r,  r,    s6    B<r:[[2.0A0I0IJJr+   c                 .    t        |       }|y ||_        y r/   )r,  r  )orignewr   s      r)   copy_torchscript_modifierrC    s    #D)D| $Cr+   _overloaded_fnsaP  
Example usage of overload function:
@torch.jit._overload
def my_function(x: type0) -> type0: # decl 1
    pass

@torch.jit._overload
def my_function(x: type1) -> type1: # decl 2
    pass

def my_function(x):                 # implementation
    if isinstance(x, type0):
        return x
    elif isinstance(x, type1):
        return x
c           	          t        |      \  }}}d|  dt        |       d| d| d	dj                  |      z   dz   t        z   S )NzImplementation for the z "zk" is missing. Please make sure a definition is provided and defined after all overload declarations.
File "z", line z:
 
)r   rR   r   _OVERLOAD_EXAMPLE)r   rO   sourcelinesfile_linenofilenames        r)   ,get_overload_no_implementation_error_messagerL    sj    )B3)G&Kh
!$r/#*>)? @
(;-s	4 ''+
	 		
 	r+   c                    	 t        |       }|j                  j
                  d   j
                  }d }d }t        |      dk7  s ||d         sU ||d         sId}|dj                  |j                  j                  d      d d	       z  }|d
t        z   z  }t        |      y y # t        $ r#}t        j                  d|  d       Y d }~y d }~ww xY w)Nz=Unable to retrieve source for @torch.jit._overload function: rB   r   c                 6    t        | t        j                        S r/   )r%   r   Passxs    r)   is_passz%_check_overload_body.<locals>.is_pass  s    !SXX&&r+   c                     t        | t        j                        xrB t        | j                  t        j                        xr | j                  j                  t
        u S r/   )r%   r   Exprr{   r   EllipsisrP  s    r)   is_ellipsisz)_check_overload_body.<locals>.is_ellipsis  sA    q#((# *177CLL1*)	
r+   rc   zHOnly `pass` statement or `...` can be the body of overload declaration:
rG  r   z$ <- Expecting `pass` or `...` here!
)r   r   r#  r$  r   r   ro   r   r\   re   rH  rK   )func
parsed_defr   r   rR  rV  msgs          r)   _check_overload_bodyrZ    s    t_
 >>q!&&D'
 4yA~gd1g.+d1g2FW 	 	tyy**006r:;;69JJJ3 3G.)   	KD6QRS	
 	s   B% %	C.CCc                     t        |        t        |       }t        j                  |      }|g }|t        |<   |j	                  |        | S r/   )rZ  rR   rD  r_   rq   )rW  	qual_namefn_overload_lists      r)   	_overloadr^    sN    %I&**95%5	"D!Kr+   c                 ,    t         j                  |       S r/   )rD  r_   r\  s    r)   _get_fn_overloadsra    s    y))r+   c                     t         | = y r/   )rD  r`  s    r)   _clear_fn_overloadsrc    s
    	"r+   c                     t        j                         }t        d      D ]  }|J |j                  } |J |j                  j
                  }|j                  j                  }||fS Nr5   )r   r   ranger   f_codeco_nameco_firstlineno)methodcurrent_framert   
class_nameline_nos        r)   get_class_name_linenorn    sy    ((*M 1X -%	
%%,,	- $$$%%--J""11Gwr+   _overloaded_methods_overloaded_method_class_filenoc                 :   t        |        t        |       }t        j                  |d       }|i }|t        |<   t	        |       \  }}|j                  |d       }|g }|||<   |t
        ||f<   nt
        ||f   }||k7  rt        d      |j                  |        | S )NzmCannot currently overload the same method name in two different classes with the same name in the same module)rZ  rR   ro  r_   rn  rp  rK   rq   )rW  r\  class_name_maprl  rm  method_overloadsexisting_linenos          r)   _overload_methodru  6  s    %I(,,Y=N)7I&/5J%))*d;%5z"CJ'J(?@99j:QRg%A 
 D!Kr+   c                 T   t        | d      sy t        |       }t        j                  |d       }|y |j                  |j                  d       }|y t        |       d   }t        |      d   }|t        t        |      d         z   }||k\  r||k  st        dt        |       z         |S )Nr3   rc   r   zLOverloads are not useable when a module is redeclared within the same file: )	r$   rR   ro  r_   r3   r   ro   AssertionErrorr   )rj  	mod_classr\  rr  	overloadsmethod_line_nomod_class_filenomod_end_filenos           r)   _get_overloaded_methodsr}  Q  s    6:&'I(,,Y=N""9#5#5t<I.v6q9N0;A>%,Ei,PQR,S(TTN..>^3SZ&k
 	
 r+   c                     | t         u rt        d       t        | d      syt        |       }t        r| j
                  dk(  r	|t        u ry| j
                  dk(  xr |t         u xs |t        u S )Nr   r!   Fr   Tr"   )r   'raise_error_container_parameter_missingr$   r	   r   r!   rr   r(   
ann_origins     r)   is_tupler  h  se    
e|/8 3%CJ*4u9L>>X%V:+>+U*PUBUVr+   c                     | t         u rt        d       t        | d      syt        |       }t        r| j
                  dk(  r	|t        u ry| j
                  dk(  xr |t         u xs |t        u S )Nr
   r!   Fr   Tr"   )r
   r  r$   r	   r   r!   r   r  s     r)   is_listr  v  b    
d{/73%CJ*4t9K>>X%T:+=+StASTr+   c                     | t         u rt        d       t        | d      syt        |       }t        r| j
                  dk(  r	|t        u ry| j
                  dk(  xr |t         u xs |t        u S )Nr   r!   Fr   Tr"   )r   r  r$   r	   r   r!   dictr  s     r)   is_dictr    r  r+   c                     | t         u rt        d       t        | t              xs0 t	        | d      xr" | j
                  dk(  xr t        |       t         u S )Nr   r!   r"   )r   r  r%   r   r$   r!   r	   r'   s    r)   is_unionr    sR    
e|/8c+, \" 	'NNh&	'_%r+   c                 r    | t         u rt        d       d }d } ||       xs t        |       xr  ||       S )Nr   c                 b    t        | d      xr" | j                  dk(  xr t        |       t        u S )Nr!   r"   )r$   r!   r	   r   r'   s    r)   is_optional_as_optionalz,is_optional.<locals>.is_optional_as_optional  s3    C& .(*.CH,	
r+   c                 ^    t        |       }t        |      dk(  xr d |v xs t        d       |v S re  )r   ro   r&   )r(   ann_argss     r)   is_union_as_optionalz)is_optional.<locals>.is_union_as_optional  s2    C=8}!Rtx'7'Q4:;QRr+   )r   r  r  )r(   r  r  s      r)   is_optionalr    s>    
h/
;
S #3'XHSM,W>RSV>WXr+   c                 J    | t         u rt        d      t        |       t         u S )Nz_Attempted to use Future without a contained type. Please add a contained type, e.g. Future[int])r   rK   r	   r'   s    r)   	is_futurer    s,    
f}
 	

 c?f$$r+   c                 6    | t         u ryt        |       t         u S )NT)r   r	   r'   s    r)   is_awaitr    s    
f}c?f$$r+   )PyRRef)RRefc                 J    | t         u rt        d      t        |       t         u S )Nz[Attempted to use RRef without a contained type. Please add a contained type, e.g. RRef[int])r  rK   r	   r'   s    r)   is_rrefr    s,    $; 
 #$&&r+   c                 "    t        | t              S r/   )r%   r  rO   s    r)   is_rref_instancer    s    #v&&r+   c                      yr1  r   r  s    r)   r  r    s    r+   c                 D    t        |       sy t        j                  |       S r/   )r   r   r_   r  s    r)   _try_get_dispatched_fnr    s    B<!!"%%r+   locc           
         |
t               }t        | t              rt        | d      sJ t        | d      r5| j                  D cg c]  }|| j
                  v r| j
                  |   ! }}ng }t        j                  d d dk  rt        | di       }nNt        j                  |       }t        |      dk(  r+t        | d      rt        j                  | j                        }g }| j                  D ]  }||v r||   }t        |t              rD|B ||j                        }|,t!        d| d	| j"                   d
|j%                                |}t&        j(                  j*                  j-                  |||      }	|j/                  |	       |j/                  t&        j0                  j2                  j5                                 t7        |       j"                  | j                  ||fS c c}w )N_fields_field_defaultsr5   r   __annotations__r   __base__zUnknown type annotation: 'z' in NamedTuple zh. Likely due to partial support for ForwardRef parameters in NamedTuples, see #95858. Issue occurred at )r   r   rr   r$   r  r  sysversion_inforG   r   get_annotationsro   r  r%   r   __forward_arg__
ValueErrorr3   	highlightrC   jitannotationsann_to_typerq   rD   
TensorTypegetInferredr&   )
rO   r  rcbfielddefaultsobj_annotationsr  
field_typercb_typethe_types
             r)   _get_named_tuple_propertiesr    s   
 {lc5!gc9&===s%& 
+++ &
 
  g%!#'8"=!11#61$j)A%55cllCOK 3BO#(/JH *j1coz99:#$4ZL@PQTQ]Q]P^ _..1mmo->@ 
 &
yy,,88S#NHx(uxx22>>@Ag3Bh 9s{{KAAK
s   $G'unqual_namefield_namesr  c                 <    t        j                  |||      } ||  S )N)r  )collections
namedtuple)tr  r  r  	TupleTypes        r)   _create_named_tupler  ,  s"     &&{K(SIa=r+   c               #   4  K   t         j                  j                         } t         j                  j                  d d        	 d  t         j                  j                  | d   | d          y # t         j                  j                  | d   | d          w xY wwNr   rc   )rC   rD   _jit_get_emit_hooks_jit_set_emit_hooks)hookss    r)   _disable_emit_hooksr  6  sl     HH((*E	HH  t,9$$U1XuQx8$$U1XuQx8s   ?BA- 'B-(BBc                     dd}dd}y )Nc                     t         j                  j                         | _        t         j                  j	                  d d        y r/   )rC   rD   r  r  r  rX   s    r)   	__enter__z0_disable_emit_hooks_decorator.<locals>.__enter__A  s*    XX113
$$T40r+   c                 x    t         j                  j                  | j                  d   | j                  d          y r  )rC   rD   r  r  )r0   r   s     r)   r  z/_disable_emit_hooks_decorator.<locals>.__exit__E  s&    $$TZZ]DJJqMBr+   r   Nr   )_DecoratorContextManagerr  r  s      r)   _disable_emit_hooks_decoratorr  @  s    1Cr+   c                 N    t        j                  |       syt        | t              S r1  )r   isclassr   rz   r  s    r)   _is_exceptionr  I  s    ??3c9%%r+   c                 F    | dk(  rt        d      t        d|  d|  d      )Nr   z]Attempted to use Dict without contained types. Please add contained type, e.g. Dict[int, int]zAttempted to use z= without a contained type. Please add a contained type, e.g. z[int])rK   target_types    r)   r  r  O  sC    f
 	

 
K= )=-u	 r+   c                     | t         u s| t        u rt        d       y | t        u s| t        u rt        d       y | t
        u s| t        u rt        d       y | | t        u rt        d       y y )Nr
   r   r   r   )r
   r   r  r   rr   r   r  r   r  s    r)   check_args_existr  ]  sa    dkT1/7		!5/8		t 3/7		x 7/
; !8r+   c                 N    | g k(  s
| i k(  s| dk(  rt        j                  d       y y )Nr   zThe inner type of a container is lost when calling torch.jit.isinstance in eager mode. For example, List[int] would become list and therefore falsely return True for List[float] or List[str].)r#  r$  r  s    r)   check_empty_containersr  h  s+    
byC2I	
 "+r+   c                    t        |      }t        |       |y|t        u s|t        u r\t	        |        t        | t              syt        |      d   }t        |      }| D ]!  }|rt        ||      r yt        ||      r! y y|t        u s|t        u rt	        |        t        | t              syt        |      d   }t        |      d   }| j                         D ]=  \  }}	t        ||      s yt        |      }
|
rt        |	|      r. yt        |	|      r= y y|t        u s|t        u r~t	        |        t        | t              syt        |      }t        |       t        |      k7  ryt        | |      D ]/  \  }}t        |      }|rt        ||      r  yt        ||      r/ y y|t        u st!        |t"              r>| yt        |      }|D ]+  }t        |      }|rt        | |      c S t        | |      s+ y y)NFr   Trc   )r	   r  r   r
   r  r%   r   container_checkerr   r  r   r   rr   ro   zipr   r   r   )rO   r  origin_typearg_type
arg_originelkey_typeval_typer   val
val_origin	arg_typesel_type	el_origininner_typesr  t_origins                    r)   r  r  u  s	   [)K[!		t 3s##t$K(+)
 	B(X6 H-	 		t 3s##t$K(+K(+		 		HCc8,#H-J(h7 X.		 		!5s##u%[)	s8s9~%sI. 	KB"7+I(W5 G,	 		%" ;{+ 	A!!}H(a00C#	 r+   c                    t        |t        j                  j                        r1t        |t              st        d      |D ]  }t        | |      s y yt        |      }|rt        | |      S t        |       t        | |      S )NzPThe second argument to `torch.jit.isinstance` must be a type or a tuple of typesTF)
r%   r  abc	Containerrr   rK   _isinstancer	   r  r  )rO   r  t_typer  s       r)   r  r    s    +{889+u-& 
 " 	F3'	 [)K k22 [! c;''r+   c                   D     e Zd Zdeej
                     f fdZd Z xZS )_TensorExtractortensorsc                2    t        |   |i | || _        y r/   )superrY   r  )r0   r  r   r   	__class__s       r)   rY   z_TensorExtractor.__init__  s    $)&)r+   c                 l   t        |t        j                        r| j                  j	                  |       yt        |t
              ryt        |t              st        |      ryt        |t              ryt        |t        j                  j                        ryt        |t        j                        ryy )NrF  )r%   rC   Tensorr  rq   r   CFuturer  CAwaitcudaEvent	threadingThread)r0   rO   s     r)   persistent_idz_TensorExtractor.persistent_id  s    c5<<(LL$ c8$ c7#'7'<c6"c5::++,c9++,r+   )	r3   r!   r4   r
   rC   r  rY   r  __classcell__)r  s   @r)   r  r    s    tELL'9 r+   r  c                 l    g }t        t        j                         d|      }|j                  |        |S )z
    This function is exclusively called from C++.
    See ``torch/csrc/jit/python/python_ivalue.h``.

    It extracts the tensors contained in the given object, through pickling.
    )protocolr  )r  ioBytesIOdump)rO   r  	extractors      r)   _extract_tensorsr    s.     #%G GLINN3Nr+   c                     t        | t        j                  j                        r#t	        | j
                  j                               S t        | t        j                  j                        r| j                  S y r/   )	r%   rC   r  ScriptModuler   _c_typerE   rF   r  s    r)   _get_model_idr	    sN    #uyy--.366<<>""	C11	2!!!r+   )T)r   )Fr  )NN)r   r   r   r  
contextlibrH   r   r   pickler  r   r  r1   r"   r#  weakrefr   r   r   r   r   r   r	   r
   r   r   r   r   rC   torch.distributed.rpctorch.package._manglingpackage	_manglingrL   torch._awaitsr   torch._Cr  r   r  torch._sourcesr   r   r   torch.futuresr  r   r!  r  r   	UnionTyper   _threadr   ImportError_dummy_threadWeakKeyDictionaryr   FAKE_FILENAME_PREFIXr*   r-   BroadcastingList1rf  rt   globalsr9   r   rR   rT   r   r   r   r   r   r   r   r   r   r   r   r   r   r	  r  AbstractContextManagerr  r&  r(  r*  r/  r2  r   r6  r;  r>  r,  rC  rD  rH  rL  rZ  r^  ra  rc  rn  ro  rp  ru  r}  r  r  r  r  r  r  r  distributedrpcis_availabletorch._C._distributed_rpcr  r  r  r  r  rD   _jit_tree_viewsSourceRanger  r  contextmanagerr  r  r  r  r  r  r  r  Picklerr  r  r	  rI   __new__
__format____repr____str__r   r+   r)   <module>r*     s         	  
          
  2 2   8 K K    ,,6eDk 6 --8uT{ 8eD#I../ /w 
&H G N 
 / T   () 	q! :A(9GI $%:d .C$c C$L$ $ 
>5B12 12h
t=,d *tCy >,Tn>4nQ Q +\6tJ== gT

Ot O *t *
ST S4K% .0c4>)* / $	 @	*#U38_ 4 =? T#tCh$7889 > ?A eCHos&:!; @6.WT W
UD 
U
UD 
UY$%d %%T % 	%%'0*' '' '
 
& ;?OB	%((**66	7OBd c CHo	 9 9C&$ &<
?4 ?D(T (2v~~ <
(3-  g	$))

	$))

	$))

	$))

	 I.  &%%H&s   ,O   OO