a
    àñhg¨  ã                   @   s0  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mZm	Z	 ddl
Z
ddlmZ ddlmZ ddlmZmZmZ ddlmZ ddl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  ddl!m"Z" ddlm#Z#m$Z$m%Z%m&Z& e"e
j'j(_)e"e
j'j*_)e
j'j*Z*de*_ ee*dƒ e�r4e +dddg¡Z,ndd„ Z,dd„ Z-dd„ Z.G dd„ de/ƒZ0G dd„ de0ƒZ1G dd„ de2ƒZ3G dd„ de/ƒZ4G d d!„ d!e5ƒZ6d"d#„ Z7G d$d%„ d%ƒZ8e�r G d&d'„ d'ee3eƒƒZ9G d(d)„ d)e9ƒZ:e:j; <¡ D ]L\Z=Z>e?e>ƒ�s
e@e>eAƒ�s
�qèe= Bd*¡�sèeCe9e=ƒ�r&�qèeDe9e=e>ƒ �qèd+d,„ ZEh d-£ZFd.d/„ ZGeEe
jHjƒD ]B\Z=ZIe= Bd*¡�rr�qZe=e:j;v�rZe=eFv�rZeDe:eIjJeGe=ƒƒ �qZn$G d0d'„ d'e
jHjƒZ9G d1d)„ d)e9ƒZ:dFd2d3„ZKd4d5„ ZLd6d7„ ZMd8d9„ ZNd:d;„ ZOd<d=„ ZPd>d?„ ZQG d@dA„ dAe/ƒZRdBdC„ ZSeeSdDƒ eejTdEƒ dS )GzßTorchScript

This module contains functionality to support the JIT's scripting frontend, notably:
    - torch.jit.script

This is not intended to be imported directly; please use the exposed
functionalities in `torch.jit`.
é    N)ÚAnyÚDict)Ú
set_module)ÚScriptMethodStubÚwrap_cpp_moduleÚinfer_methods_to_compile)ÚModule)Ú_enabled)Ú_register_builtin)Úwith_metaclassÚget_function_from_type)Úget_jit_defÚget_default_argsÚget_jit_class_def)Ú_qualified_name)Ú
_graph_for)Ú_try_get_jit_cached_functionÚ_try_get_jit_cached_overloadsÚ_set_jit_function_cacheÚ_set_jit_overload_cachez†
Functionally equivalent to a :class:`ScriptModule`, but represents a single
function and does not have any attributes or Parameters.
z	torch.jitÚ	AttributeÚvalueÚtypec                 C   s   | S ©N© )r   r   r   r   úQ/home/yuhw/wc/uboone-dl-vtx/venv/lib/python3.9/site-packages/torch/jit/_script.pyr   2   s    c                 C   s$   t | dƒr dt| ƒv pt | dƒS d S )NÚ	__class__Ú__dict__Ú	__slots__)ÚhasattrÚdir©Úclsr   r   r   Ú_is_new_style_class8   s    
r#   c                 C   s@   t | | jƒ}tjj | ¡}tj ||||¡ tjj 	| |¡ d S r   )
r   Ú__name__ÚtorchÚjitÚfrontendZget_default_args_for_classÚ_CZ_jit_script_class_compileÚ_stateZ_add_script_class)ÚobjÚrcbÚqualified_nameÚastÚdefaultsr   r   r   Ú_compile_and_register_class=   s    r/   c                   @   sT   e Zd Zdd„ Zdd„ Zdd„ Zdd„ Zd	d
„ Zdd„ Zdd„ Z	dd„ Z
dd„ ZdS )ÚOrderedDictWrapperc                 C   s
   || _ d S r   )Ú_c)Úselfr1   r   r   r   Ú__init__T   s    zOrderedDictWrapper.__init__c                 C   s   dd„ |   ¡ D ƒS )Nc                 S   s   g | ]\}}|‘qS r   r   ©Ú.0ÚkÚvr   r   r   Ú
<listcomp>X   ó    z+OrderedDictWrapper.keys.<locals>.<listcomp>©Úitems©r2   r   r   r   ÚkeysW   s    zOrderedDictWrapper.keysc                 C   s   dd„ |   ¡ D ƒS )Nc                 S   s   g | ]\}}|‘qS r   r   r4   r   r   r   r8   [   r9   z-OrderedDictWrapper.values.<locals>.<listcomp>r:   r<   r   r   r   ÚvaluesZ   s    zOrderedDictWrapper.valuesc                 C   s   t |  ¡ ƒS r   )Úlenr>   r<   r   r   r   Ú__len__]   s    zOrderedDictWrapper.__len__c                 C   s   t dƒ‚d S )Nz6cannot delete methods or parameters of a script module©ÚRuntimeError©r2   r6   r   r   r   Ú__delitem__`   s    zOrderedDictWrapper.__delitem__c                 C   s
   | j  ¡ S r   )r1   r;   r<   r   r   r   r;   c   s    zOrderedDictWrapper.itemsc                 C   s(   || vrt d |¡ƒ‚| j ||¡ d S )NzKCan't add a new parameter after ScriptModule construction. Tried to add '{})rB   Úformatr1   Úsetattr©r2   r6   r7   r   r   r   Ú__setitem__f   s    ÿÿzOrderedDictWrapper.__setitem__c                 C   s   | j  |¡S r   )r1   ÚcontainsrC   r   r   r   Ú__contains__n   s    zOrderedDictWrapper.__contains__c                 C   s   || vrt |ƒ‚| j |¡S r   )ÚKeyErrorr1   ÚgetattrrC   r   r   r   Ú__getitem__q   s    zOrderedDictWrapper.__getitem__N)r$   Ú
__module__Ú__qualname__r3   r=   r>   r@   rD   r;   rH   rJ   rM   r   r   r   r   r0   S   s   r0   c                       s<   e Zd Z‡ fdd„Zdd„ Zdd„ Zdd„ Zd	d
„ Z‡  ZS )ÚOrderedModuleDictc                    s"   t t| ƒ tj |¡¡ || _d S r   )ÚsuperrP   r3   r%   r(   Ú
ModuleDictÚ_python_modules)r2   ÚmoduleZpython_dict©r   r   r   r3   x   s    zOrderedModuleDict.__init__c                 C   s   | j  ¡ }|S r   )rS   r;   ©r2   Úrr   r   r   r;   ‚   s    
zOrderedModuleDict.itemsc                 C   s
   || j v S r   ©rS   rC   r   r   r   rJ   †   s    zOrderedModuleDict.__contains__c                 C   s8   t |tƒr$| j ||¡ || j|< ntd ||¡ƒ‚d S )NznCannot re-assign modules in a ScriptModule with non-scripted module, tried to replace existing module '{}': {})Ú
isinstanceÚScriptModuler1   rF   rS   rB   rE   rG   r   r   r   rH   ‰   s    

ÿÿzOrderedModuleDict.__setitem__c                 C   s
   | j | S r   rX   rC   r   r   r   rM   œ   s    zOrderedModuleDict.__getitem__)	r$   rN   rO   r3   r;   rJ   rH   rM   Ú__classcell__r   r   rU   r   rP   w   s
   
rP   c                       s   e Zd Z‡ fdd„Z‡  ZS )Ú
ScriptMetac           	         s   i ˆ _ ttˆ ddƒƒˆ _t|ƒD ]D}t|di ƒ ¡ D ]\}}|ˆ j |< q4t|dtƒ ƒ}ˆ j |¡ˆ _q t| ¡ ƒD ]*\}}t|t	ƒrrt
ˆ |ƒ |ˆ j |jj< qrtˆ ddƒr¾ttˆ ƒ |||¡S tˆ ddd	„ ƒ‰t ˆ¡‡ ‡fd
d„ƒ}|ˆ _ttˆ ƒ |||¡S )NZ__constants__r   Ú_methodsÚ_constants_setÚ_disable_script_metaFr3   c                 S   s   d S r   r   r<   r   r   r   Ú<lambda>¿   r9   z%ScriptMeta.__init__.<locals>.<lambda>c           	         s²   t ˆ jƒ}ˆ| g|¢R i |¤Ž t ˆ jƒ|k}t| ƒˆ kr®dd„ }tjjj| || d�| jd< | jj	}| 
¡ D ]}t| |ƒ qn| ¡ D ]\}}t| |ƒ q†dD ]}t| |ƒ qžd S )Nc                 S   s6   t | ƒ}t|dƒr*dd„ t|j ¡ ƒD ƒS t| ƒS d S )Nr]   c                 S   s   g | ]\}}|‘qS r   r   r4   r   r   r   r8   Ì   r9   zUScriptMeta.__init__.<locals>.init_then_script.<locals>.make_stubs.<locals>.<listcomp>)r   r   Úsortedr]   r;   r   )rT   r"   r   r   r   Ú
make_stubsÉ   s    
zAScriptMeta.__init__.<locals>.init_then_script.<locals>.make_stubs)Zshare_typesÚ_actual_script_module)Ú_parametersÚ_buffersÚ_modules)r?   r]   r   r%   r&   Ú
_recursiveÚcreate_script_moduler   rc   Ú_concrete_typeZget_attributesÚdelattrZget_modules)	r2   ÚargsÚkwargsZnum_methodsZadded_methods_in_initrb   Zconcrete_typeÚnameÚ_©r"   Zoriginal_initr   r   Úinit_then_scriptÁ   s     
	þÿz-ScriptMeta.__init__.<locals>.init_then_script)r]   ÚsetrL   r^   Úreversedr;   Úunionra   rY   r   rj   Zoriginal_methodr$   rQ   r\   r3   Ú	functoolsÚwraps)	r"   rm   ÚbasesÚattrsÚbaser6   r7   Zbase_constantsrp   rU   ro   r   r3   ©   s$    

zScriptMeta.__init__©r$   rN   rO   r3   r[   r   r   rU   r   r\   ¨   s   r\   c                   @   s   e Zd Zdd„ ZdS )Ú_CachedForwardc                 C   s
   |   d¡S )NÚforward)Ú__getattr__)r2   r*   r"   r   r   r   Ú__get__ä   s    z_CachedForward.__get__N)r$   rN   rO   r}   r   r   r   r   rz   ã   s   rz   c                   @   s   e Zd ZdS )ÚScriptWarningN)r$   rN   rO   r   r   r   r   r~   è   s   r~   c                 C   s0   t s| S tjdd�}t| | jdd�}t||| ƒS )Né   ©Z	frames_uprZ   )Z	self_name)r	   Ú_jit_internalÚ!createResolutionCallbackFromFramer   r$   r   )ÚfnÚ_rcbr-   r   r   r   Úscript_methodì   s
    r…   c                   @   s   e Zd Zdd„ Zdd„ ZdS )ÚConstMapc                 C   s
   || _ d S r   ©Úconst_mapping)r2   rˆ   r   r   r   r3     s    zConstMap.__init__c                 C   s
   | j | S r   r‡   ©r2   Úattrr   r   r   r|     s    zConstMap.__getattr__N)r$   rN   rO   r3   r|   r   r   r   r   r†      s   r†   c                       sV   e Zd ZdZg d¢Z‡ fdd„Zeƒ Z‡ fdd„Z‡ fdd„Z	d	d
„ Z
dd„ Z‡  ZS )rZ   zÝ
        ``ScriptModule``s wrap a C++ ``torch::jit::Module``. ``ScriptModule``s
        contain methods, attributes, parameters, and
        constants. These can be accessed the same as on a normal ``nn.Module``.
        )ÚcodeÚcode_with_constantsÚgraphÚinlined_graphÚoriginal_namec                    s   t t| ƒ ¡  d S r   )rQ   rZ   r3   r<   rU   r   r   r3     s    úScriptModule.__init__c                    s&   d| j vrtt| ƒ |¡S t| j|ƒS )Nrc   )r   rQ   rZ   r|   rL   rc   r‰   rU   r   r   r|     s    
zScriptModule.__getattr__c                    s^   d| j vrLt|tƒr:d| jj vr(i | j_|j| j|< |j}tt| ƒ 	||¡S t
| j||ƒ d S )Nrc   Ú__annotations__)r   rY   r   r   r‘   r   r   rQ   rZ   Ú__setattr__rF   rc   ©r2   rŠ   r   rU   r   r   r’   #  s    

zScriptModule.__setattr__c                 C   sJ   d| j v r| j |¡S tjdd�}tj |¡}t||d ƒ| j	| 
¡ j
< d S )Nrc   é   r€   )r   rc   Údefiner�   r‚   r%   r(   Z_parse_source_defr   r]   rm   )r2   Úsrcr+   r-   r   r   r   r•   7  s
    
zScriptModule.definec                 C   s
   | j  ¡ S r   )rc   Ú_replicate_for_data_parallelr<   r   r   r   r—   M  s    z)ScriptModule._replicate_for_data_parallel)r$   rN   rO   Ú__doc__Z__jit_unused_properties__r3   rz   r{   r|   r’   r•   r—   r[   r   r   rU   r   rZ     s   rZ   c                       s4  e Zd ZdZdZ‡ fdd„Zedd„ ƒZedd„ ƒZd	d
„ Z	e
dd„ ƒZe
dd„ ƒZe
dd„ ƒZe
dd„ ƒZdd„ Zdd„ Zdd„ Zdd„ Zdd„ Zdd„ Zdd „ Ze
d!d"„ ƒZd#d$„ Z‡ fd%d&„Z‡ fd'd(„Zd)d*„ Zd+d,„ Zd-d.„ Zd/d0„ Zd1d2„ Zd3d4„ Zd5d6„ Z d7d8„ Z!‡ fd9d:„Z"d;d<„ Z#d=d>„ Z$‡  Z%S )?ÚRecursiveScriptModulea$  
        The core data structure in TorchScript is the ``ScriptModule``. It is an
        analogue of torch's ``nn.Module`` and represents an entire model as a tree of
        submodules. Like normal modules, each individual module in a ``ScriptModule`` can
        have submodules, parameters, and methods. In ``nn.Module``\s methods are implemented
        as Python functions, but in ``ScriptModule``\s methods are implemented as
        TorchScript functions,  a statically-typed subset of Python that contains all
        of PyTorch's built-in Tensor operations. This difference allows your
        ``ScriptModule``\s code to run without the need for a Python interpreter.

        ``ScriptModule``\s should not be created manually, instead use
        either :func:`tracing <torch.jit.trace>` or :func:`scripting <torch.jit.script>`.
        Tracing and scripting can be applied incrementally and :ref:`composed as necessary <Types>`.

        * Tracing records the tensor operations as executed with a set of example inputs and uses these
          operations to construct a computation graph. You can use the full dynamic behavior of Python with tracing,
          but values other than Tensors and control flow aren't captured in the graph.

        * Scripting inspects the Python code of the model
          and compiles it to TorchScript. Scripting allows the use of many `types`_ of values and supports dynamic control flow.
          Many, but not all features of Python are supported by the compiler, so changes to the source code may be necessary.
        Tc                    s,   d| j d< || _tt| ƒ ¡  t| dƒ d S )NTÚ_initializingZtraining)r   r1   rQ   r™   r3   rj   )r2   Ú
cpp_modulerU   r   r   r3   l  s    
úRecursiveScriptModule.__init__c                 C   s   t | ƒ}||ƒ t  |¡ |S )a‰  
            Construct a RecursiveScriptModule that's ready for use. PyTorch
            code should use this to construct a RecursiveScriptModule instead
            of instead of calling `__init__` directly, as it makes sure the
            object is properly finalized (and in the future we may take
            control of how the RecursiveScriptModule instance is created).

            Arguments:
                cpp_module:  The C++ Module that will hold the actual state of
                             this RecursiveScriptModule instance.
                init_fn:  Lambda that initializes the RecursiveScriptModule passed to it.
            )r™   Ú_finalize_scriptmodule)r›   Úinit_fnÚscript_moduler   r   r   Ú
_constructu  s    
z RecursiveScriptModule._constructc                 C   sB   t tj | j¡ƒ| _t tj | j¡ƒ| _t| j| j	ƒ| _	d| _
d S )NF)r0   r%   r(   ÚParameterDictr1   rd   Ú
BufferDictre   rP   rf   rš   ©rŸ   r   r   r   r�   ‹  s    ÿÿÿz,RecursiveScriptModule._finalize_scriptmodulec                 C   s¦   |   |¡ tjj | j ¡ ¡| _i }tj | j¡ 	¡ D ]\}}t
|ƒ||< q6t| j|ƒ| _ttj | j¡ƒ| _ttj | j¡ƒ| _dd„ | j 	¡ D ƒ| _d| jd< dS )zé
            Re-construct an instance of RecursiveScriptModule using an instance of a C++ module.

            Arguments:
                cpp_module: The C++ module that this RecursiveScriptModule will be rebuilt around.
            c                 S   s$   i | ]\}}t |tjjƒs||“qS r   )rY   r%   r(   ÚScriptMethodr4   r   r   r   Ú
<dictcomp>±  s   þz6RecursiveScriptModule._reconstruct.<locals>.<dictcomp>Frš   N)r3   r%   r(   ZConcreteModuleTypeZfrom_jit_typer1   Ú_typeri   rR   r;   r   rP   rf   r0   r¡   rd   r¢   re   r   )r2   r›   Úmodulesrm   r   r   r   Ú_reconstruct˜  s    
ÿþz"RecursiveScriptModule._reconstructc                 C   s   | j jS )z£
            Returns a string representation of the internal graph for the
            ``forward`` method. See :ref:`interpreting-graphs` for details.
            )r{   r�   r<   r   r   r   r�   ¸  s    zRecursiveScriptModule.graphc                 C   s   | j jS )zø
            Returns a string representation of the internal graph for the
            ``forward`` method. This graph will be preprocessed to inline all function and method calls.
            See :ref:`interpreting-graphs` for details.
            )r{   rŽ   r<   r   r   r   rŽ   À  s    z#RecursiveScriptModule.inlined_graphc                 C   s   | j jS )zÌ
            Returns a pretty-printed representation (as valid Python syntax) of
            the internal graph for the ``forward`` method. See
            :ref:`inspecting-code` for details.
            )r{   r‹   r<   r   r   r   r‹   É  s    zRecursiveScriptModule.codec                 C   s   | j j}|d t|d ƒfS )a   
            Returns a tuple of:

            [0] a pretty-printed representation (as valid Python syntax) of
            the internal graph for the ``forward`` method. See `code`.
            [1] a ConstMap following the CONSTANT.cN format of the output in [0].
            The indices in the [0] output are keys to the underlying constant's values.

            See :ref:`inspecting-code` for details.
            r   r”   )r{   rŒ   r†   rV   r   r   r   rŒ   Ò  s    z)RecursiveScriptModule.code_with_constantsc                 O   s   | j j|i |¤ŽS )zx
            save(f, _extra_files={})

            See :func:`torch.jit.save <torch.jit.save>` for details.
            )r1   Úsave©r2   rk   rl   r   r   r   r©   á  s    zRecursiveScriptModule.savec                 O   s   | j j|i |¤ŽS )a  
            _save_for_lite_interpreter(f)

            Add (or update) the bytecode session to the script model. The updated model is used
            in lite interpreter for mobile applications.

            Arguments:
                f: a string containing a file name.
                _extra_files: Map from filename to contents which will be stored as part of 'f'.

            )r1   Z_save_for_mobilerª   r   r   r   Ú_save_for_lite_interpreteré  s    z0RecursiveScriptModule._save_for_lite_interpreterc                 O   s   | j j|i |¤ŽS r   )r1   Z_save_to_buffer_for_mobilerª   r   r   r   Ú$_save_to_buffer_for_lite_interpreter÷  s    z:RecursiveScriptModule._save_to_buffer_for_lite_interpreterc                 O   s   | j j|i |¤ŽS r   )r1   Úsave_to_bufferrª   r   r   r   r­   ú  s    z$RecursiveScriptModule.save_to_bufferc                 O   s
   | j  ¡ S r   )r1   Úget_debug_staterª   r   r   r   r®   ý  s    z%RecursiveScriptModule.get_debug_statec                 C   s   d  | j¡S )Nzoriginal_name={})rE   r�   r<   r   r   r   Ú
extra_repr   s    z RecursiveScriptModule.extra_reprc                 O   s   | j j|i |¤ŽS r   )r{   Ú	graph_forrª   r   r   r   r°     s    zRecursiveScriptModule.graph_forc                 C   s0   t | ƒt| j ¡  ¡ ƒkrdS t| j ¡  ¡ ƒS )NÚ )r   Ústrr1   r¦   rm   r<   r   r   r   r�     s    z#RecursiveScriptModule.original_namec                 C   s"   t jdd�}| j | j||¡ d S )Nr”   r€   )r�   r‚   r1   Z_defineri   )r2   r–   r+   r   r   r   r•     s    	zRecursiveScriptModule.definec                    sŠ   d| j vrtdƒ‚| jr(tt| ƒ |¡S || jv r<| j| S | j |¡rT| j 	|¡S | j 
|¡rz| j |¡}|| j |< |S tt| ƒ |¡S )Nrš   zKScriptModule has not been initialized, did you forget to call super's init?)r   rB   rš   rQ   r™   r|   rf   r1   r   rL   Z_has_methodZ_get_method)r2   rŠ   r…   rU   r   r   r|     s    
ÿ


z!RecursiveScriptModule.__getattr__c                    sŽ   | j rtt| ƒ ||¡S || jv r.|| j|< n\| j |¡rJ| j ||¡ n@t| dƒrx|| j 	¡  
¡ v rxtd ||¡ƒ‚ntt| ƒ ||¡S d S )Nri   z;Cannot mutate TorchScript constant value: '{}'. Value: '{}')rš   rQ   r™   r’   rf   r1   r   rF   ri   Zget_constantsr=   ÚAttributeErrorrE   r“   rU   r   r   r’   0  s     
ÿþÿÿz!RecursiveScriptModule.__setattr__c                 C   s   t  d¡‚d S )NzáScriptModules cannot be deepcopied using copy.deepcopy or saved using torch.save. Mixed serialization of script and non-script modules is not supported. For purely script modules use my_script_module.save(<filename>) instead.)ÚpickleÚPickleErrorr<   r   r   r   Ú__getstate__M  s    ÿz"RecursiveScriptModule.__getstate__c                 C   s   t jj t | j¡¡S r   )r%   r&   rg   r   Úcopyr1   r<   r   r   r   Ú__copy__T  s    zRecursiveScriptModule.__copy__c                 C   s   t jj t | j|¡¡S r   )r%   r&   rg   r   r·   Údeepcopyr1   )r2   Úmemor   r   r   Ú__deepcopy__W  s    z"RecursiveScriptModule.__deepcopy__c                 O   s4   t | |ƒ}t |dd ƒt t|ƒkr&tƒ ‚||i |¤ŽS )NÚ__func__)rL   r™   ÚNotImplementedError)r2   Úmethod_namerk   rl   Úself_methodr   r   r   Úforward_magic_method^  s    
ÿz*RecursiveScriptModule.forward_magic_methodc                 C   s
   |   d¡S )NÚ__iter__©rÀ   r<   r   r   r   rÁ   f  s    zRecursiveScriptModule.__iter__c                 C   s   |   d|¡S )NrM   rÂ   )r2   Úidxr   r   r   rM   i  s    z!RecursiveScriptModule.__getitem__c                 C   s
   |   d¡S )Nr@   rÂ   r<   r   r   r   r@   l  s    zRecursiveScriptModule.__len__c                 C   s   |   d|¡S )NrJ   rÂ   )r2   Úkeyr   r   r   rJ   o  s    z"RecursiveScriptModule.__contains__c                    s*   | j }|jttdƒkr$tt| ƒ  ¡ S |ƒ S )NÚ__dir__)rÅ   r¼   r   r™   rQ   ©r2   r¿   rU   r   r   rÅ   t  s    ÿzRecursiveScriptModule.__dir__c                 C   s    | j }|jttdƒkrdS |ƒ S )NÚ__bool__T)rÇ   r¼   r   r™   rÆ   r   r   r   rÇ     s    ÿzRecursiveScriptModule.__bool__c                 C   s   dd„ }t  | j ¡ |¡S )Nc                 S   s   d S r   r   r£   r   r   r   rž   Š  s    zCRecursiveScriptModule._replicate_for_data_parallel.<locals>.init_fn)r™   r    r1   r—   )r2   rž   r   r   r   r—   ‡  s    
ÿz2RecursiveScriptModule._replicate_for_data_parallel)&r$   rN   rO   r˜   r_   r3   Ústaticmethodr    r�   r¨   Úpropertyr�   rŽ   r‹   rŒ   r©   r«   r¬   r­   r®   r¯   r°   r�   r•   r|   r’   r¶   r¸   r»   rÀ   rÁ   rM   r@   rJ   rÅ   rÇ   r—   r[   r   r   rU   r   r™   P  sN   	

 




r™   Ú__c                    s   dd l ‰ ˆ j| ‡ fdd„d�S )Nr   c                    s   ˆ   | ¡pˆ  | ¡S r   )Ú
isfunctionÚismethod©Úx©Úinspectr   r   r`   ¦  r9   z_get_methods.<locals>.<lambda>)Ú	predicate)rÐ   Ú
getmembersr!   r   rÏ   r   Ú_get_methods¡  s    ÿrÓ   >"   Z	_get_namer§   ÚbuffersZ
state_dictr   ZtrainZ_load_from_state_dictZnamed_parametersZ_slow_forwardZnamed_modulesZhalfZshare_memoryZ_tracing_nameÚ_applyÚapplyZcudaÚdoubler{   Z	zero_gradZload_state_dictZ_named_membersZ
add_moduleÚchildrenr¯   ÚevalZregister_bufferZnamed_buffersZ_save_to_state_dictZregister_parameterÚfloatÚtoZnamed_childrenÚ
parametersÚcpuc                    s   ‡ fdd„}|S )Nc                    s   t ˆ d ƒ‚d S )Nz" is not supported on ScriptModulesrA   rª   ©rm   r   r   ÚfailÏ  s    z_make_fail.<locals>.failr   )rm   rß   r   rÞ   r   Ú
_make_failÎ  s    rà   c                       s   e Zd Zd‡ fdd„	Z‡  ZS )rZ   Nc                    s   t ƒ  ¡  d S r   ©rQ   r3   ©r2   ÚargrU   r   r   r3   á  s    r�   )Nry   r   r   rU   r   rZ   à  s   c                       s   e Zd Zd‡ fdd„	Z‡  ZS )r™   Nc                    s   t ƒ  ¡  d S r   rá   râ   rU   r   r   r3   å  s    rœ   )Nry   r   r   rU   r   r™   ä  s   c                 C   sJ  t s| S |durt d¡ t| tƒr(| S t| tjjƒrLtjj	 
| tjj	j¡S t| ƒ}t | ¡rÈt| tjjƒrztd | ¡ƒ‚t| ƒsŠtdƒ‚t|  ¡ ƒdkr¢tdƒ‚|du r¸t |d ¡}t| ||ƒ | S t| dƒrâ| j} t | ¡}t| ƒ t| ƒ}|rú|S t| | jƒ}|du �rt | ¡}tj  |||t!| ƒ¡}| j"|_"t#| |ƒ |S dS )	au  
    Scripting a function or ``nn.Module`` will inspect the source code, compile
    it as TorchScript code using the TorchScript compiler, and return a :class:`ScriptModule` or
    :class:`ScriptFunction`. TorchScript itself is a subset of the Python language, so not all
    features in Python work, but we provide enough functionality to compute on
    tensors and do control-dependent operations. For a complete guide, see the
    :ref:`language-reference`.

    ``torch.jit.script`` can be used as a function for modules and functions, and as a decorator
    ``@torch.jit.script`` for :ref:`torchscript-classes` and functions.

    Arguments:
        obj (callable, class, or ``nn.Module``):  The ``nn.Module``, function, or class type to
                                                  compile.

    Returns:
        If ``obj`` is ``nn.Module``, ``script`` returns
        a :class:`ScriptModule` object. The returned :class:`ScriptModule` will
        have the same set of sub-modules and parameters as the
        original ``nn.Module``. If ``obj`` is a standalone function,
        a :class:`ScriptFunction` will be returned.

    **Scripting a function**
        The ``@torch.jit.script`` decorator will construct a :class:`ScriptFunction`
        by compiling the body of the function.

        Example (scripting a function):

        .. testcode::

            import torch

            @torch.jit.script
            def foo(x, y):
                if x.max() > y.max():
                    r = x
                else:
                    r = y
                return r

            print(type(foo))  # torch.jit.ScriptFuncion

            # See the compiled graph as Python code
            print(foo.code)

            # Call the function using the TorchScript interpreter
            foo(torch.ones(2, 2), torch.ones(2, 2))

        .. testoutput::
            :hide:

            ...

    **Scripting an nn.Module**
        Scripting an ``nn.Module`` by default will compile the ``forward`` method and recursively
        compile any methods, submodules, and functions called by ``forward``. If a ``nn.Module`` only uses
        features supported in TorchScript, no changes to the original module code should be necessary. ``script``
        will construct :class:`ScriptModule` that has copies of the attributes, parameters, and methods of
        the original module.

        Example (scripting a simple module with a Parameter):

        .. testcode::

            import torch

            class MyModule(torch.nn.Module):
                def __init__(self, N, M):
                    super(MyModule, self).__init__()
                    # This parameter will be copied to the new ScriptModule
                    self.weight = torch.nn.Parameter(torch.rand(N, M))

                    # When this submodule is used, it will be compiled
                    self.linear = torch.nn.Linear(N, M)

                def forward(self, input):
                    output = self.weight.mv(input)

                    # This calls the `forward` method of the `nn.Linear` module, which will
                    # cause the `self.linear` submodule to be compiled to a `ScriptModule` here
                    output = self.linear(output)
                    return output

            scripted_module = torch.jit.script(MyModule(2, 3))

        Example (scripting a module with traced submodules):

        .. testcode::

            import torch
            import torch.nn as nn
            import torch.nn.functional as F

            class MyModule(nn.Module):
                def __init__(self):
                    super(MyModule, self).__init__()
                    # torch.jit.trace produces a ScriptModule's conv1 and conv2
                    self.conv1 = torch.jit.trace(nn.Conv2d(1, 20, 5), torch.rand(1, 1, 16, 16))
                    self.conv2 = torch.jit.trace(nn.Conv2d(20, 20, 5), torch.rand(1, 20, 16, 16))

                def forward(self, input):
                    input = F.relu(self.conv1(input))
                    input = F.relu(self.conv2(input))
                    return input

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

        To compile a method other than ``forward`` (and recursively compile anything it calls), add
        the :func:`@torch.jit.export <torch.jit.export>` decorator to the method. To opt out of compilation
        use :func:`@torch.jit.ignore <torch.jit.ignore>` or :func:`@torch.jit.unused <torch.jit.unused>`.

        Example (an exported and ignored method in a module)::

            import torch
            import torch.nn as nn

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

                @torch.jit.export
                def some_entry_point(self, input):
                    return input + 10

                @torch.jit.ignore
                def python_only_fn(self, input):
                    # This function won't be compiled, so any
                    # Python APIs can be used
                    import pdb
                    pdb.set_trace()

                def forward(self, input):
                    if self.training:
                        self.python_only_fn(input)
                    return input * 99

            scripted_module = torch.jit.script(MyModule())
            print(scripted_module.some_entry_point(torch.randn(2, 2)))
            print(scripted_module(torch.randn(2, 2)))
    Nz]`optimize` is deprecated and has no effect. Use `with torch.jit.optimized_execution() insteadzWType '{}' cannot be compiled since it inherits from nn.Module, pass an instance insteadzLTorchScript classes must be new-style classes. Please inherit from 'object'.r   z\TorchScript classes does not support inheritance yet. Please directly inherit from 'object'.r”   Z__script_if_tracing_wrapper)$r	   ÚwarningsÚwarnrY   rZ   r%   Únnr   r&   rg   rh   r   r   rÐ   ÚisclassÚ
issubclassrB   rE   r#   r?   Úmror�   r‚   r/   r   Z__original_fnÚ#createResolutionCallbackFromClosureÚ"_check_directly_compile_overloadedr   r   r$   r(   Z_jit_script_compiler   r˜   r   )r*   ÚoptimizeÚ
_frames_upr„   r,   Zmaybe_already_compiled_fnr-   rƒ   r   r   r   Úscripté  sb     ÿ

ÿ
þÿÿÿ



ÿ
rî   c                 C   sB   |  ¡ D ]4\}}|| vs$| | |krtjj |dj|d�¡‚qd S )NzŸDefault parameters on overloads do not affect the runtime so they must equal to the default parameter on the implementation function. Found on parameter {name}rÞ   )r;   r%   r&   r'   ZFrontendErrorrE   )Zimpl_defaultsÚoverload_defaultsÚlocrm   Zoverload_valuer   r   r   Ú_check_overload_defaults¸  s    þþrñ   c           
      C   sz   t | | jƒ ¡ }tjj | d d t | ¡¡}t ||jƒ}t	| ƒ}t	|ƒ}t
 |¡}t||| ¡ ƒ tj ||||||¡}	|	S r   )r   r$   Údeclr%   r&   ÚannotationsZget_signaturerÐ   rÌ   r   r�   rê   rñ   Úranger(   Z_jit_script_compile_overload)
Úoverload_fnÚ	qual_nameZimpl_fnZoverload_declZoverload_signatureZimpl_astrï   Zimplementation_defaultsr„   rƒ   r   r   r   Ú_compile_function_with_overloadÃ  s(    ÿ

ÿúr÷   c                 C   sj   t | ƒ}t| ƒ}t |¡}|d u r&|S g }|D ]}| t||| ƒ¡ q.|rR|| }t| |ƒ t |¡ |S r   )r   r   r�   Ú_get_fn_overloadsÚappendr÷   r   Z_clear_fn_overloads)r*   Zexisting_compiled_fnsrö   Zuncompiled_overloadsZcompiled_fnsrõ   r   r   r   Ú_get_overloadsÚ  s    

ÿ

rú   c                 C   s,   t | ƒ}t |¡st| ƒr(td |¡ƒ‚d S )Nz£Function {} cannot be directly compiled because it is overloaded. It must be used in a context of a function where its inputs can determine which overload to call.)r   r�   rø   r   rB   rE   )r*   rö   r   r   r   rë   ñ  s    þÿrë   c                 C   s–   t  | ¡stdƒ‚t| ƒs"tdƒ‚t| tjjƒo>t|  	¡ ƒdk}|s\t|  	¡ ƒdkr\tdƒ‚t
| ƒ}t d¡}t| | jƒ}tj ||||¡ d| _| S )Nz$interface must be applied to a classz1TorchScript interfaces must inherit from 'object'é   r   zmTorchScript interface does not support inheritance yet. Please directly inherit from 'object' or 'nn.Module'.r”   T)rÐ   rç   rB   r#   rè   r%   ræ   r   r?   ré   r   r�   r‚   r   r$   r(   Z_jit_script_interface_compileZ__torch_script_interface__)r*   Zis_module_interfacer,   r+   r-   r   r   r   Ú	interfaceû  s"    
ÿ
ÿrü   c                 C   s0   t | ƒ}tj ||¡}t | ¡}t| ||ƒ d S r   )r   r%   r(   Z	CallStackr�   Z'createResolutionCallbackForClassMethodsr/   )r*   rð   Z
_qual_nameZerror_stackr+   r   r   r   Ú_recursive_compile_class  s    
rý   c                   @   s(   e Zd Zd	dd„Zd
dd„Zdd„ ZdS )ÚCompilationUnitNr   c                 C   s*   t j ¡ | _|d ur&| j||d d� d S )Nr”   )rí   )r%   r(   rþ   r1   r•   )r2   Úlangrí   r   r   r   r3   $  s    zCompilationUnit.__init__c                 C   s$   |st  |d ¡}| j ||¡ d S )Nr”   )r�   r‚   r1   r•   )r2   rÿ   r+   rí   r   r   r   r•   )  s    zCompilationUnit.definec                 C   s&   | j  |¡}|d u r"td |¡ƒ‚|S )Nz''CompilationUnit' has no attribute '{}')r1   Zfind_functionr³   rE   )r2   rŠ   rW   r   r   r   r|   .  s    zCompilationUnit.__getattr__)Nr   )Nr   )r$   rN   rO   r3   r•   r|   r   r   r   r   rþ   #  s   

rþ   c                 C   s   | d usJ dƒ‚| S )NzUnwrapping null optionalr   rÍ   r   r   r   Ú_unwrap_optional5  s    r   zaten::_unwrap_optionalzaten::is_scripting)Nr   N)Ur˜   rt   ÚcollectionsrÐ   r·   r´   rä   Útypingr   r   r%   Ztorch._jit_internalr�   Ztorch.utilsr   Ztorch.jit._recursiver   r   r   Ztorch.nnr   Ztorch.jit._stater	   Ztorch.jit._builtinsr
   Z
torch._sixr   r   Ztorch.jit.frontendr   r   r   r   Ztorch.jit._fuserr   r   r   r   r   r(   r¤   r°   ZScriptFunctionÚ
namedtupler   r#   r/   Úobjectr0   rP   r   r\   rz   ÚWarningr~   r…   r†   rZ   r™   r   r;   rm   ÚitemÚcallablerY   rÉ   Ú
startswithr   rF   rÓ   Z_compiled_methods_allowlistrà   ræ   Úmethodr$   rî   rñ   r÷   rú   rë   rü   rý   rþ   r   Zis_scriptingr   r   r   r   Ú<module>   s�   


$1;	?  I%ÿþ
 P
	
