a
    –¥»a™í  ã                   @   s¬  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	m
Z
mZmZ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mZ ddlmZ ddlmZ ddlmZ dd	lm Z  dd
l!m"Z"m#Z#m$Z$ ddlm%Z% ddl&m'Z' ddlm(Z(m)Z)m*Z*m+Z+ ddl,m-Z-m.Z.m/Z/ ddl0m1Z1m2Z2 ddl3m4Z4 ddl5m6Z6m7Z7m8Z8 ddl9m:Z: e8ƒ a;e'ej<j=_>e'ej<j?_>ej<j?Z?de?_ ee?dƒ e�r¢e @dddg¡ZAndd„ ZAdeA_ dd„ ZBdd„ ZCdd „ ZDG d!d"„ d"eEƒZFG d#d$„ d$eFƒZGG d%d&„ d&eHƒZIG d'd(„ d(eEƒZJG d)d*„ d*eKƒZLd+d,„ ZMG d-d.„ d.ƒZNe2eOejPjd/œd0d1„ZQe�rjg d2¢ZRG d3d4„ d4eEƒZSeRD ]ZTd5d6„ ZUeVeSeTeUƒ �qfG d7d8„ d8e eIeƒƒZWG d9d:„ d:eWƒZXeXjY Z¡ D ]L\Z[Z\e]e\ƒ�sÔe^e\e_ƒ�sÔ�q²e[ `d;¡�s²eaeWe[ƒ�rð�q²eVeWe[e\ƒ �q²d<d=„ Zbh d>£Zcd?d@„ ZdebejPjƒD ]B\Z[Zee[ `d;¡�r<�q$e[eXjYv�r$e[ecv�r$eVeXeejfede[ƒƒ �q$n4G dAd4„ d4eEƒZSG dBd8„ d8ejPjƒZWG dCd:„ d:eWƒZXdDdE„ ZgdFdG„ ZhdHdI„ ZidjdJdK„Zjdkeee e
eee f df dLœdMdN„ZkdOdP„ ZldQdR„ ZmdSdT„ ZndUdV„ ZodWdX„ ZpdYdZ„ Zqej<jrZreerdƒ dleOeseseOd\œd]d^„ZtG d_d`„ d`ƒZuG dadb„ dbƒZvG dcdd„ ddƒZwdedf„ Zxeexdgƒ eejydhƒ ee-diƒ ee.diƒ ee/diƒ dS )mzß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ÚListÚTupleÚUnionÚCallable)Ú
set_module)ÚScriptMethodStubÚwrap_cpp_moduleÚinfer_methods_to_compileÚ_compile_and_register_class)ÚModule)Ú_enabled)Ú_register_builtin)Úwith_metaclass)Ú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_cache)Úhas_torch_functionÚhas_torch_function_unaryÚhas_torch_function_variadic)ÚPackageExporterÚPackageImporteré   )Úvalidate_map_location)Úmonkeytype_traceÚJitTypeTraceConfigÚJitTypeTraceStore)Úclassesz†
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)   úK/home/yuhw/wc/pochoir/venv/lib/python3.9/site-packages/torch/jit/_script.pyr%   @   s    aÑ  
    This method is a pass-through function that returns `value`, mostly
    used to indicate to the TorchScript compiler that the left-hand side
    expression is a class instance attribute with type of `type`. Note that
    `torch.jit.Attribute` should only be used in `__init__` method of `nn.Module`
    subclasses.

    Though TorchScript can infer correct type for most Python expressions, there are some cases where
    type inference can be wrong, including:

    - Empty containers like `[]` and `{}`, which TorchScript assumes to be container of `Tensor`
    - Optional types like `Optional[T]` but assigned a valid value of type `T`, TorchScript would assume
      it is type `T` rather than `Optional[T]`

    In eager mode, it is simply a pass-through function that returns `value`
    without other implications.

    Example:

    .. testcode::

        import torch
        from typing import Dict

        class AttributeModule(torch.nn.Module):
            def __init__(self):
                super(M, self).__init__()
                self.foo = torch.jit.Attribute(0.1, float)

                # we should be able to use self.foo as a float here
                assert 0.0 < self.foo

                self.names_ages = torch.jit.Attribute({}, Dict[str, int])
                self.names_ages["someone"] = 20
                assert isinstance(self.names_ages["someone"], int)

        m = AttributeModule()
        # m will contain two attributes
        # 1. foo of type float
        # 2. names_ages of type Dict[str, int]

    .. testcleanup::

        del AttributeModule
        del m

    Args:
        value: An initial value to be assigned to attribute.
        type: A Python type

    Returns:
        Returns `value`
c                   C   s   t S r(   )Útype_trace_dbr)   r)   r)   r*   Ú_get_type_trace_dby   s    r,   c                 C   s   t | |d ƒS r(   )Úgetattr)ÚclsÚnamer)   r)   r*   Ú_get_function_from_type~   s    r0   c                 C   s$   t | dƒr dt| ƒv pt | dƒS d S )NÚ	__class__Ú__dict__Ú	__slots__)ÚhasattrÚdir©r.   r)   r)   r*   Ú_is_new_style_class„   s    
r7   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)Úselfr9   r)   r)   r*   Ú__init__™   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>�   ó    z+OrderedDictWrapper.keys.<locals>.<listcomp>©Úitems©r:   r)   r)   r*   Úkeysœ   s    zOrderedDictWrapper.keysc                 C   s   dd„ |   ¡ D ƒS )Nc                 S   s   g | ]\}}|‘qS r)   r)   r<   r)   r)   r*   r@       rA   z-OrderedDictWrapper.values.<locals>.<listcomp>rB   rD   r)   r)   r*   ÚvaluesŸ   s    zOrderedDictWrapper.valuesc                 C   s   t |  ¡ ƒS r(   )ÚlenrF   rD   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©r:   r>   r)   r)   r*   Ú__delitem__¥   s    zOrderedDictWrapper.__delitem__c                 C   s
   | j  ¡ S r(   )r9   rC   rD   r)   r)   r*   rC   ¨   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 '{})rJ   Úformatr9   Úsetattr©r:   r>   r?   r)   r)   r*   Ú__setitem__«   s    ÿÿzOrderedDictWrapper.__setitem__c                 C   s   | j  |¡S r(   )r9   ÚcontainsrK   r)   r)   r*   Ú__contains__³   s    zOrderedDictWrapper.__contains__c                 C   s   || vrt |ƒ‚| j |¡S r(   )ÚKeyErrorr9   r-   rK   r)   r)   r*   Ú__getitem__¶   s    zOrderedDictWrapper.__getitem__N)Ú__name__Ú
__module__Ú__qualname__r;   rE   rF   rH   rL   rC   rP   rR   rT   r)   r)   r)   r*   r8   ˜   s   r8   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(   )ÚsuperrX   r;   ÚtorchÚ_CÚ
ModuleDictÚ_python_modules)r:   ÚmoduleZpython_dict©r1   r)   r*   r;   ½   s    zOrderedModuleDict.__init__c                 C   s   | j  ¡ }|S r(   )r]   rC   ©r:   Úrr)   r)   r*   rC   Ç   s    
zOrderedModuleDict.itemsc                 C   s
   || j v S r(   ©r]   rK   r)   r)   r*   rR   Ë   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ÚScriptModuler9   rN   r]   rJ   rM   rO   r)   r)   r*   rP   Î   s    

ÿÿzOrderedModuleDict.__setitem__c                 C   s
   | j | S r(   rb   rK   r)   r)   r*   rT   á   s    zOrderedModuleDict.__getitem__)	rU   rV   rW   r;   rC   rR   rP   rT   Ú__classcell__r)   r)   r_   r*   rX   ¼   s
   
rX   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ˆ ƒ |||¡ d S )NZ__constants__r)   Ú_methodsÚ_constants_setÚ_disable_script_metaFr;   c                 S   s   d S r(   r)   rD   r)   r)   r*   Ú<lambda>  rA   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 )Nrg   c                 S   s   g | ]\}}|‘qS r)   r)   r<   r)   r)   r*   r@     rA   zUScriptMeta.__init__.<locals>.init_then_script.<locals>.make_stubs.<locals>.<listcomp>)r'   r4   Úsortedrg   rC   r   )r^   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)rG   rg   r'   rZ   ÚjitÚ
_recursiveÚcreate_script_moduler2   rm   Ú_concrete_typeZget_attributesÚdelattrZget_modules)	r:   ÚargsÚkwargsZnum_methodsZadded_methods_in_initrl   Zconcrete_typer/   Ú_©r.   Zoriginal_initr)   r*   Úinit_then_script  s     
	þÿz-ScriptMeta.__init__.<locals>.init_then_script)rg   Úsetr-   rh   ÚreversedrC   Úunionrk   rc   r	   ru   Zoriginal_methodrU   rY   rf   r;   Ú	functoolsÚwraps)	r.   r/   ÚbasesÚattrsÚbaser>   r?   Zbase_constantsrz   r_   ry   r*   r;   î   s$    

zScriptMeta.__init__©rU   rV   rW   r;   re   r)   r)   r_   r*   rf   í   s   rf   c                   @   s   e Zd Zdd„ ZdS )Ú_CachedForwardc                 C   s
   |   d¡S )NÚforward)Ú__getattr__)r:   Úobjr.   r)   r)   r*   Ú__get__)  s    z_CachedForward.__get__N)rU   rV   rW   rˆ   r)   r)   r)   r*   r„   (  s   r„   c                   @   s   e Zd ZdS )ÚScriptWarningN)rU   rV   rW   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_uprd   )Z	self_name)r   Ú_jit_internalÚ!createResolutionCallbackFromFramer   rU   r	   )ÚfnÚ_rcbÚastr)   r)   r*   Úscript_method1  s
    r‘   c                   @   s   e Zd Zdd„ Zdd„ ZdS )ÚConstMapc                 C   s
   || _ d S r(   ©Úconst_mapping)r:   r”   r)   r)   r*   r;   F  s    zConstMap.__init__c                 C   s
   | j | S r(   r“   ©r:   Úattrr)   r)   r*   r†   I  s    zConstMap.__getattr__N)rU   rV   rW   r;   r†   r)   r)   r)   r*   r’   E  s   r’   )ÚimporterÚscript_module_idÚreturnc                 C   sH   t | jtjjƒstdƒ‚tj ¡ }tj || j| jt	| j
ƒ|¡}t|ƒS )z»
    Called by ``torch.package.PackageImporter``'s Pickler's ``persistent_load`` function.
    Performs work of loading and returning a ScriptModule from a ``torch.package`` archive.
    z{Loading ScriptObjects from a PackageImporter created from a directory is not supported. Use a package archive file instead.)rc   Z
zip_readerrZ   r[   ZPyTorchFileReaderrJ   ÚCompilationUnitZ_import_ir_module_from_packageZstorage_contextr    Zlast_map_locationr
   )r—   r˜   ZcuÚ
cpp_moduler)   r)   r*   Úunpackage_script_moduleM  s    ÿ
ûrœ   )Ú__iter__rH   Ú__neg__Ú__mul__rR   Ú__add__Ú__sub__Ú__pow__Ú__truediv__Ú__mod__Ú__ne__Ú__eq__Ú__lt__Ú__gt__Ú__le__Ú__ge__Ú__and__Ú__or__Ú__xor__rT   rP   Ú__call__Ú__int__Ú	__float__Ú__bool__Ú__str__Ú	__enter__Ú__exit__c                       sP   e Zd ZdZ‡ fdd„Z‡ fdd„Z‡ fdd„Zdd	„ Zd
d„ Zdd„ Z	‡  Z
S )ÚRecursiveScriptClassa  
        An analogue of RecursiveScriptModule for regular objects that are not modules.
        This class is a wrapper around a torch._C.ScriptObject that represents an instance
        of a TorchScript class and allows it to be used in Python.

        Attributes:
            _c [torch._C.ScriptObject]: The C++ object to which attribute lookups and method
                calls are forwarded.
            _props [Dict[str, property]]: A dictionary of properties fetched from self._c and
                exposed on this wrppaer.
        c                    sB   t t| ƒ ¡  d| jd< || _dd„ | j ¡ D ƒ| _d| jd< d S )NTÚ_initializingc                 S   s   i | ]}|j t|j|jƒ“qS r)   )r/   ÚpropertyÚgetterÚsetter)r=   Úpropr)   r)   r*   Ú
<dictcomp>”  rA   z1RecursiveScriptClass.__init__.<locals>.<dictcomp>F)rY   rµ   r;   r2   r9   Z_propertiesÚ_props)r:   Z	cpp_classr_   r)   r*   r;   Ž  s
    
úRecursiveScriptClass.__init__c                    sH   d| j v r$| j d r$tt| ƒ |¡S || jv r<| j|  ¡ S t| j|ƒS ©Nr¶   )r2   rY   rµ   r†   r¼   Úfgetr-   r9   r•   r_   r)   r*   r†   ˜  s
    
z RecursiveScriptClass.__getattr__c                    sR   d| j v r&| j d r&tt| ƒ ||¡S || jv r@| j|  |¡S t| j||ƒ d S r¾   )r2   rY   rµ   Ú__setattr__r¼   ÚfsetrN   r9   ©r:   r–   r&   r_   r)   r*   rÀ   ¡  s
    
z RecursiveScriptClass.__setattr__c                 O   s*   | j  |¡stƒ ‚|  |¡}||i |¤ŽS r(   )r9   Ú_has_methodÚ	TypeErrorr†   ©r:   Úmethod_namerv   rw   Úself_methodr)   r)   r*   Úforward_magic_method¬  s    
z)RecursiveScriptClass.forward_magic_methodc                 C   s   t  d¡‚d S )NzScriptClasses cannot be pickled)ÚpickleÚPickleErrorrD   r)   r)   r*   Ú__getstate__³  s    z!RecursiveScriptClass.__getstate__c                 C   s(   | j  d¡r|  d|¡S |  d|¡S d S )NÚ__iadd__r    )r9   rÃ   rÈ   )r:   Úotherr)   r)   r*   rÌ   ¶  s    zRecursiveScriptClass.__iadd__)rU   rV   rW   Ú__doc__r;   r†   rÀ   rÈ   rË   rÌ   re   r)   r)   r_   r*   rµ   ‚  s   
	rµ   c                 O   s   | j tg|¢R i |¤ŽS r(   )rÈ   rÆ   ©r:   rv   rw   r)   r)   r*   Úmethod_template¾  s    rÐ   c                       sd   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edœdd„Z‡  ZS )rd   zÚ
        A wrapper around C++ ``torch::jit::Module``. ``ScriptModule``\s
        contain methods, attributes, parameters, and
        constants. These can be accessed the same way as on a normal ``nn.Module``.
        )ÚcodeÚcode_with_constantsÚgraphÚinlined_graphÚoriginal_namec                    s   t t| ƒ ¡  d S r(   )rY   rd   r;   rD   r_   r)   r*   r;   Ó  s    úScriptModule.__init__c                    s&   d| j vrtt| ƒ |¡S t| j|ƒS )Nrm   )r2   rY   rd   r†   r-   rm   r•   r_   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 )Nrm   Ú__annotations__)r2   rc   r%   r1   r×   r'   r&   rY   rd   rÀ   rN   rm   rÂ   r_   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 )Nrm   r   r‹   )r2   rm   ÚdefinerŒ   r�   rZ   r[   Z_parse_source_defr	   rg   r/   )r:   ÚsrcÚrcbr�   r)   r)   r*   rØ   ñ  s
    
zScriptModule.definec                 C   s
   | j  ¡ S r(   )rm   Ú_replicate_for_data_parallelrD   r)   r)   r*   rÛ     s    z)ScriptModule._replicate_for_data_parallel)Úexporterc                 C   s&   |  ¡ }|j | jt|ƒ¡ t|ffS )a}  
            Called by ``torch.package.PackageExporter``'s Pickler's ``persistent_id`` when
            saving TorchScript objects. Performs act of saving a ScriptModule inside of
            a ``torch.package`` archive.

            Returns method to load the ScriptModule from a ``torch.package.PackageImporter``'s
            Pickler's ``persistent_load`` function.
            )Zget_unique_idZscript_module_serializerÚ	serializer9   Úintrœ   )r:   rÜ   r˜   r)   r)   r*   Ú__reduce_package__
  s    	zScriptModule.__reduce_package__)rU   rV   rW   rÎ   Z__jit_unused_properties__r;   r„   r…   r†   rÀ   rØ   rÛ   r   rß   re   r)   r)   r_   r*   rd   Ë  s   rd   c                       s,  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 ‡ fd7d8„Z!d9d:„ 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 )NTr¶   Ztraining)r2   r9   rY   rà   r;   ru   )r:   r›   r_   r)   r*   r;   3  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).

            Args:
                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*   Ú
_construct<  s    
z RecursiveScriptModule._constructc                 C   sB   t tj | j¡ƒ| _t tj | j¡ƒ| _t| j| j	ƒ| _	d| _
d S )NF)r8   rZ   r[   ÚParameterDictr9   rn   Ú
BufferDictro   rX   rp   r¶   ©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.

            Args:
                cpp_module: The C++ module that this RecursiveScriptModule will be rebuilt around.
            c                 S   s$   i | ]\}}t |tjjƒs||“qS r)   )rc   rZ   r[   ÚScriptMethodr<   r)   r)   r*   r»   x  s   þz6RecursiveScriptModule._reconstruct.<locals>.<dictcomp>Fr¶   N)r;   rZ   r[   ZConcreteModuleTypeZfrom_jit_typer9   Ú_typert   r\   rC   r
   rX   rp   r8   ræ   rn   rç   ro   r2   )r:   r›   Úmodulesr/   r)   r)   r*   Ú_reconstruct_  s    
ÿþz"RecursiveScriptModule._reconstructc                 C   s   | j  d¡jS )z£
            Returns a string representation of the internal graph for the
            ``forward`` method. See :ref:`interpreting-graphs` for details.
            r…   )r9   Ú_get_methodrÓ   rD   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Ô   rD   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Ñ   rD   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’   r`   r)   r)   r*   rÒ   ™  s    z)RecursiveScriptModule.code_with_constantsc                 K   s   | j jt|ƒfi |¤ŽS )zx
            save(f, _extra_files={})

            See :func:`torch.jit.save <torch.jit.save>` for details.
            )r9   ÚsaveÚstr)r:   Úfrw   r)   r)   r*   rî   ¨  s    zRecursiveScriptModule.savec                 O   s   | j j|i |¤ŽS )az  
            _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.

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

            )r9   Z_save_for_mobilerÏ   r)   r)   r*   Ú_save_for_lite_interpreter°  s    z0RecursiveScriptModule._save_for_lite_interpreterc                 O   s   | j j|i |¤ŽS r(   )r9   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(   )r9   Úsave_to_bufferrÏ   r)   r)   r*   ró   Á  s    z$RecursiveScriptModule.save_to_bufferc                 O   s
   | j  ¡ S r(   )r9   Úget_debug_staterÏ   r)   r)   r*   rô   Ä  s    z%RecursiveScriptModule.get_debug_statec                 C   s   d  | j¡S )Nzoriginal_name={})rM   rÕ   rD   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'   rï   r9   rê   r/   rD   r)   r)   r*   rÕ   Í  s    z#RecursiveScriptModule.original_namec                 C   s"   t jdd�}| j | j||¡ d S )Nr   r‹   )rŒ   r�   r9   Z_definert   )r:   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?)r2   rJ   r¶   rY   rà   r†   rp   r9   r4   r-   rÃ   rí   )r:   r–   r‘   r_   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 )Nrt   z;Cannot mutate TorchScript constant value: '{}'. Value: '{}')r¶   rY   rà   rÀ   rp   r9   r4   rN   rt   Zget_constantsrE   ÚAttributeErrorrM   rÂ   r_   r)   r*   rÀ   ÷  s     
ÿþÿÿz!RecursiveScriptModule.__setattr__c                 C   s   t jj t | j¡¡S r(   )rZ   rq   rr   r
   Úcopyr9   rD   r)   r)   r*   Ú__copy__  s    zRecursiveScriptModule.__copy__c                 C   s   t jj t | j|¡¡S r(   )rZ   rq   rr   r
   rù   Údeepcopyr9   )r:   Úmemor)   r)   r*   Ú__deepcopy__  s    z"RecursiveScriptModule.__deepcopy__c                 O   s4   t | |ƒ}t |dd ƒt t|ƒkr&tƒ ‚||i |¤ŽS )NÚ__func__)r-   rà   ÚNotImplementedErrorrÅ   r)   r)   r*   rÈ     s    
ÿz*RecursiveScriptModule.forward_magic_methodc                 C   s
   |   d¡S )Nr�   ©rÈ   rD   r)   r)   r*   r�   &  s    zRecursiveScriptModule.__iter__c                 C   s   |   d|¡S )NrT   r   )r:   Úidxr)   r)   r*   rT   )  s    z!RecursiveScriptModule.__getitem__c                 C   s
   |   d¡S )NrH   r   rD   r)   r)   r*   rH   ,  s    zRecursiveScriptModule.__len__c                 C   s   |   d|¡S )NrR   r   )r:   Úkeyr)   r)   r*   rR   /  s    z"RecursiveScriptModule.__contains__c                    s*   | j }|jttdƒkr$tt| ƒ  ¡ S |ƒ S )NÚ__dir__)r  rþ   r0   rà   rY   ©r:   rÇ   r_   r)   r*   r  4  s    ÿzRecursiveScriptModule.__dir__c                 C   s    | j }|jttdƒkrdS |ƒ S )Nr±   T)r±   rþ   r0   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ã   J  s    zCRecursiveScriptModule._replicate_for_data_parallel.<locals>.init_fn)rà   rå   r9   rÛ   )r:   rã   r)   r)   r*   rÛ   G  s    
ÿz2RecursiveScriptModule._replicate_for_data_parallel)%rU   rV   rW   rÎ   ri   r;   Ústaticmethodrå   râ   rì   r·   rÓ   rÔ   rÑ   rÒ   rî   rñ   rò   ró   rô   rõ   rö   rÕ   rØ   r†   rÀ   rú   rý   rÈ   r�   rT   rH   rR   r  r±   rÛ   re   r)   r)   r_   r*   rà     sL   	

 




rà   Ú__c                    s   dd l ‰ ˆ j| ‡ fdd„d�S )Nr   c                    s   ˆ   | ¡pˆ  | ¡S r(   )Ú
isfunctionÚismethod©Úx©Úinspectr)   r*   rj   f  rA   z_get_methods.<locals>.<lambda>)Ú	predicate)r  Ú
getmembersr6   r)   r  r*   Ú_get_methodsa  s    ÿr  >$   ÚdoubleZ_load_from_state_dictÚfloatZ
state_dictrõ   Ú_applyZshare_memoryZcudaÚchildrenr'   Ú
parametersZ_slow_forwardZ_tracing_nameZnamed_modulesZnamed_childrenZhalfZ_named_membersZget_extra_stateZnamed_buffersZload_state_dictZset_extra_stateZtrainÚtoZregister_parameterr…   rë   Znamed_parametersZ
add_moduleÚapplyZregister_bufferZ_save_to_state_dictÚbuffersZ	_get_nameÚcpuÚevalZ	zero_gradc                    s   ‡ fdd„}|S )Nc                    s   t ˆ d ƒ‚d S )Nz" is not supported on ScriptModulesrI   rÏ   ©r/   r)   r*   Úfail‘  s    z_make_fail.<locals>.failr)   )r/   r  r)   r  r*   Ú
_make_fail�  s    r  c                       s   e Zd Z‡ fdd„Z‡  ZS )rµ   c                    s   t ƒ  ¡  d S r(   ©rY   r;   rD   r_   r)   r*   r;   £  s    r½   rƒ   r)   r)   r_   r*   rµ   ¢  s   c                       s   e Zd Zd‡ fdd„	Z‡  ZS )rd   Nc                    s   t ƒ  ¡  d S r(   r  ©r:   Úargr_   r)   r*   r;   §  s    rÖ   )Nrƒ   r)   r)   r_   r*   rd   ¦  s   c                       s   e Zd Zd‡ fdd„	Z‡  ZS )rà   Nc                    s   t ƒ  ¡  d S r(   r  r  r_   r)   r*   r;   «  s    rá   )Nrƒ   r)   r)   r_   r*   rà   ª  s   c                 C   sæ   t | tjjƒs| S t| ƒ}||v r.|t| ƒ S t| dƒr@|  ¡ n| } | ||< i }| j ¡ D ]j\}}|dkr”| ¡ D ]\}}t	||ƒ||< qr|||< qZt |tjjƒr¼t |t
ƒs¼t	||ƒ||< qZ|||< qZ| ¡ D ]\}}|| j|< qÎ| S )NÚ__prepare_scriptable__rp   )rc   rZ   Únnr   Úidr4   r   r2   rC   Ú!call_prepare_scriptable_func_implrd   )r‡   rü   Zobj_idZnew_obj_dictr/   Z
sub_moduler>   r?   r)   r)   r*   r#  ®  s&    

r#  c                 C   s   i }t | |ƒS r(   )r#  )r‡   rü   r)   r)   r*   Úcall_prepare_scriptable_funcÐ  s    r$  c                 C   s   t j | ¡S )a²  
    Create a ``torch._C.ScriptDict`` instance with the data from ``obj``.

    Args:
        obj (dict): The Python dictionary that is used to initialize the ``ScriptDict``
                    returned by this function.

    Returns:
        An instance of ``torch._C.ScriptDict`` that has the same data as ``obj``
        and can be passed between Python and TorchScript with reference semantics and
        zero copy overhead.
    )rZ   r[   Z
ScriptDict)r‡   r)   r)   r*   Úcreate_script_dictÔ  s    r%  c                 C   s   t j | ¡S )aª  
    Create a ``torch._C.ScriptList`` instance with the data from ``obj``.
    Args:
        obj (dict): The Python list that is used to initialize the ``ScriptList``
                    returned by this function.
    Returns:
        An instance of ``torch._C.ScriptList`` that has the same data as ``obj``
        and can be passed between Python and TorchScript with reference semantics and
        zero copy overhead.
    )rZ   r[   Z
ScriptList)r‡   Z	type_hintr)   r)   r*   Úcreate_script_listä  s    r&  )Úexample_inputsc                 C   s†  t s| S |durt d¡ t| tƒr(| S t| tƒr6| S t| tƒrD| S |rätƒ at	rÚt
tƒ}t	|ƒ�f t|tƒr”| ¡ D ]\}}|D ]}||Ž  q‚qvn&t|tƒr²|D ]}	| |	Ž  q¢ntdƒ‚W d  ƒ qä1 sÎ0    Y  n
t d¡ t| tjjƒ�rt| ƒ} tjj | tjjj¡S t| tƒ�r&t| ƒS t| tƒ�r:t| ƒS t | ¡�rÒt| ƒ}
t| tjjƒ�rltd  | ¡ƒ‚t| t!j"ƒ�r~| S t#| ƒ�s�tdƒ‚t$|  %¡ ƒdk�rªtdƒ‚|du �rÂt& '|d	 ¡}t(| ||
ƒ | S t )| ¡�sêt *| ¡�rtt| ƒ}
t+| d
ƒ�r| j,} t& -| ¡}t.| ƒ t/| ƒ}|�r(|S t0| | j1ƒ}|du �rHt& -| ¡}tj2 3|
||t4| ƒ¡}| j5|_5t6| |ƒ |S tjj 7| ¡S dS )aº  
    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`.

    Scripting a dictionary or list copies the data inside it into a TorchScript instance than can be
    subsequently passed by reference between Python and TorchScript with zero copy overhead.

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

    Args:
        obj (callable, class, or ``nn.Module``):  The ``nn.Module``, function, class type,
                                                  dictionary, or list to compile.
        example_inputs (Union[List[Tuple], Dict[Callable, List[Tuple]], None]): Provide example inputs
            to annotate the arguments for a function or ``nn.Module``.

    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. If ``obj`` is a ``dict``, then
        ``script`` returns an instance of `torch._C.ScriptDict`. If ``obj`` is a ``list``,
        then ``script`` returns an instance of `torch._C.ScriptList`.

    **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.ScriptFunction

            # 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 a function using example_inputs**
        Example inputs can be used to annotate a function arguments.

        Example (annotating a function before scripting):

        .. testcode::

            import torch

            def test_sum(a, b):
                return a + b

            # Annotate the arguments to be int
            scripted_fn = torch.jit.script(test_sum, example_inputs=[(3, 4)])

            print(type(scripted_fn))  # torch.jit.ScriptFunction

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

            # Call the function using the TorchScript interpreter
            scripted_fn(20, 100)

        .. 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)))

        Example ( Annotating forward of nn.Module using example_inputs)::

            import torch
            import torch.nn as nn
            from typing import NamedTuple

            class MyModule(NamedTuple):
            result: List[int]

            class TestNNModule(torch.nn.Module):
                def forward(self, a) -> MyModule:
                    result = MyModule(result=a)
                    return result

            pdt_model = TestNNModule()

            # Runs the pdt_model in eager model with the inputs provided and annotates the arguments of forward
            scripted_model = torch.jit.script(pdt_model, example_inputs={pdt_model: [([10, 20, ], ), ], })

            # Run the scripted_model with actual inputs
            print(scripted_model([20]))
    Nz]`optimize` is deprecated and has no effect. Use `with torch.jit.optimized_execution() insteadzˆError: Unable to infer types. Please format the inputs to type `List[Tuple]` or `Dict[Callable, List[Tuple]]` to be run with MonkeyType.zîWarning: monkeytype is not installed. Please install https://github.com/Instagram/MonkeyType to enable Profile-Directed Typing in TorchScript. Refer to https://github.com/Instagram/MonkeyType/blob/master/README.rst to install MonkeyType. zWType '{}' 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)8r   ÚwarningsÚwarnrc   rµ   rd   ÚScriptFunctionr#   r+   r!   r"   r   rC   r   Ú
ValueErrorrZ   r!  r   r$  rq   rr   rs   r   Údictr%  Úlistr&  r  Úisclassr   Ú
issubclassrJ   rM   ÚenumÚEnumr7   rG   ÚmrorŒ   r�   r   r  r  r4   Z__original_fnÚ#createResolutionCallbackFromClosureÚ"_check_directly_compile_overloadedr   r   rU   r[   Z_jit_script_compiler   rÎ   r   Zcreate_script_class)r‡   ÚoptimizeZ
_frames_upr�   r'  Zmonkeytype_configr^   Zexample_inputZexampleZexamplesÚqualified_nameZmaybe_already_compiled_fnr�   rŽ   r)   r)   r*   Úscriptò  sš     Iÿ





(

ÿþÿ
ÿÿ



ÿ
r7  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  )rC   rZ   rq   ZfrontendZFrontendErrorrM   )Zimpl_defaultsÚoverload_defaultsÚlocr/   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   rU   ÚdeclrZ   rq   ÚannotationsZget_signaturer  r  r   rŒ   r3  r:  Úranger[   Z_jit_script_compile_overload)
Úoverload_fnÚ	qual_nameZimpl_fnZoverload_declZoverload_signatureZimpl_astr8  Zimplementation_defaultsr�   rŽ   r)   r)   r*   Ú_compile_function_with_overload8  s(    ÿ

ÿúr@  c                 C   s‚   t | ƒ}t| ƒ}t |¡}|d u r&|S | |v r>tt d| ¡ƒ‚g }|D ]}| t||| ƒ¡ qF|rj|| }t| |ƒ t 	|¡ |S )NÚfunction)
r   r   rŒ   Ú_get_fn_overloadsrJ   Z,get_overload_no_implementation_error_messageÚappendr@  r   Z_clear_fn_overloads)r‡   Zexisting_compiled_fnsr?  Zuncompiled_overloadsZcompiled_fnsr>  r)   r)   r*   Ú_get_overloadsO  s&    
ÿ
ÿ

rD  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Œ   rB  r   rJ   rM   )r‡   r?  r)   r)   r*   r4  j  s    þÿr4  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 ||||¡}|| _| 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   )r  r.  rJ   r7   r/  rZ   r!  r   rG   r2  r   rŒ   r�   r   rU   r[   Z_jit_script_interface_compileZ__torch_script_interface__)r‡   Zis_module_interfacer6  rÚ   r�   Zmangled_classnamer)   r)   r*   Ú	interfacet  s"    
ÿ
ÿrF  c                 C   s,   t | ƒ}tj ||¡}t | ¡}t| ||ƒS r(   )r   rZ   r[   Z	CallStackrŒ   Z'createResolutionCallbackForClassMethodsr   )r‡   r9  Z
_qual_nameZerror_stackrÚ   r)   r)   r*   Ú_recursive_compile_class“  s    
rG  ú ©ÚsÚpaddingÚoffsetÚcharc                    s<   |t | ƒkr|t | ƒ8 }d ‡ fdd„t|| ƒD ƒ¡|  S )Nr÷   c                    s   g | ]}ˆ ‘qS r)   r)   )r=   rx   ©rM  r)   r*   r@   ¢  rA   zpad.<locals>.<listcomp>)rG   Újoinr=  rI  r)   rN  r*   ÚpadŸ  s    rP  c                   @   s8   e Zd Zdeeedœdd„Zeedœdd„Zd	d
„ ZdS )Ú_ScriptProfileColumné   r   )ÚheaderÚ	alignmentrL  c                 C   s   || _ || _|| _i | _d S r(   )rS  rT  rL  Úrows)r:   rS  rT  rL  r)   r)   r*   r;   ¦  s    z_ScriptProfileColumn.__init__)Úlinenor&   c                 C   s   || j |< d S r(   )rU  )r:   rV  r&   r)   r)   r*   Úadd_row¬  s    z_ScriptProfileColumn.add_rowc                    s–   t ˆjƒ}g }ˆj ¡ D ],\}}t|ƒ}| ||f¡ tt |ƒ|ƒ}qˆjdkrj|ˆj ‰ ˆ ˆ ˆj 8 ‰ nd‰ ‡ ‡fdd„|D ƒ}tˆjˆ ˆj	ƒ|fS )Nr   c                    s"   g | ]\}}|t |ˆ ˆjƒf‘qS r)   )rP  rL  )r=   r  Úcell©rK  r:   r)   r*   r@   ½  rA   z4_ScriptProfileColumn.materialize.<locals>.<listcomp>)
rG   rS  rU  rC   rï   rC  ÚmaxrT  rP  rL  )r:   Ú
max_lengthrU  r  r&   rX  r)   rY  r*   Úmaterialize¯  s    


z _ScriptProfileColumn.materializeN)rR  r   )	rU   rV   rW   rï   rÞ   r;   r   rW  r\  r)   r)   r)   r*   rQ  ¥  s   rQ  c                   @   s,   e Zd Zee ee dœdd„Zdd„ ZdS )Ú_ScriptProfileTable©ÚcolsÚsource_rangec                 C   s   || _ || _d S r(   r^  )r:   r_  r`  r)   r)   r*   r;   Â  s    z_ScriptProfileTable.__init__c           
      C   sÀ   g }g }d}| j D ]*}| ¡ \}}||7 }| |t|ƒf¡ q| |¡ | tdt|ƒddƒ¡ | jD ]N}d}|D ]6\}}| |¡}	|	d u r |tdt|ƒƒ7 }qr||	7 }qr| |¡ qfd |¡S )Nr÷   r   ú=Ú
)	r_  r\  rC  r,  rP  rG   r`  ÚgetrO  )
r:   ÚoutputsÚcellsZheader_bufferÚcolrS  rU  ÚlineZ
row_bufferrX  r)   r)   r*   Údump_stringÆ  s$    




z_ScriptProfileTable.dump_stringN)rU   rV   rW   r   rQ  rÞ   r;   rh  r)   r)   r)   r*   r]  Á  s   r]  c                   @   s:   e Zd Zdd„ Zdd„ Zdd„ Zedœdd	„Zd
d„ ZdS )Ú_ScriptProfilec                 C   s   t j ¡ | _d S r(   )r$   Z	profilingri  ÚprofilerD   r)   r)   r*   r;   Þ  s    z_ScriptProfile.__init__c                 C   s   | j  ¡  d S r(   )rj  ÚenablerD   r)   r)   r*   rk  á  s    z_ScriptProfile.enablec                 C   s   | j  ¡  d S r(   )rj  ÚdisablerD   r)   r)   r*   rl  ä  s    z_ScriptProfile.disable)r™   c                    s"  g }| j  ¡ D �]}| ¡ }| ¡  ¡ }tdd„ |D ƒƒ‰ ‡ fdd„|D ƒ}| ¡ }|t|ƒ }t||ƒ}t	dƒ}t	dƒ}	t	dƒ}
t	ddd	ƒ}| 
¡ }|D ]V}| ||¡ | ||||  ¡ | |¡}|d urš|	 || ¡ ¡ |
 || ¡ ¡ qšt||	|
|gt|ƒƒ}| | ¡ ¡ qd
 |¡S )Nc                 S   s"   g | ]}t |ƒt | d ¡ƒ ‘qS )rH  )rG   Úlstrip©r=   rg  r)   r)   r*   r@   ì  rA   z._ScriptProfile.dump_string.<locals>.<listcomp>c                    s   g | ]}|ˆ d … ‘qS r(   r)   rn  ©Údedentr)   r*   r@   í  rA   zLine #ZHitsz	Time (ns)zLine Contentsr   r   z

)rj  Z_dump_statsÚsourceÚtextÚ
splitlinesÚminZstarting_linenorG   r=  rQ  Zline_maprW  rc  ÚcountZduration_nsr]  r-  rC  rh  rO  )r:   rd  Úsource_statsZ
source_refZsource_linesZ
start_lineZend_liner`  rV  ÚhitsÚtime_nsZline_contentsÚstatsrg  ÚstatÚtabler)   ro  r*   rh  ç  s0    

z_ScriptProfile.dump_stringc                 C   s   t |  ¡ ƒ d S r(   )Úprintrh  rD   r)   r)   r*   Údump  s    z_ScriptProfile.dumpN)	rU   rV   rW   r;   rk  rl  rï   rh  r}  r)   r)   r)   r*   ri  Ý  s
   ri  c                 C   s   | d usJ dƒ‚| S )NzUnwrapping null optionalr)   r	  r)   r)   r*   Ú_unwrap_optional  s    r~  zaten::_unwrap_optionalzaten::is_scriptingzaten::has_torch_function)N)Nr   NN)r   rH  )zrÎ   r~   Úcollectionsr0  r  rù   rÉ   r(  Útypingr   r   r   r   r   r   rZ   Ztorch._jit_internalrŒ   Ztorch.utilsr   Ztorch.jit._recursiver	   r
   r   r   Ztorch.nnr   Ztorch.jit._stater   Ztorch.jit._builtinsr   Z
torch._sixr   Ztorch.jit.frontendr   r   r   r   Ztorch.jit._fuserr   r   r   r   r   Ztorch.overridesr   r   r   Ztorch.packager   r   Z_serializationr    Ztorch.jit._monkeytype_configr!   r"   r#   Ztorch._classesr$   r+   r[   ré   rö   r*  Ú
namedtupler%   r,   r0   r7   Úobjectr8   rX   r'   rf   r„   ÚWarningr‰   r‘   r’   rï   r!  rœ   Z_magic_methodsrµ   rÆ   rÐ   rN   rd   rà   r2   rC   r/   ÚitemÚcallablerc   r·   Ú
startswithr4   r  Z_compiled_methods_allowlistr  ÚmethodrU   r#  r$  r%  r&  r7  r:  r@  rD  r4  rF  rG  rš   rÞ   rP  rQ  r]  ri  r~  Zis_scriptingr)   r)   r)   r*   Ú<module>   sÒ    


6$1;;
L  B'ÿþ"
  ÿÿ  =

*


