a
    7Sic                     @   s  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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ZddlZ
ddlmZ ddlmZmZmZ ddlmZ ddlm  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' ej(dd dkrdd	lm)Z) ndd	l*m)Z) e%e+d
< zddl,Z,e,j-Z-W n" e.yb   ddl/Z/e/j-Z-Y n0 e0 Z1de+d< dd Z2de3dddZ4dd Z5dd Z6e7dddZ8e"e9 dddZ:dd Z;dd Z<dd  Z=d!d" Z>G d#d$ d$e?Z@d%d& ZAd'd( ZBG d)d* d*ejCZDdd,d-ZEd.d/ ZFd0d1 ZGe7dd2d3ZHe7dd4d5ZIe7dd6d7ZJd8d9 ZKd:d; ZLddd<d=ZMi aNe e9e"e f e+d>< d?ZOd@dA ZPdBdC ZQdDdE ZRdFdG ZSdddHdIZTe$e9e3f ddJdKZUi aVe e9e e9e"e f f e+dL< i ZWdMdN ZXdOdP ZYe7ddQdRZZe7ddSdTZ[e7ddUdVZ\dWdX Z]dYdZ Z^e7dd[d\Z_e
j`jab rdd]lmcZc dd^ldmeZe e7dd_d`Zfe7ddadbZgne7ddcdbZge7ddddeZhG dfdg dge?Ziei ZjekddhD ]Zlejem diel < qe7ddjdkZnde9ddmdnZododp Zpdqdr Zqe9e"e9 e$edsf dtdudvZrejsdwdx ZtdddydzZue7dd{d|Zvddd}d~Zwdd Zxdd ZyddddZzddddZ{e7dddZ|e7dddZ}G dd dej~Zdd ZdS )z
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)dedent)Future)get_source_lines_and_file	parse_def
fake_range)
AnyCallableDictGenericListOptionalTupleTypeTypeVarUnion   )      )FinalLockTypez8weakref.WeakKeyDictionary[Callable, Dict[str, Callable]]boolean_dispatchedc                    sB    fdd t ttf d fddfddfd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                    sN   d| v r@|  d}|d }d|dd  }t||} ||S t|| S d S )N.r      )splitjoingetattr)qualified_namemodulepartsbaseZremaining_piecesZmodule_value)lookupInModule O/var/www/html/django/DPS/env/lib/python3.9/site-packages/torch/_jit_internal.pyr    ;   s    


z7createResolutionCallbackFromEnv.<locals>.lookupInModulereturnc                    s"  d}|t | k r&| | dvr&|d7 }q| d | dkr>d|fS  | d |  |}|d usrJ d| d |  |t | ks| | dkr||fS | | dksJ g }| | dkrd}|d7 }| |d  |\}}|| ||7 }qt |dkr
|t| |d fS ||d  |d fS d S )	Nr   ),[]r   z()r!   zUnresolvable type r&   r'   )lenstripappendtuple)exprr   ir   r   Zpart_lenpart)r    parseNestedExprr!   r"   r/   E   s(    


z8createResolutionCallbackFromEnv.<locals>.parseNestedExprc                    sB   z( | |\}}|t | ks$J d|W S  ty<   Y d S 0 d S )Nz;whole expression was not parsed, falling back to c++ parser)r(   	Exception)r,   r   valueZ
len_parsed)r/   r!   r"   	parseExpra   s    z2createResolutionCallbackFromEnv.<locals>.parseExprc                    s
   |  S Nr!   )r,   )lookup_baser2   r!   r"   <lambda>o       z1createResolutionCallbackFromEnv.<locals>.<lambda>)r   r   int)r4   r!   )r    r4   r2   r/   r"   createResolutionCallbackFromEnv2   s    	
r8   )	frames_upc                    sl   t  }d}|| d k r4|dus$J |j}|d7 }q|dus@J |j|j G  fdddt}t| S )aZ  
    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   r   Nc                       s   e Zd Z fddZdS )z.createResolutionCallbackFromFrame.<locals>.envc                    s:   |v r| S | v r  | S |t tv r6tt|S d S r3   )dirbuiltinsr   selfkey	f_globalsf_localsr!   r"   __getattr__   s    z:createResolutionCallbackFromFrame.<locals>.env.__getattr__N__name__
__module____qualname__rB   r!   r?   r!   r"   env   s   rG   )inspectcurrentframef_backrA   r@   objectr8   )r9   framer-   rG   r!   r?   r"   !createResolutionCallbackFromFramer   s    
	rM   c                 C   s:   i }| | j t| jjD ]\}}| j| j||< q|S )zC
    Get a dictionary of closed over variables from a function
    )update__globals__	enumerate__code__co_freevars__closure__cell_contents)fncapturesindexZcaptured_namer!   r!   r"   get_closure   s
    rX   c                    s&   t |  G  fdddt}t| S )z
    Create a resolutionCallback by introspecting the function instead of
    looking up the stack for the enclosing scope
    c                       s   e Zd Z fddZdS )z;createResolutionCallbackFromClosure.<locals>.closure_lookupc                    s<   | v r | S t t|r$tt|S t t|r8tt|S d S r3   )hasattrtypingr   r;   r<   closurer!   r"   rB      s    



zGcreateResolutionCallbackFromClosure.<locals>.closure_lookup.__getattr__NrC   r!   r[   r!   r"   closure_lookup   s   r]   )rX   rK   r8   )rU   r]   r!   r[   r"   #createResolutionCallbackFromClosure   s    r^   r#   c                    sX   t  rdS tjjtttf}t |r*dS  j} fdd|D }dd |D }t	|S )NFc                    s(   g | ] }t t |d rt |qS r3   rH   	isroutiner   .0nameclsr!   r"   
<listcomp>   r6   z%can_compile_class.<locals>.<listcomp>c                 S   s   g | ]}t |d qS )rQ   )rY   )rb   rU   r!   r!   r"   rf     r6   )
is_ignored_fntorchnnModuler+   listr0   
issubclass__dict__all)re   Zignored_builtin_classesnamesfnsZhas_coder!   rd   r"   can_compile_class   s    
rq   c                 C   s`   zt | }W n ty$   g  Y S 0 g }|j D ]&\}}|j|jksPg   S || q4|S )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]
    )rH   	signaturer0   
parametersitemskindPOSITIONAL_OR_KEYWORDr*   )rU   Zcallable_signatureZargument_namesrc   paramr!   r!   r"   get_callable_argument_names  s    
rx   c                 C   s   t | tjr| jS t | tjr4dt| j| jgS t | tj	rrt
jdkrP| jn| jj}t| j dt| dS t | tjrddd | jD S t | tjst | tjr| j S dS )	z
    Convert an AST node containing a type annotation to the string present in the source
    that represents the same annotation.
    r   )r   	   r&   r'   r%   c                 S   s   g | ]}t |qS r!   )get_annotation_str)rb   eltr!   r!   r"   rf   2  r6   z&get_annotation_str.<locals>.<listcomp>N)
isinstanceastNameid	Attributer   rz   r1   attr	Subscriptsysversion_infoslicer   eltsConstantNameConstant)
annotationZsubscript_slicer!   r!   r"   rz   $  s    rz   c                 C   s   t | }dd |j D }t | }tt|}t|j	dksVt
|j	d tjsftd|  d|j	d }i }|jjD ]<}|jrt|jnd}|du rq||j}	|	|v r|||	 ||< q|t|j}
|
du}|j}|t jjuot
|t }|r|r|||
< |S )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.
    c                 S   s2   i | ]*\}}|j tjjurt|j ts||j qS r!   )r   rH   	Parameteremptyr|   str)rb   rc   	parameterr!   r!   r"   
<dictcomp>L  s   z*get_type_hint_captures.<locals>.<dictcomp>r   r   z	Expected z to be a functionN)rH   rr   rs   rt   	getsourcer}   parser   r(   bodyr|   FunctionDefRuntimeErrorargsr   rz   argreturnsreturn_annotationr   r   r   )rU   rr   Zname_to_typesrcafZannotation_to_typer   Zarg_annotation_strarg_nameZliteral_return_annotationZvalid_literal_annotationr   Zvalid_return_annotation_typer!   r!   r"   get_type_hint_captures:  s0    
	
 

r   c                    sN   fddj D }i  |D ] } t|  t| q fdd}|S )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.
    c                    s&   g | ]}t t |rt |qS r!   r_   ra   rd   r!   r"   rf     r6   z;createResolutionCallbackForClassMethods.<locals>.<listcomp>c                    s    |  v r |  S t t| d S d S r3   )r   r;   )r>   )rV   r!   r"   lookup_in_class  s    z@createResolutionCallbackForClassMethods.<locals>.lookup_in_class)rm   rN   rX   r   )re   rp   rU   r   r!   )rV   re   r"   'createResolutionCallbackForClassMethods  s    r   c           	         s    fdd}j du r4j dur4j }|_ nDj du rVj durVj }|_ n"j du rpj du rpd}ntd||_ |dur||_|dur||_ |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                     sN   d}|v r| }n t | k r*|   }|r<| i |S | i |S d S NF)r(   )r   kwargsZdispatch_flag	arg_indexr   if_falseif_truer!   r"   rU     s    
zboolean_dispatch.<locals>.fnNz&only one function can have a docstring)r   r   rW   defaultr   )__doc__r   rE   rD   r   )	r   r   r   r   r   module_name	func_namerU   docr!   r   r"   boolean_dispatch  s,    
r   c                   @   s$   e Zd ZdZdZdZdZdZdZdS )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 modelN)	rD   rE   rF   r   UNUSEDIGNOREEXPORTDEFAULTCOPY_TO_SCRIPT_WRAPPERr!   r!   r!   r"   r     s   r   c                 C   s   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rU   r!   r!   r"   export  s    *r   c                 C   sD   t | tr8| }t|jdtj |jr4t|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(MyModule, self).__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   )rU   propr!   r!   r"   unused   s    %
r   c                   @   s(   e Zd Zdd ZeeeddddZdS )_IgnoreContextManagerc                 K   s   d S r3   r!   )r=   r   r!   r!   r"   __init__3  s    z_IgnoreContextManager.__init__N)exc_type	exc_value	tracebackr$   c                 C   s   d S r3   r!   )r=   r   r   r   r!   r!   r"   __exit__6  s    z_IgnoreContextManager.__exit__)rD   rE   rF   r   r   r   r!   r!   r!   r"   r   2  s   r   Fc                    sv   t  r }tj|_|S t ts0td  |dd}|rTtj	dt
d | n rftj	dt
d  fd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                    s    rt j| _nt j| _| S r3   )r   r   r   r   r   dropr!   r"   	decorator  s    
zignore.<locals>.decorator)callabler   r   r   r|   boolr   popwarningswarnFutureWarning)r   r   rU   r   r   r!   r   r"   ignore9  s(    >
r   c                 C   s   t j| _| S r3   )r   r   r   r   r!   r!   r"   _copy_to_script_wrapper  s    r   c                 C   sB   t | D ]4}t| |rt| |}t|rt|tju r dS qdS )NTF)r:   rY   r   r   get_torchscript_modifierr   r   )modrc   itemr!   r!   r"   module_has_exports  s    

r   c                 C   s   t | }|d u rdS |tju S r   )r   r   r   )rU   r   r!   r!   r"   should_drop  s    r   c                 C   s   t | }|tju p|tju S r3   )r   r   r   r   )rU   r   r!   r!   r"   rg     s    rg   c                 C   s   t tj| |d dtS )N)r   )r|   rH   getattr_staticstaticmethodre   rU   r!   r!   r"   is_static_fn  s    r   c                 C   s   t | |jS r3   )rH   r   __func__r   r!   r!   r"   get_static_fn  s    r   c                 C   s*   t | sd S t| dr| j} t| dtjS )Nr   r   )r   rY   r   r   r   r   r   r!   r!   r"   r     s
    
r   c                 C   s   t | }|d u rd S ||_d S r3   )r   r   )orignewr   r!   r!   r"   copy_torchscript_modifier  s    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              	   C   sB   t |\}}}d|  dt| d| d| d	d| d t 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   _qualified_namer   _OVERLOAD_EXAMPLE)ru   objsourcelinesfile_linenofilenamer!   r!   r"   ,get_overload_no_implementation_error_message  s    r   c              
   C   s   zt | }W n8 tyD } z td|  d W Y d }~d S d }~0 0 |jjd j}dd }dd }t|dks||d s||d sd	}|d
|j	d
d d 7 }|dt
 7 }t|d S )Nz=Unable to retrieve source for @torch.jit._overload function: r   r   c                 S   s   t | tjS r3   )r|   r}   Passxr!   r!   r"   is_pass  s    z%_check_overload_body.<locals>.is_passc                 S   s   t | tjot | jtjS r3   )r|   r}   Exprr1   Ellipsisr   r!   r!   r"   is_ellipsis  s    z)_check_overload_body.<locals>.is_ellipsisr   zHOnly `pass` statement or `...` can be the body of overload declaration:
r   r   z$ <- Expecting `pass` or `...` here!
)r   OSErrorr   r   r}   r   r(   r   sourcer   r   r   )funcZ
parsed_defer   r   r   msgr!   r!   r"   _check_overload_body  s    $r   c                 C   s<   t |  t| }t|}|d u r.g }|t|< ||  | S r3   )r   r   r   getr*   )r   	qual_nameZfn_overload_listr!   r!   r"   	_overload   s    

r   c                 C   s
   t | S r3   )r   r   r   r!   r!   r"   _get_fn_overloads  s    r   c                 C   s
   t | = d S r3   )r   r   r!   r!   r"   _clear_fn_overloads  s    r   c                 C   sL   t  }tdD ]}|d us J |j}q|d us4J |jj}|jj}||fS Nr   )rH   rI   rangerJ   f_codeco_nameco_firstlineno)methodcurrent_framer-   
class_nameline_nor!   r!   r"   get_class_name_lineno  s    r  _overloaded_methodsc                 C   s   t |  t| }t|d }|d u r0i }|t|< t| \}}||d }|d u rjg }|||< |t||f< nt||f }||krtd||  | S )NzmCannot currently overload the same method name in two different classes with the same name in the same module)r   r   r  r   r  _overloaded_method_class_filenor   r*   )r   r   class_name_mapr   r   Zmethod_overloadsZexisting_linenor!   r!   r"   _overload_method.  s"    
r  c                 C   s   t | dsd S t| }t|d }|d u r.d S ||jd }|d u rHd S t| d }t|d }|tt|d  }||kr||kstdt|  |S )NrD   r   r   zLOverloads are not useable when a module is redeclared within the same file: )	rY   r   r  r   rD   r   r(   r0   r   )r   Z	mod_classr   r  Z	overloadsZmethod_line_noZmod_class_filenoZmod_end_filenor!   r!   r"   _get_overloaded_methodsF  s    
r  c                 C   sH   | t u rtd t| dsdS | jdkoFt| dd t u pFt| dd tu S )Nr   rE   FrZ   
__origin__)r   'raise_error_container_parameter_missingrY   rE   r   r+   annr!   r!   r"   is_tupleZ  s    

r  c                 C   sH   | t u rtd t| dsdS | jdkoFt| dd t u pFt| dd tu S )Nr   rE   FrZ   r  )r   r  rY   rE   r   rk   r	  r!   r!   r"   is_liste  s    

r  c                 C   sH   | t u rtd t| dsdS | jdkoFt| dd t u pFt| dd tu S )Nr	   rE   FrZ   r  )r	   r  rY   rE   r   dictr	  r!   r!   r"   is_dicto  s    

r  c                 C   s4   | t u rtd t| do2| jdko2t| dd t u S )Nr   rE   rZ   r  )r   r  rY   rE   r   r	  r!   r!   r"   is_uniony  s    
r  c                 C   s8   | t u rtd dd }dd }|| p6t| o6|| S )Nr   c                 S   s$   t | do"| jdko"t| dd tu S )NrE   rZ   r  )rY   rE   r   r   r	  r!   r!   r"   is_optional_as_optional  s
    
z,is_optional.<locals>.is_optional_as_optionalc                 S   s   | j }t|dkod |v S r   )__args__r(   )r
  Zann_argsr!   r!   r"   is_union_as_optional  s    z)is_optional.<locals>.is_union_as_optional)r   r  r  )r
  r  r  r!   r!   r"   is_optional  s
    r  c                 C   s    | t u rtdt| dd t u S )Nz_Attempted to use Future without a contained type. Please add a contained type, e.g. Future[int]r  )r   r   r   r	  r!   r!   r"   	is_future  s
    r  )RRef)PyRRefc                 C   s    | t u rtdt| dd t u S )Nz[Attempted to use RRef without a contained type. Please add a contained type, e.g. RRef[int]r  )r  r   r   r	  r!   r!   r"   is_rref  s
    r  c                 C   s
   t | tS r3   )r|   r  r   r!   r!   r"   is_rref_instance  s    r  c                 C   s   dS r   r!   r  r!   r!   r"   r    s    c                 C   s(   | j dv o&t| dd tu p&t| ttS )N>   rZ   typing_extensionsr  )rE   r   r   r|   typer	  r!   r!   r"   is_final  s    
r  c                   @   s   e Zd Zdd ZdS )BroadcastingListClsc                 C   s   d S r3   r!   )r=   typesr!   r!   r"   __getitem__  s    zBroadcastingListCls.__getitem__N)rD   rE   rF   r  r!   r!   r!   r"   r    s   r  r   ZBroadcastingListc                   C   s   dS )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!   r"   is_scripting  s    r   Tc                 C   s   t | dr| jS t| tjjr$| jS t| dd r8| j}nt| t	j
rL| j}ntd|dkr`d}| j}|dkrt| jS |d u rtd| dt|r|d	d
}|dd
}|r|dkrd}nd| }d|v rtd| d| d|d | S )N_jit_override_qualnamerD   z)Could not get name of python class objectz<lambda>Z_lambdaztorch._classesz(Could not get qualified name for class 'z': __module__ can't be None.<_>__main__Z	__torch__z
__torch__.r   z': 'z' is not a valid identifier)rY   r!  r|   rh   _CScriptFunctionr   r   rD   enumEnumrc   r   rE   package_manglingZ
is_mangledreplace)r   Zmangle_namerc   r   r!   r!   r"   r     s8    




r   c                 C   s   t | sd S t| S r3   )r   r   r   r   r!   r!   r"   _try_get_dispatched_fn  s    r,  c                    s   t  trt dsJ t dr8 fdd jD }ng }g }t d} jD ]H}|r| jv rtjj j| t	 }|
| qP|
tjj  qPt j j||fS )N_fields_field_defaultsc                    s    g | ]}| j v r j | qS r!   )r.  )rb   fieldr  r!   r"   rf   !  s   
z/_get_named_tuple_properties.<locals>.<listcomp>__annotations__)rl   r+   rY   r-  r0  rh   jitannotationsZann_to_typer   r*   r&  
TensorTypegetInferredr  rD   )r   defaultsr2  Zhas_annotationsr/  Zthe_typer!   r  r"   _get_named_tuple_properties  s    



r6  .)unqual_namefield_namesr5  c                 C   s8   t jdk r t||}||j_ntj|||d}||  S )N)r   r   r   )r5  )r   r   collections
namedtuple__new____defaults__)tr7  r8  r5  	TupleTyper!   r!   r"   _create_named_tuple1  s
    

r?  c                  c   s8   t j } t jd d  d V  t j| d | d  d S Nr   r   )rh   r&  _jit_get_emit_hooks_jit_set_emit_hooks)hooksr!   r!   r"   _disable_emit_hooks:  s    
rD  c                 C   s    d ddd}d ddd}d S )Nr#   c                 S   s   t j | _t jd d  d S r3   )rh   r&  rA  rC  rB  )r=   r!   r!   r"   	__enter__C  s    z0_disable_emit_hooks_decorator.<locals>.__enter__c                 W   s   t j| jd | jd  d S r@  )rh   r&  rB  rC  )r=   r   r!   r!   r"   r   G  s    z/_disable_emit_hooks_decorator.<locals>.__exit__r!   )Z_DecoratorContextManagerrE  r   r!   r!   r"   _disable_emit_hooks_decoratorB  s    rF  c                 C   s   t | sdS t| tS r   )rH   isclassrl   r0   r  r!   r!   r"   _is_exceptionJ  s    
rH  c                 C   s*   | dkrt dt d|  d|  dd S )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])r   target_typer!   r!   r"   r  O  s    r  c                 C   s   t | dd S )Nr  r   rI  r!   r!   r"   
get_origin]  s    rL  c                 C   s   t | dd S )Nr  rK  rI  r!   r!   r"   get_argsa  s    rM  c                 C   sj   | t u s| tu rtd nL| tu s*| tu r4td n2| tu sD| tu rNtd n| d u s^| tu rftd d S )Nr   r   r	   r   )r   rk   r  r   r+   r	   r  r   rI  r!   r!   r"   check_args_existe  s    


rN  c                 C   s&   | g ks| i ks| dkr"t d d S )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  r!   r!   r"   check_empty_containersp  s    rO  c                 C   s  t |}t| |tu s |tu r~t|  t| ts6dS t|d }t |}| D ]*}|rht||sx dS qNt||sN dS qNdS |tu s|t	u rt|  t| t	sdS t|d }t|d }| 
 D ]J\}}	t||s dS t |}
|
r t|	|s dS qt|	|s dS qdS |tu s*|tu rt|  t| tsBdS t|}t| t|kr`dS t| |D ]>\}}t |}|rt||s dS nt||sj dS qjdS |tu r| d u rdS t|}|D ]4}t |}|rt| |  S t| |r dS qdS )NFr   Tr   )rL  rN  rk   r   rO  r|   rM  container_checkerr	   r  rt   r   r+   r(   zipr   )r   rJ  origin_typearg_typeZ
arg_originelZkey_typeZval_typer>   valZ
val_originZ	arg_typesZel_typeZ	el_originZinner_typesr=  Zt_originr!   r!   r"   rP  {  sr    









rP  c                 C   sf   t |tjjr>t |ts td|D ]}t| |r$ dS q$dS t|}|rTt| |S t	| t | |S )NzPThe second argument to `torch.jit.isinstance` must be a type or a tuple of typesTF)
r|   r9  abc	Containerr+   r   _isinstancerL  rP  rN  )r   rJ  Zt_typerR  r!   r!   r"   rX    s    


rX  c                       s0   e Zd Zeej d fddZdd Z  ZS )_TensorExtractor)tensorsc                   s   t  j|i | || _d S r3   )superr   rZ  )r=   rZ  r   r   	__class__r!   r"   r     s    z_TensorExtractor.__init__c                 C   sf   t |tjr| j| dS t |tr*dS t |ts<t|r@dS t |tjj	rRdS t |t
jrbdS d S )Nr   )r|   rh   TensorrZ  r*   r   CFuturer  cudaEvent	threadingThread)r=   r   r!   r!   r"   persistent_id  s    
z_TensorExtractor.persistent_id)	rD   rE   rF   r   rh   r^  r   rd  __classcell__r!   r!   r\  r"   rY    s   rY  c                 C   s$   g }t t d|d}||  |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.
    )protocolrZ  )rY  ioBytesIOdump)r   rZ  Z	extractorr!   r!   r"   _extract_tensors  s    
rk  )r   )F)T)r   
contextlibr9  r(  rH   r}   weakrefr   textwrapr   rh   r   r;   rZ   rh  picklerb  Ztorch.distributed.rpctorch._Cr   r_  torch._sourcesr   r   r   Ztorch.futuresZtorch.package._manglingpackageZ	_manglingr*  r   r   r	   r
   r   r   r   r   r   r   r   r   r  r0  _threadr   ImportError_dummy_threadWeakKeyDictionaryr   r8   r7   rM   rX   r^   r   rq   r   rx   rz   r   r   r   rK   r   r   r   AbstractContextManagerr   r   r   r   r   rg   r   r   r   r   r   r   r   r   r   r   r   r  r  r  r  r  r  r  r  r  r  r  ZdistributedZrpcis_availabler  Ztorch._C._distributed_rpcr  r  r  r  r  BroadcastingList1r   r-   globalsr   r   r,  r6  r?  contextmanagerrD  rF  rH  r  rL  rM  rN  rO  rP  rX  PicklerrY  rk  r!   r!   r!   r"   <module>   s   0
@2:F..2
^ 

		C	
>