
    YTh              	       0   % S r SSKrSSKrSSKrSSKrSSKrSSKrSSKrSSKJ	r	J
r
Jr  SSKrSSKJr  SSKJr  SSKJrJr  SSKJr  SSKJr  SSKJrJr  SS	KJrJrJr  SS
KJrJ r J!r!J"r"  SSK#J$r$J%r%J&r&J'r'J(r(  SSK)J*r*J+r+J,r,  SSK-J.r.  SSK/J0r0J1r1J2r2  SSK3J4r4J5r5  SSK6J7r7  SSK8J9r9  \" 5       q:\\Rv                  Rx                  l=        \\Rv                  R|                  l=        \Rv                  R|                  r>S\>l         S\>l?        S\>l@        \7" \>S5        S rA\A\>lB        \$(       a  \R                  " SSS/5      rDOS rDS\Dl         S rES rFS rG " S  S!5      rH " S" S#\H5      rI " S$ S%\J5      rK " S& S'5      rL " S( S)\M5      rNS* rO " S+ S,5      rPS-\5S.\QS/\R                  R\                  4S0 jrS\$(       Ga=  / S1QrT " S2 S35      rU\T H  rVS4 rW\X" \U\V\W5        M      " S5 S6\.\KS79rY " S8 S9\Y5      rZ\ZR                  R                  5        HS  u  r]r^\_" \^5      (       d  \`" \^\a5      (       d  M#  \]R                  S:5      (       d  \c" \Y\]5      (       a  MI  \X" \Y\]\^5        MU     S; rd1 S<kreS= rf\d" \R                  R\                  5       Hh  u  r]rg\]R                  S:5      (       d  \]R                  S>5      (       a  M4  \]\ZR                  ;  d  MF  \]\e;  d  MN  \X" \Z\gR~                  \f" \]5      5        Mj     O4 " S? S35      rU " S@ S6\R                  R\                  5      rY " SA S9\Y5      rZSB riSC rjSD rkS`SE jrlSFqm\n\oSG'       SaSH\\p\q   \r\
\p\q   4   S4   4SI jjrs    SaSH\\p\q   \r\
\p\q   4   S4   4SJ jjrtSK ruSL rvSM rwSN rxSO rySP rz\Rv                  R                  r{\7" \{S5        SbSQ\QSR\|SS\|ST\Q4SU jjr} " SV SW5      r~ " SX SY5      r " SZ S[5      rS\ r\" \S]5        \" \GR                  S^5        \" \0S_5        \" \1S_5        \" \2S_5        g)czTorchScript.

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CallableUnion)classes)_get_model_id_qualified_name)log_torchscript_usage)_register_builtin)
_graph_for_script_method_graph_for)JitTypeTraceConfigJitTypeTraceStoremonkeytype_trace)_compile_and_register_classinfer_methods_to_compileScriptMethodStubwrap_cpp_module)_enabled_set_jit_function_cache_set_jit_overload_cache_try_get_jit_cached_function_try_get_jit_cached_overloads)get_default_argsget_jit_class_defget_jit_def)Module)has_torch_functionhas_torch_function_unaryhas_torch_function_variadic)PackageExporterPackageImporter)
set_module   )validate_map_locationz
Functionally equivalent to a :class:`ScriptModule`, but represents a single
function and does not have any attributes or Parameters.
ScriptFunctiontorch.jit.ScriptFunctionz	torch.jitc                 .    [         R                  " S5      e)Nz ScriptFunction cannot be pickledpicklePickleErrorclss    I/var/www/auris/envauris/lib/python3.13/site-packages/torch/jit/_script.py_reducer.   I   s    


?
@@    	Attributevaluetypec                     U $ N )r1   r2   s     r-   r0   r0   T   s    r/   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 `jit.ScriptModule`
    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.jit.ScriptModule):
            def __init__(self) -> None:
                super().__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

    Note: it's now preferred to instead use type annotations instead of `torch.jit.Attribute`:

    .. testcode::

        import torch
        from typing import Dict

        class AttributeModule(torch.nn.Module):
            names: Dict[str, int]

            def __init__(self) -> None:
                super().__init__()
                self.names = {}

        m = AttributeModule()

    .. testcleanup::

        del AttributeModule
        del m

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

    Returns:
        Returns `value`
c                      [         $ r4   )type_trace_dbr5   r/   r-   _get_type_trace_dbr8      s    r/   c                     [        XS 5      $ r4   )getattr)r,   names     r-   _get_function_from_typer<      s    3d##r/   c                 h    [        U S5      (       a!  S[        U 5      ;   =(       d    [        U S5      $ g )N	__class____dict__	__slots__)hasattrdirr+   s    r-   _is_new_style_classrC      s/    sK  SX%Bk)BB !r/   c                   J    \ rS rSrS rS rS rS rS rS r	S r
S	 rS
 rSrg)OrderedDictWrapper   c                     Xl         g r4   _c)selfrI   s     r-   __init__OrderedDictWrapper.__init__   s    r/   c                 X    U R                  5        VVs/ s H  u  pUPM	     snn$ s  snnf r4   itemsrJ   kvs      r-   keysOrderedDictWrapper.keys   "    "jjl+ldal+++   &c                 X    U R                  5        VVs/ s H  u  pUPM	     snn$ s  snnf r4   rN   rP   s      r-   valuesOrderedDictWrapper.values   rU   rV   c                 4    [        U R                  5       5      $ r4   )lenrX   rJ   s    r-   __len__OrderedDictWrapper.__len__   s    4;;=!!r/   c                     [        S5      e)Nz6cannot delete methods or parameters of a script moduleRuntimeErrorrJ   rQ   s     r-   __delitem__OrderedDictWrapper.__delitem__   s    STTr/   c                 6    U R                   R                  5       $ r4   )rI   rO   r\   s    r-   rO   OrderedDictWrapper.items   s    ww}}r/   c                 `    X;  a  [        SU 35      eU R                  R                  X5        g )NzICan't add a new parameter after ScriptModule construction. Tried to add ')ra   rI   setattrrP   s      r-   __setitem__OrderedDictWrapper.__setitem__   s2    =[\][^_  	r/   c                 8    U R                   R                  U5      $ r4   )rI   containsrb   s     r-   __contains__OrderedDictWrapper.__contains__   s    ww""r/   c                 X    X;  a  [        U5      eU R                  R                  U5      $ r4   )KeyErrorrI   r:   rb   s     r-   __getitem__OrderedDictWrapper.__getitem__   s$    =1+wwq!!r/   rH   N)__name__
__module____qualname____firstlineno__rK   rS   rX   r]   rc   rO   ri   rm   rq   __static_attributes__r5   r/   r-   rE   rE      s0    ,,"U#"r/   rE   c                   @   ^  \ rS rSrU 4S jrS rS rS rS rSr	U =r
$ )OrderedModuleDict   c                 j   > [         TU ]  [        R                  R	                  U5      5        X l        g r4   )superrK   torch_C
ModuleDict_python_modules)rJ   modulepython_dictr>   s      r-   rK   OrderedModuleDict.__init__   s'    ,,V45  +r/   c                 :    U R                   R                  5       nU$ r4   )r   rO   rJ   rs     r-   rO   OrderedModuleDict.items   s      &&(r/   c                     XR                   ;   $ r4   r   rb   s     r-   rm   OrderedModuleDict.__contains__   s    ((((r/   c                     [        U[        5      (       a*  U R                  R                  X5        X R                  U'   g [        SU SU 35      e)NzgCannot re-assign modules in a ScriptModule with non-scripted module, tried to replace existing module 'z': )
isinstanceScriptModulerI   rh   r   ra   rP   s      r-   ri   OrderedModuleDict.__setitem__   sR     a&&GGOOA!&'  #==>Cs1#G r/   c                      U R                   U   $ r4   r   rb   s     r-   rq   OrderedModuleDict.__getitem__  s    ##A&&r/   r   )rs   rt   ru   rv   rK   rO   rm   ri   rq   rw   __classcell__r>   s   @r-   ry   ry      s!    +)&' 'r/   ry   c                   (   ^  \ rS rSrU 4S jrSrU =r$ )
ScriptMetai  c                   >^ ^	 0 T l         [        [        T SS5      5      T l        [	        U5       Hk  n[        US0 5      R                  5        H  u  pVUT R                   U'   M     [        US[        5       5      nT R                  R                  U5      T l        Mm     [        UR                  5       5       HK  u  pV[        U[        5      (       d  M  [        T U5        UT R                   UR                  R                  '   MM     [        T SS5      (       a  [        T
T ]9  XU5        g [        T SS 5      m	[        R                   " T	5      U U	4S	 j5       nUT l        [        T
T ]9  XU5        g )
N__constants__r5   _methods_constants_set_disable_script_metaFrK   c                     g r4   r5   r\   s    r-   <lambda>%ScriptMeta.__init__.<locals>.<lambda>0  s    dr/   c                   > [        T	R                  5      nT
" U /UQ70 UD6  [        T	R                  5      U:  n[        U 5      T	:X  a  S n[        R                  R
                  R                  XU(       + S9U R                  S'   U R                  R                  nUR                  5        H  n[        X5        M     UR                  5        H  u  px[        X5        M     S H  n[        X5        M     g g )Nc                     [        U 5      n[        US5      (       a8  [        UR                  R	                  5       5       VVs/ s H  u  p#UPM	     snn$ [        U 5      $ s  snnf )Nr   )r2   rA   sortedr   rO   r   )r   r,   rQ   rR   s       r-   
make_stubsAScriptMeta.__init__.<locals>.init_then_script.<locals>.make_stubs:  sT    v,CsJ//.4S\\5G5G5I.JK.Jda.JKK7??  Ls   A )share_types_actual_script_module)_parameters_buffers_modules)r[   r   r2   r}   jit
_recursivecreate_script_moduler?   r   _concrete_typeget_attributesdelattrget_modules)rJ   argskwargsnum_methodsadded_methods_in_initr   concrete_typer;   _r,   original_inits            r-   init_then_script-ScriptMeta.__init__.<locals>.init_then_script2  s    cll+K$000$'$5$C!DzS @ II((==6K2K >  + !% : : I I)88:DD' ;,88:GDD'  ;CDD' D/ !r/   )r   setr:   r   reversedrO   unionr   r   r   r   original_methodrs   r|   rK   	functoolswraps)r,   r;   basesattrsbaserQ   rR   base_constantsr   r   r>   s   `        @r-   rK   ScriptMeta.__init__  s5   ') or!BCUODj"5;;="#Q >")$0@#%"HN!$!3!3!9!9.!IC	 $ 5;;=)DA!-..Q;<Q..778 *
 3.66 GT%0Z1BC		'	( 
(	(> (e,r/   r5   rs   rt   ru   rv   rK   rw   r   r   s   @r-   r   r     s    :- :-r/   r   c                       \ rS rSrS rSrg)_CachedForwardiV  c                 $    U R                  S5      $ )Nforward)__getattr__)rJ   objr,   s      r-   __get___CachedForward.__get__W  s    	**r/   r5   N)rs   rt   ru   rv   r   rw   r5   r/   r-   r   r   V  s    +r/   r   c                       \ rS rSrSrg)ScriptWarningi[  r5   Nrs   rt   ru   rv   rw   r5   r/   r-   r   r   [  s    r/   r   c                     [         (       d  U $ [        R                  " SS9n[        X R                  SS9n[        XU 5      $ )N   	frames_upr   )	self_name)r   _jit_internal!createResolutionCallbackFromFramer   rs   r   )fn_rcbasts      r-   script_methodr   _  s;    8	 ::QGD
b++
@CDr**r/   c                        \ rS rSrS rS rSrg)ConstMapis  c                     Xl         g r4   const_mapping)rJ   r   s     r-   rK   ConstMap.__init__t  s    *r/   c                      U R                   U   $ r4   r   )rJ   attrs     r-   r   ConstMap.__getattr__w  s    !!$''r/   r   N)rs   rt   ru   rv   rK   r   rw   r5   r/   r-   r   r   s  s    +(r/   r   importerscript_module_idreturnc                 d   [        U R                  [        R                  R                  5      (       d  [        S5      e[        R                  R                  5       n[        R                  R                  UU R                  U R                  [        U R                  5      U5      n[        U5      $ )z
Call 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.)r   
zip_readerr}   r~   PyTorchFileReaderra   CompilationUnit_import_ir_module_from_packagestorage_contextr$   last_map_locationr   )r   r   cu
cpp_modules       r-   unpackage_script_moduler   {  s     h))588+E+EFFN
 	
 
	!	!	#B88
  h889J :&&r/   )__iter__r]   __neg____mul__rm   __add____sub____pow____truediv____mod____ne____eq____lt____gt____le____ge____and____or____xor__rq   ri   __call____int__	__float____bool____str__	__enter____exit__c                   V   ^  \ rS rSrSrU 4S jrU 4S jrU 4S jrS rS r	S r
S	rU =r$ )
RecursiveScriptClassi  a  Wrapper for a TorchScript class instance for use in Python.

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                 &  > [         TU ]  5         SU R                  S'   Xl        U R                  R	                  5        Vs0 s H.  nUR
                  [        UR                  UR                  5      _M0     snU l	        SU R                  S'   g s  snf )NT_initializingF)
r|   rK   r?   rI   _propertiesr;   propertygettersetter_props)rJ   	cpp_classpropr>   s      r-   rK   RecursiveScriptClass.__init__  s|    G-1DMM/*G
 !GG//11D 		8DKK==1DK
 .3DMM/*s   5Bc                    > U R                   R                  S5      (       a  [        TU ]  U5      $ XR                  ;   a  U R                  U   R                  5       $ [        U R                  U5      $ Nr
  )r?   getr|   r   r  fgetr:   rI   rJ   r   r>   s     r-   r    RecursiveScriptClass.__getattr__  s[    }}  11w*400{{"{{4(--//477D))r/   c                    > U R                   R                  S5      (       a  [        TU ]  X5      $ XR                  ;   a  U R                  U   R                  U5      $ [        U R                  X5        g r  )r?   r  r|   __setattr__r  fsetrh   rI   rJ   r   r1   r>   s      r-   r   RecursiveScriptClass.__setattr__  sZ    }}  11w*477{{"{{4(--e44DGGT)r/   c                     U R                   R                  U5      (       d  [        eU R                  U5      nU" U0 UD6$ r4   )rI   _has_method	TypeErrorr   rJ   method_namer   r   self_methods        r-   forward_magic_method)RecursiveScriptClass.forward_magic_method  s<    77&&{33**;7K///r/   c                 .    [         R                  " S5      e)NzScriptClasses cannot be pickledr(   r\   s    r-   __getstate__!RecursiveScriptClass.__getstate__  s    $$%FGGr/   c                     U R                   R                  S5      (       a  U R                  SU5      $ U R                  SU5      $ )N__iadd__r   )rI   r  r$  )rJ   others     r-   r*  RecursiveScriptClass.__iadd__  s=    ww"":..00UCC00EBBr/   )rI   r  )rs   rt   ru   rv   __doc__rK   r   r  r$  r'  r*  rw   r   r   s   @r-   r  r    s.    		3	*	*	0	H	C 	Cr/   r  c                 6    U R                   " [        /UQ70 UD6$ r4   )r$  r"  rJ   r   r   s      r-   method_templater0    s    ,,[J4J6JJr/   c                      ^  \ rS rSr% Sr/ SQrSU 4S jjr\" 5       r\	S\
4   \S'   U 4S jrU 4S jrS	 rS
 rS\4S jrSrU =r$ )r   i  a  Wrapper for C++ torch::jit::Module with methods, attributes, and parameters.

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                 "   > [         TU ]  5         g r4   r|   rK   )rJ   r>   s    r-   rK   ScriptModule.__init__      Gr/   .r   c                 n   > SU R                   ;  a  [        TU ]	  U5      $ [        U R                  U5      $ )Nr   )r?   r|   r   r:   r   r  s     r-   r   ScriptModule.__getattr__  s2    &dmm;w*400455t<<r/   c                 :  > SU R                   ;  at  [        U[        5      (       aP  SU R                  R                   ;  a  0 U R                  l        UR
                  U R                  U'   UR                  n[        TU ]!  X5      $ [        U R                  X5        g )Nr   __annotations__)r?   r   r0   r>   r>  r2   r1   r|   r  rh   r   r  s      r-   r  ScriptModule.__setattr__  s{    &dmm; eY//
 )0G0GG9;616D((.!KKEw*477D..<r/   c                 "   SU R                   ;   a  U R                  R                  U5      $ [        R                  " SS9n[
        R                  R                  U5      n[        X#S 5      U R                  UR                  5       R                  '   g )Nr   r#   r   )r?   r   definer   r   r}   r~   _parse_source_defr   r   r;   )rJ   srcrcbr   s       r-   rA  ScriptModule.define/  sl    &$--7 1188==  AAANC((,,S1C-=c-MDMM#((*//*r/   c                 6    U R                   R                  5       $ r4   )r   _replicate_for_data_parallelr\   s    r-   rG  )ScriptModule._replicate_for_data_parallelE  s    --JJLLr/   exporterc                     UR                  5       nUR                  R                  U R                  [	        U5      5        [
        U44$ )ap  Save a ScriptModule inside of a ``torch.package`` archive.

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.
)get_unique_idscript_module_serializer	serializerI   intr   )rJ   rI  r   s      r-   __reduce_package__ScriptModule.__reduce_package__H  sB      (557--77EUAVW+.>-@AAr/   r5   r   N)rs   rt   ru   rv   r-  __jit_unused_properties__rK   r   r   r   r   r>  r   r  rA  rG  r    rO  rw   r   r   s   @r-   r   r     sW    	%
!	 '5&6#s(#6	=
	=(	N,	M	B 	B 	Br/   r   )	metaclassc                   0  ^  \ rS rSrSrSrU 4S jr\S 5       r\S 5       r	S r
\S 5       r\S	 5       r\S
 5       r\S 5       rS rS rS rS rS rS rS r\S 5       rS rU 4S jrU 4S jrS rS rS rS rS rS r S r!U 4S jr"S r#S  r$S!r%U =r&$ )"RecursiveScriptModuleiV  a  Retain the existing isinstance(ScriptModule) behavior.

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                 d   > SU R                   S'   Xl        [        TU ]  5         [	        U S5        g )NTr
  training)r?   rI   r|   rK   r   )rJ   r   r>   s     r-   rK   RecursiveScriptModule.__init__t  s-    -1DMM/* GG D*%r/   c                 V    [        U 5      nU" U5        [         R                  U5        U$ )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.
)rU  _finalize_scriptmodule)r   init_fnscript_modules      r-   
_construct RecursiveScriptModule._construct}  s,     2*=MM" "88G  r/   c                 8   [        [        R                  R                  U R                  5      5      U l        [        [        R                  R                  U R                  5      5      U l        [        U R                  U R                  5      U l	        SU l
        g )NF)rE   r}   r~   ParameterDictrI   r   
BufferDictr   ry   r   r
  r\  s    r-   rZ  ,RecursiveScriptModule._finalize_scriptmodule  sx    (:&&}'7'78)M% &8##M$4$45&M" &7  -"8"8&M" +0M'r/   c                 J   U R                  U5        [        R                  R                  R	                  U R
                  R                  5       5      U l        0 n[        R                  R                  U R
                  5      R                  5        H  u  p1[        U5      X#'   M     [        U R
                  U5      U l        [        [        R                  R                  U R
                  5      5      U l        [        [        R                  R!                  U R
                  5      5      U l        U R$                  R                  5        VVs0 s H2  u  pE['        U[        R                  R(                  5      (       a  M0  XE_M4     snnU l        SU R$                  S'   gs  snnf )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.
Fr
  N)rK   r}   r~   ConcreteModuleTypefrom_jit_typerI   _typer   r   rO   r   ry   r   rE   r`  r   ra  r   r?   r   ScriptMethod)rJ   r   modulesr;   rQ   rR   s         r-   _reconstruct"RecursiveScriptModule._reconstruct  s)    MM*% #((("="="K"K#D
 G$)HH$7$7$@$F$F$H  /
 ; %I-dggw?DM  2%((2H2H2QRD.uxx/B/B477/KLDM
 !MM//11DA!!UXX%:%:; 1DM
 .3DMM/*s   /F Fc                 L    U R                   R                  S5      R                  $ )z~Return a string representation of the internal graph for the ``forward`` method.

See :ref:`interpreting-graphs` for details.
r   )rI   _get_methodr4  r\   s    r-   r4  RecursiveScriptModule.graph  s     77&&y1777r/   c                 .    U R                   R                  $ )z
Return 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   r5  r\   s    r-   r5  #RecursiveScriptModule.inlined_graph  s     <<---r/   c                 .    U R                   R                  $ )z
Return a pretty-printed representation (as valid Python syntax) of the internal graph for the ``forward`` method.

See :ref:`inspecting-code` for details.
)r   r2  r\   s    r-   r2  RecursiveScriptModule.code  s     <<$$$r/   c                 T    U R                   R                  nUS   [        US   5      4$ )a\  Return a tuple.

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   r3  r   r   s     r-   r3  )RecursiveScriptModule.code_with_constants  s*     00AaD(1Q4.))r/   c                 N    U R                   R                  " [        U5      40 UD6$ )a1  Save with a file-like object.

save(f, _extra_files={})

See :func:`torch.jit.save <torch.jit.save>` which accepts a file-like object.
This function, torch.save(), converts the object to a string, treating it as a path.
DO NOT confuse these two functions when it comes to the 'f' parameter functionality.
)rI   savestr)rJ   fr   s      r-   rv  RecursiveScriptModule.save  s      77<<A1&11r/   c                 :    U R                   R                  " U0 UD6$ )a&  Add (or update) the bytecode session to the script model.

_save_for_lite_interpreter(f)

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

)rI   _save_for_mobiler/  s      r-   _save_for_lite_interpreter0RecursiveScriptModule._save_for_lite_interpreter  s     77++T<V<<r/   c                 :    U R                   R                  " U0 UD6$ r4   )rI   _save_to_buffer_for_mobiler/  s      r-   $_save_to_buffer_for_lite_interpreter:RecursiveScriptModule._save_to_buffer_for_lite_interpreter  s    7755tFvFFr/   c                 :    U R                   R                  " U0 UD6$ r4   )rI   save_to_bufferr/  s      r-   r  $RecursiveScriptModule.save_to_buffer	  s    77))4:6::r/   c                 6    U R                   R                  5       $ r4   )rI   get_debug_stater/  s      r-   r  %RecursiveScriptModule.get_debug_state  s    77**,,r/   c                      SU R                    3$ )Nzoriginal_name=)r6  r\   s    r-   
extra_repr RecursiveScriptModule.extra_repr  s    #D$6$6#788r/   c                 B    U R                   R                  " U /UQ70 UD6$ r4   )r   	graph_forr/  s      r-   r  RecursiveScriptModule.graph_for  s!    <<))$@@@@r/   c                     [        U 5      [        U R                  R                  5       R	                  5       5      :X  a  g[        U R                  R                  5       R	                  5       5      $ N )r2   rw  rI   rg  r;   r\   s    r-   r6  #RecursiveScriptModule.original_name  sG    DzS!5!5!788tww}}++-..r/   c                 x    [         R                  " SS9nU R                  R                  U R                  X5        g )Nr#   r   )r   r   rI   _definer   )rJ   rC  rD  s      r-   rA  RecursiveScriptModule.define  s,      AAANCGGOOD//:r/   c                   > SU R                   ;  a  [        S5      eU R                  (       a  [        TU ]  U5      $ XR
                  ;   a  U R
                  U   $ U R                  R                  U5      (       a  U R                  R                  U5      $ U R                  R                  U5      (       a+  U R                  R                  U5      nX R                   U'   U$ [        TU ]  U5      $ )Nr
  zKScriptModule has not been initialized, did you forget to call super's init?)r?   ra   r
  r|   r   r   rI   rA   r:   r  rm  )rJ   r   r   r>   s      r-   r   !RecursiveScriptModule.__getattr__'  s    dmm3"a  !!w*400 }}$}}T**&&wwt,,$$T** $ 3 3D 9 '4d#$$7&t,,r/   c                   > U R                   (       a  [        TU ]	  X5      $ XR                  ;   a  X R                  U'   g U R                  R                  U5      (       a  U R                  R                  X5        g [        U S5      (       a=  XR                  R                  5       R                  5       ;   a  [        SU SU S35      e[        TU ]	  X5      $ )Nr   z+Cannot mutate TorchScript constant value: 'z'. Value: '')r
  r|   r  r   rI   rA   rh   r   get_constantsrS   AttributeErrorr  s      r-   r  !RecursiveScriptModule.__setattr__?  s    !!w*477}}$&+d#&&,.////==?DDFF %A${SXRYYZ[  w*477r/   c                     [         R                  R                  R                  [        R                  " U R
                  5      5      $ r4   )r}   r   r   r   copyrI   r\   s    r-   __copy__RecursiveScriptModule.__copy__Z  s*    99''77		$''8JKKr/   c                     [         R                  R                  R                  [        R
                  " U R                  U5      5      $ r4   )r}   r   r   r   r  deepcopyrI   )rJ   memos     r-   __deepcopy__"RecursiveScriptModule.__deepcopy__]  s,    99''77dggt8TUUr/   c                 r    [        X5      n[        USS 5      [        [        U5      :X  a  [        eU" U0 UD6$ )N__func__)r:   rU  NotImplementedErrorr!  s        r-   r$  *RecursiveScriptModule.forward_magic_methodd  sA    !$4K{J5%{:  *)///r/   c                 $    U R                  S5      $ )Nr   r$  r\   s    r-   r   RecursiveScriptModule.__iter__l  s    ,,Z88r/   c                 &    U R                  SU5      $ )Nrq   r  )rJ   idxs     r-   rq   !RecursiveScriptModule.__getitem__o  s    ,,]C@@r/   c                 $    U R                  S5      $ )Nr]   r  r\   s    r-   r]   RecursiveScriptModule.__len__r  s    ,,Y77r/   c                 &    U R                  SU5      $ )Nrm   r  )rJ   keys     r-   rm   "RecursiveScriptModule.__contains__u  s    ,,^SAAr/   c                    > U R                   nUR                  [        [        S5      :X  a  [        TU ]  5       $ U" 5       $ )N__dir__)r  r  r<   rU  r|   )rJ   r#  r>   s     r-   r  RecursiveScriptModule.__dir__z  s=    ,,K$$*+@)LM w((= r/   c                 f    U R                   nUR                  [        [        S5      :X  a  gU" 5       $ )Nr  T)r  r  r<   rU  )rJ   r#  s     r-   r  RecursiveScriptModule.__bool__  s2    --K$$*+@*MN = r/   c                 d    S n[         R                  U R                  R                  5       U5      $ )Nc                     g r4   r5   rb  s    r-   r[  CRecursiveScriptModule._replicate_for_data_parallel.<locals>.init_fn  s    r/   )rU  r]  rI   rG  )rJ   r[  s     r-   rG  2RecursiveScriptModule._replicate_for_data_parallel  s.     )33446 r/   )r?   r   rI   r   r   r   )'rs   rt   ru   rv   r-  r   rK   staticmethodr]  rZ  rj  r  r4  r5  r2  r3  rv  r|  r  r  r  r  r  r6  rA  r   r  r  r  r$  r   rq   r]   rm   r  r  rG  rw   r   r   s   @r-   rU  rU  V  s   	0  $	& 
	! 
	!, 

	0 

	0	3@ 
	8 
	8 
	. 
	. 
	% 
	% 
	* 
	*		2	=	G	;	-	9	A 
	/ 
	/

	;	-0	86	L	V	0	9	A	8	B
	!	!		 		r/   rU  __c                 6   ^ SS K mTR                  " U U4S jS9$ )Nr   c                 Z   > TR                   " U 5      =(       d    TR                  " U 5      $ r4   )
isfunctionismethod)xinspects    r-   r   _get_methods.<locals>.<lambda>  s#    W%7%7%:%Qg>N>Nq>Q%Qr/   )	predicate)r  
getmembers)r,   r  s    @r-   _get_methodsr    s!     !!Q
 	
r/   >%   tocpucudaevalhalfr2   applyfloattrain_applydoublebuffersr   ri  children	_get_name	zero_grad
add_moduler  
parameters
state_dictshare_memory_slow_forward_tracing_namenamed_buffersnamed_modules_named_membersnamed_childrenget_extra_stateload_state_dictregister_bufferregister_moduleset_extra_statenamed_parametersregister_parameter_save_to_state_dict_load_from_state_dictc                    ^  U 4S jnU$ )Nc                     > [        TS-   5      e)Nz" is not supported on ScriptModulesr`   )rJ   r   r   r;   s      r-   fail_make_fail.<locals>.fail  s    t&JJKKr/   r5   )r;   r  s   ` r-   
_make_failr    s    	L r/   
_call_implc                       \ rS rSrSrg)r  i  r5   Nr   r5   r/   r-   r  r    s    r/   c                   ,   ^  \ rS rSrSU 4S jjrSrU =r$ )r   i  c                 "   > [         TU ]  5         g r4   r8  rJ   argr>   s     r-   rK   r9    r:  r/   r5   r4   r   r   s   @r-   r   r         	 	r/   c                   ,   ^  \ rS rSrSU 4S jjrSrU =r$ )rU  i  c                 "   > [         TU ]  5         g r4   r8  r  s     r-   rK   rX    r:  r/   r5   r4   r   r   s   @r-   rU  rU    r  r/   c                    [        U [        R                  R                  5      (       d  U $ [	        U 5      nX!;   a  U[	        U 5         $ [        U S5      (       a  U R                  5       OU n XU'   0 nU R                  R                  5        H  u  pEUS:X  a,  UR                  5        H  u  pg[        Xq5      XV'   M     XSU'   M7  [        U[        R                  R                  5      (       a$  [        U[        5      (       d  [        XQ5      X4'   M  XSU'   M     UR                  5        H  u  pgXpR                  W'   M     U $ )N__prepare_scriptable__r   )r   r}   nnr   idrA   r  r?   rO   !call_prepare_scriptable_func_implr   )r   r  obj_idnew_obj_dictr;   
sub_modulerQ   rR   s           r-   r  r    s   c588??++
WF ~BsG} )05M(N(N""$TW 
 LLLL..0:"((* A! J
 +!+
EHHOO44Z>
 >
 "C:!TL!+ 1 ""$T % Jr/   c                     0 n[        X5      $ r4   )r  )r   r  s     r-   call_prepare_scriptable_funcr    s    ')D,S77r/   c                 @    [         R                  R                  U 5      $ )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.
)r}   r~   
ScriptDict)r   s    r-   create_script_dictr  "  s     88s##r/   c                 @    [         R                  R                  U 5      $ )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.
)r}   r~   
ScriptList)r   	type_hints     r-   create_script_listr  2  s     88s##r/   T	_TOPLEVELexample_inputsc                    Ub  [         R                  " S[        SS9  [        U [        5      (       a  U $ [        U [
        5      (       a  U $ [        U [        5      (       a  U $ U(       a  [        5       q[        (       a  [        [        5      n[        U5         [        U[        5      (       a(  UR                  5        H  u  pgU H  nU" U6   M
     M     O/[        U[        5      (       a  U H  n	U " U	6   M
     O[        S5      eS S S 5        O[         R                  " S5        [        U [        R                   R"                  5      (       aW  [%        U 5      n [        R&                  R(                  R+                  U [        R&                  R(                  R,                  5      $ [/        U S5      (       a  U R1                  5       OU n [        U [        5      (       a  [3        U 5      $ [        U [        5      (       a  [5        U 5      $ [6        R8                  " U 5      (       a  [;        U 5      n
[=        U [        R                   R"                  5      (       a  [?        SU  S35      e[=        U [@        RB                  5      (       a  U $ [E        U 5      (       d  [?        S	5      e[G        U RI                  5       5      S
:  a  [?        S5      eUc  [J        RL                  " US-   5      n[O        XU
5        U $ [6        RP                  " U 5      (       d  [6        RR                  " U 5      (       Ga  [;        U 5      n
[/        U S5      (       a"  U RT                  n [J        RV                  " U 5      n[/        U S5      (       a  [?        SU RX                  -   5      e[[        U 5        []        U 5      nU(       a  Xl/        U$ [a        X Rb                  5      nUc  [J        RV                  " U 5      n[        Rd                  Rg                  XU[i        U 5      5      nU Rj                  Ul5        SUl1        SUl6        Xl/        [o        X5        U$ [        R&                  R(                  Rq                  U 5      $ ! , (       d  f       GNT= f)Nz^`optimize` is deprecated and has no effect. Use `with torch.jit.optimized_execution()` instead   )
stacklevelzError: Unable to infer types. Please format the inputs to type `List[Tuple]` or `Dict[Callable, List[Tuple]]` to be run with MonkeyType.zWarning: 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. r  zType 'zO' 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#   __script_if_tracing_wrapper__script_unsupportedzTorchScript error: r%   r&   )9warningswarnFutureWarningr   r  r   r%   r   r7   r   r   dictrO   list
ValueErrorr}   r  r   r  r   r   r   r   rA   r  r  r  r  isclassr   
issubclassra   enumEnumrC   r[   mror   r   r   r  r  __original_fn#createResolutionCallbackFromClosurer  "_check_directly_compile_overloadedr   _torchdynamo_inliner   rs   r~   _jit_script_compiler   r-  ru   r   create_script_class)r   optimize
_frames_upr   r
  monkeytype_configr   example_inputexampleexamplesqualified_namemaybe_already_compiled_fnr   r   s                 r-   _script_implr)  D  s    A		
 #+,,
#|$$
#~&&

 *+ 2= A!"34nd33 2@1E1E1G-'4G"G, (5 2H  55$2X %3 %W  54& MMi #uxx''*3/yy##88%%>>
 	
 s455 &&( 	 #t!#&&#t!#&&s(- c588??++lm  c499%%J"3''0  swwy>A9  < BB:PQ>RD#C~>
			C	 	 G$4$4S$9$9(-3566##C DDSID 3.//4s7O7OOPP*3/$@$E!$<?9,,#||,< DDSIDXX))'7'<
 [[
&4!$(	yy##77<<K 54s   A-Q**
Q9c                     [         (       d  U $  [        nSq[        U UUS-   UUS9nU(       a  [        S[	        U5      S9  UUq$ ! Wqf = f)a  Script the function.

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().__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) -> None:
                super().__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) -> None:
                super().__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]))
Fr#   )r   r!  r"  r   r
  script)model_id)r   r	  r)  r	   r   )r   r!  r"  r   r
  prevrets          r-   r+  r+    s]    ` 8
	!A~)
 !(]35GH	D	s   3A A	c                     UR                  5        H?  u  p4X0;  d
  X   U:w  d  M  [        R                  R                  R	                  USU 35      e   g )NzDefault parameters on overloads do not affect the runtime so they must equal to the default parameter on the implementation function. Found on parameter )rO   r}   r   frontendFrontendError)impl_defaultsoverload_defaultslocr;   overload_values        r-   _check_overload_defaultsr6    sW     1 7 7 9$(;~(M))$$22!F$  !:r/   c                    [        X R                  5      R                  5       n[        R                  R
                  R                  U S S [        R                  " U 5      5      n[        X"R                  5      n[        U 5      n[        U5      n[        R                  " U5      n[        XvUR                  5       5        [        R                  R                  UUUUUU5      n	U	$ r4   )r   rs   declr}   r   annotationsget_signaturer  r  r   r   r  r6  ranger~   _jit_script_compile_overload)
overload_fn	qual_nameimpl_fnoverload_decloverload_signatureimpl_astr3  implementation_defaultsr   r   s
             r-   _compile_function_with_overloadrD    s    -A-ABGGIM..<<T4!1!1+!> 7$4$45H(5.w7<<WEDM4G4G4I 
	.	.
B Ir/   c                 L   [        U 5      n[        U 5      n[        R                  " U5      nUc  U$ X;   a   [	        [        R
                  " SU 5      5      eU Vs/ s H  n[        XBU 5      PM     nnU(       a  X-   n[        X5        [        R                  " U5        U$ s  snf )Nfunction)	r   r   r   _get_fn_overloadsra   ,get_overload_no_implementation_error_messagerD  r   _clear_fn_overloads)r   existing_compiled_fnsr>  uncompiled_overloadsr=  compiled_fnss         r-   _get_overloadsrM    s    9#>$I(::9E#$$
"FFzSVW
 	
 0/K 	(D/  
 ,; C.%%i0s   B!c                     [        U 5      n[        R                  " U5      (       d  [        U 5      (       a  [	        SU S35      eg )Nz	Function z 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   rG  r   ra   )r   r>  s     r-   r  r    sO    $I&&y115RSV5W5W	{ #F F
 	
 6Xr/   c                 ,   [         R                  " U 5      (       d  [        S5      e[        U 5      (       d  [        S5      e[	        U [
        R                  R                  5      =(       a    [        U R                  5       5      S:H  nU(       d(  [        U R                  5       5      S:  a  [        S5      e[        U 5      n[        R                  " S5      n[        X R                  5      n[
        R                  R!                  X$X15      nXPl        U $ )a  Decorate to annotate classes or modules of different types.

This decorator can be used to define an interface that can be used to annotate
classes or modules of different types. This can be used for to annotate a submodule
or attribute class that could have different types that implement the same
interface, or which could be swapped at runtime; or to store a list of modules or
classes of varying types.

It is sometimes used to implement "Callables" - functions or modules that implement
an interface but whose implementations differ and which can be swapped out.

Example:
.. testcode::

    import torch
    from typing import List

    @torch.jit.interface
    class InterfaceType:
        def run(self, x: torch.Tensor) -> torch.Tensor:
            pass

    # implements InterfaceType
    @torch.jit.script
    class Impl1:
        def run(self, x: torch.Tensor) -> torch.Tensor:
            return x.relu()

    class Impl2(torch.nn.Module):
        def __init__(self) -> None:
            super().__init__()
            self.val = torch.rand(())

        @torch.jit.export
        def run(self, x: torch.Tensor) -> torch.Tensor:
            return x + self.val

    def user_fn(impls: List[InterfaceType], idx: int, val: torch.Tensor) -> torch.Tensor:
        return impls[idx].run(val)

    user_fn_jit = torch.jit.script(user_fn)

    impls = [Impl1(), torch.jit.script(Impl2())]
    val = torch.rand(4, 4)
    user_fn_jit(impls, 0, val)
    user_fn_jit(impls, 1, val)
z$interface must be applied to a classz1TorchScript interfaces must inherit from 'object'r  r   zmTorchScript interface does not support inheritance yet. Please directly inherit from 'object' or 'nn.Module'.r#   )r  r  ra   rC   r  r}   r  r   r[   r  r   r   r   r   rs   r~   _jit_script_interface_compile__torch_script_interface__)r   is_module_interfacer'  rD  r   mangled_classnames         r-   	interfacerT    s    ` ??3ABBs##NOO %S%((//:Rs3779~QR?R3swwy>A#5D
 	

 %S)N

9
9!
<C C
.C>>S &7"Jr/   c                     [        U 5      n[        R                  R                  X!5      n[        R
                  " U 5      n[        XU5      $ r4   )r   r}   r~   	CallStackr   'createResolutionCallbackForClassMethodsr   )r   r4  
_qual_nameerror_stackrD  s        r-   _recursive_compile_classrZ  L  s?     %J (($$Z5K

?
?
DC&s<<r/   spaddingoffsetcharc                     U[        U 5      :  a  U[        U 5      -  nSR                  [        X-   5       Vs/ s H  oCPM     sn5      U -   $ s  snf r  )r[   joinr;  )r[  r\  r]  r^  r   s        r-   padra  Y  sL    #a&3q677%(8"9:"9QD"9:;a??:s   Ac                   F    \ rS rSrSS\S\S\4S jjrS\S\4S jrS	 r	S
r
g)_ScriptProfileColumni_  header	alignmentr]  c                 6    Xl         X l        X0l        0 U l        g r4   )rd  re  r]  rows)rJ   rd  re  r]  s       r-   rK   _ScriptProfileColumn.__init__`  s    "$&	r/   linenor1   c                      X R                   U'   g r4   )rg  )rJ   ri  r1   s      r-   add_row_ScriptProfileColumn.add_rowf  s    !		&r/   c           
         [        U R                  5      n/ nU R                  R                  5        H7  u  p4[	        U5      nUR                  X545        [        [        U5      U5      nM9     U R                  S:  a   XR                  -   nXfU R                  -  -  nOSnU VVs/ s H  u  p5U[        XVU R                  5      4PM     nnn[        U R                  X`R                  5      U4$ s  snnf )Nr   )
r[   rd  rg  rO   rw  appendmaxre  ra  r]  )rJ   
max_lengthrg  r  r1   cellr\  s          r-   materialize _ScriptProfileColumn.materializei  s    %
&())//+JCu:DKK$SY
3J ,
 >>A >>1G//GGHLM93c$56M4;;5t;; Ns   $$C-)re  rd  r]  rg  N)   r   )rs   rt   ru   rv   rw  rN  rK   r   rk  rr  rw   r5   r/   r-   rc  rc  _  s4    's 's ' '"c "# "<r/   rc  c                   8    \ rS rSrS\\   S\\   4S jrS rSr	g)_ScriptProfileTablei{  colssource_rangec                     Xl         X l        g r4   rw  rx  )rJ   rw  rx  s      r-   rK   _ScriptProfileTable.__init__|  s    	(r/   c           	         / n/ nSnU R                    H5  nUR                  5       u  pVX5-  nUR                  U[        U5      45        M7     UR                  U5        UR                  [	        S[        U5      SS5      5        U R                   HS  nSnU H7  u  pVUR                  U5      n	U	c  U[	        S[        U5      5      -  nM3  X-  nM9     UR                  U5        MU     SR                  U5      $ )Nr  r   =
)	rw  rr  rn  r  ra  r[   rx  r  r`  )
rJ   outputscellsheader_buffercolrd  rg  line
row_bufferrq  s
             r-   dump_string_ScriptProfileTable.dump_string  s    2499C??,LF#MLL&$t*-. 
 	}%s2s=11c:;%%DJ %xx~<#b#f+"66J&J !& NN:& & yy!!r/   rz  N)
rs   rt   ru   rv   r  rc  rN  rK   r  rw   r5   r/   r-   rv  rv  {  s$    )T"67 )tCy )"r/   rv  c                   >    \ rS rSrS
S jrS rS rS\4S jrS r	S	r
g)_ScriptProfilei  r   Nc                 J    [         R                  R                  5       U l        g r4   )r   	profilingr  profiler\   s    r-   rK   _ScriptProfile.__init__  s    ((779r/   c                 8    U R                   R                  5         g r4   )r  enabler\   s    r-   r  _ScriptProfile.enable  s    r/   c                 8    U R                   R                  5         g r4   )r  disabler\   s    r-   r  _ScriptProfile.disable  s    r/   c                 b   / nU R                   R                  5        GHy  nUR                  5       nUR                  5       R	                  5       n[        S U 5       5      nU Vs/ s H  ofUS  PM	     nnUR                  5       nU[        U5      -   n[        Xx5      n	[        S5      n
[        S5      n[        S5      n[        SSS5      nUR                  5       nU	 H~  nU
R                  Xf5        UR                  XdXg-
     5        UR                  U5      nUc  M@  UR                  XoR                  5       5        UR                  XoR                  5       5        M     [        XX/[!        U	5      5      nUR#                  UR%                  5       5        GM|     SR'                  U5      $ s  snf )	Nc              3   n   #    U  H+  n[        U5      [        UR                  S 5      5      -
  v   M-     g7f) N)r[   lstrip).0r  s     r-   	<genexpr>-_ScriptProfile.dump_string.<locals>.<genexpr>  s'     T|tTSS)9%::|s   35zLine #Hitsz	Time (ns)zLine Contentsr   r#   z

)r  _dump_statssourcetext
splitlinesminstarting_linenor[   r;  rc  line_maprk  r  countduration_nsrv  r  rn  r  r`  )rJ   r  source_stats
source_refsource_linesdedentr  
start_lineend_linerx  ri  hitstime_nsline_contentsstatsstattables                    r-   r  _ScriptProfile.dump_string  sy    LL446L%,,.J%??,779LT|TTF6BCldMlLC#335J!C$55H 6L)(3F'/D*;7G0!QGM ))+E$t*%%d9J,KLyy#LLzz|4OOD*:*:*<= % (w6\8JE NN5,,./3 74 {{7##- Ds   %F,c                 6    [        U R                  5       5        g r4   )printr  r\   s    r-   dump_ScriptProfile.dump  s    d !r/   )r  rQ  )rs   rt   ru   rv   rK   r  r  rw  r  r  rw   r5   r/   r-   r  r    s"    :$S $<"r/   r  c                     U c   S5       eU $ )NzUnwrapping null optionalr5   )r  s    r-   _unwrap_optionalr    s    =444=Hr/   zaten::_unwrap_optionalzaten::is_scriptingzaten::has_torch_functionr4   )Nr   NN)r   r  )r-  collectionsr  r  r   r  r)   r  typingr   r   r   r}   torch._jit_internalr   torch._classesr   r   r   torch._utils_internalr	   torch.jit._builtinsr
   torch.jit._fuserr   r   torch.jit._monkeytype_configr   r   r   torch.jit._recursiver   r   r   r   torch.jit._stater   r   r   r   r   torch.jit.frontendr   r   r   torch.nnr   torch.overridesr   r   r   torch.packager    r!   torch.utilsr"   _serializationr$   r7   r~   rh  r  r%   rs   ru   r.   
__reduce__
namedtupler0   r8   r<   rC   rE   ry   r2   r   r   Warningr   r   r   rw  r  r   _magic_methodsr  r"  r0  rh   r   rU  r?   rO   r;   itemcallabler   r  
startswithrA   r  _compiled_methods_allowlistr  methodendswithr  r  r  r  r	  boolr>  r  tupler  r)  r+  r6  rD  rM  r  rT  rZ  r   rN  ra  rc  rv  r  r  is_scriptingr5   r/   r-   <module>r     sg          ' '  + " > 7 1 A 
   P O  
 ; " 1 "#":   $.   !((  + 8  
>; '
A $  &&{Wf4EFII	 X$C( "  "F&'* &'b;- ;-|+ +
	G 	+(( (''14'
XX__'0 N>=C =C~ &	K 	$k?C &SBv SBjB BR
 ,44::<
d~~jx&@&@??4  GL$$?$? 	dD) =
&#P %UXX__5f??4  DMM,$?$?-66677)6??Jt<LM 6 uxx  
#L8
$ $ 	4 
 	LPF=
 $u+tHd5k,A'BDHIF=V 	LPc
 $u+tHd5k,A'BDHIcT.6
K\= ((** 
?K (@3 @ @c @S @< <8" "8)" )"X
 "$< = -,,.B C $&@ A *,F G -/I Jr/   