
    
i/
                    *   U d Z ddlZddlZddlZddlZddlZddlZddlZddlZddl	m
Z
mZmZmZ ddlmZmZmZ ddlmZmZ ddlZddlmZ ddlmZ ddlmZmZ ddlmZ dd	lmZ dd
l m!Z!m"Z" ddl#m$Z$m%Z%m&Z& ddl'm(Z(m)Z)m*Z*m+Z+ ddl,m-Z-m.Z.m/Z/m0Z0m1Z1 ddl2m3Z3m4Z4m5Z5 ddl6m7Z7 ddl8m9Z9m:Z:m;Z; ddl<m=Z=m>Z> ddl?m@Z@ ddlAmBZB  ed      ZC e%       aDe"ej                  j                  _G        e!ej                  j                  _G        ej                  j                  ZHdeH_         deH_I        deH_J         e@eHd       d ZKeKeH_L        e-r ej                  dddg      ZNnd ZNdeN_         d  ZOd! ZPd" ZQ G d# d$      ZR G d% d&eR      ZS G d' d(eT      ZU G d) d*      ZV G d+ d,eW      ZXd- ZY G d. d/      ZZd0e>d1e[d2ej                  jn                  fd3Z]e-rg d4Z^ G d5 d6      Z_e^D ]  Z`d7 Za ebe_e`ea         G d8 d9e7eU:      Zc G d; d<ec      Zdedj                  j                         D ]<  \  ZgZh eieh      s
 ejehek      segj                  d=      s	 emeceg      r3 ebecegeh       > d> Znh d?Zod@ Zp enej                  jn                        D ]V  \  ZgZqegj                  d=      segj                  dA      r)egedj                  vs8egeovs= ebedeqj                   epeg             X n4 G dB d6      Z_ G dC d9ej                  jn                        Zc G dD d<ec      ZddE ZsdF ZtdG ZudgdHZvdIawexeydJ<   	 	 	 	 dhdKeeze{   e|e
eze{   f   df   fdLZ}	 	 	 	 dhdMedNddOe~dPe
e[gef   dz  dKeeze{   e|e
eze{   f   df   d2efdQZdR ZdS ZdT ZdU ZdMeCd2eCfdVZdW Zej                  j                  Z e@ed       didXe[dYe~dZe~d[e[fd\Z G d] d^      Z G d_ d`      Z G da db      Zdc Z eedd        eej                  de        ee9df        ee:df        ee;df       y)jzTorchScript.

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)CallableIteratorMappingSequence)AnyTypeVarUnion)
deprecatedSelf)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_location_Tz
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                 ,    t        j                  d      )Nz ScriptFunction cannot be pickledpicklePickleErrorclss    b/var/www/vps2.regionflexible.com/Desarrollo/venv/lib/python3.12/site-packages/torch/jit/_script.py_reducer5   O   s    


?
@@    	Attributevaluetypec                     | S N )r8   r9   s     r4   r7   r7   Z   s    r6   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                      t         S r;   )type_trace_dbr<   r6   r4   _get_type_trace_dbr?      s    r6   c                     t        | |d       S r;   )getattr)r3   names     r4   _get_function_from_typerC      s    3d##r6   c                 R    t        | d      rdt        |       v xs t        | d      S y )N	__class____dict__	__slots__)hasattrdirr2   s    r4   _is_new_style_classrJ      s,    sK SX%Bk)BB !r6   c                   B    e Zd Zd Zd Zd Zd Zd Zd Zd Z	d Z
d	 Zy
)OrderedDictWrapperc                     || _         y r;   )_c)selfrN   s     r4   __init__zOrderedDictWrapper.__init__   s	    r6   c                 T    | j                         D cg c]  \  }}|	 c}}S c c}}w r;   itemsrO   kvs      r4   keyszOrderedDictWrapper.keys        "jjl+da+++   $c                 T    | j                         D cg c]  \  }}|	 c}}S c c}}w r;   rR   rT   s      r4   valueszOrderedDictWrapper.values   rX   rY   c                 4    t        | j                               S r;   )lenr[   rO   s    r4   __len__zOrderedDictWrapper.__len__   s    4;;=!!r6   c                     t        d      )Nz6cannot delete methods or parameters of a script moduleRuntimeErrorrO   rU   s     r4   __delitem__zOrderedDictWrapper.__delitem__   s    STTr6   c                 6    | j                   j                         S r;   )rN   rS   r^   s    r4   rS   zOrderedDictWrapper.items   s    ww}}r6   c                 `    || vrt        d|       | j                  j                  ||       y )NzICan't add a new parameter after ScriptModule construction. Tried to add ')rb   rN   setattrrT   s      r4   __setitem__zOrderedDictWrapper.__setitem__   s6    D=[\][^_  	1r6   c                 8    | j                   j                  |      S r;   )rN   containsrc   s     r4   __contains__zOrderedDictWrapper.__contains__   s    ww""r6   c                 V    || vrt        |      | j                  j                  |      S r;   )KeyErrorrN   rA   rc   s     r4   __getitem__zOrderedDictWrapper.__getitem__   s&    D=1+wwq!!r6   N)__name__
__module____qualname__rP   rW   r[   r_   rd   rS   rh   rk   rn   r<   r6   r4   rL   rL      s0    ,,"U#"r6   rL   c                   6     e Zd Z fdZd Zd Zd Zd Z xZS )OrderedModuleDictc                 l    t         |   t        j                  j	                  |             || _        y r;   )superrP   torch_C
ModuleDict_python_modules)rO   modulepython_dictrE   s      r4   rP   zOrderedModuleDict.__init__   s)    ,,V45  +r6   c                 :    | j                   j                         }|S r;   )ry   rS   rO   rs     r4   rS   zOrderedModuleDict.items   s      &&(r6   c                     || j                   v S r;   ry   rc   s     r4   rk   zOrderedModuleDict.__contains__   s    D((((r6   c                     t        |t              r,| j                  j                  ||       || j                  |<   y t        d| d|       )NzgCannot re-assign modules in a ScriptModule with non-scripted module, tried to replace existing module 'z': )
isinstanceScriptModulerN   rg   ry   rb   rT   s      r4   rh   zOrderedModuleDict.__setitem__   sS     a&GGOOAq!&'D  #==>Cs1#G r6   c                      | j                   |   S r;   r   rc   s     r4   rn   zOrderedModuleDict.__getitem__  s    ##A&&r6   )	ro   rp   rq   rP   rS   rk   rh   rn   __classcell__rE   s   @r4   rs   rs      s    +)&'r6   rs   c                        e Zd Z fdZ xZS )
ScriptMetac                    	 i  _         t        t         dd             _        t	        |      D ]i  }t        |di       j                         D ]  \  }}| j                   |<    t        |dt                     } j                  j                  |       _        k t        |j                               D ]E  \  }}t        |t              st         |       | j                   |j                  j                  <   G t         dd      rt        
 9  |||       y t         dd       	t        j                   	       	fd	       }| _        t        
 9  |||       y )
N__constants__r<   _methods_constants_set_disable_script_metaFrP   c                      y r;   r<   r^   s    r4   <lambda>z%ScriptMeta.__init__.<locals>.<lambda>6  s    r6   c                    t        	j                        } 
| g|i | t        	j                        |kD  }t        |       	u rd }t        j                  j
                  j                  | ||       | j                  d<   | j                  j                  }|j                         D ]  }t        | |        |j                         D ]  \  }}t        | |        dD ]  }t        | |        y y )Nc                     t        |       }t        |d      r6t        |j                  j	                               D cg c]  \  }}|	 c}}S t        |       S c c}}w )Nr   )r9   rH   sortedr   rS   r   )rz   r3   rU   rV   s       r4   
make_stubszAScriptMeta.__init__.<locals>.init_then_script.<locals>.make_stubs@  sM    v,CsJ/.4S\\5G5G5I.JKdaKK7??  Ls   A)share_types_actual_script_module)_parameters_buffers_modules)r]   r   r9   rv   jit
_recursivecreate_script_modulerF   r   _concrete_typeget_attributesdelattrget_modules)rO   argskwargsnum_methodsadded_methods_in_initr   concrete_typerB   _r3   original_inits            r4   init_then_scriptz-ScriptMeta.__init__.<locals>.init_then_script8  s    cll+K$000$'$5$C!DzS @ II((==j:O6O >  56 !% : : I I)88: (DD$'(,88: (GD!D$'(C (DD$'(/ !r6   )r   setrA   r   reversedrS   unionr   r   r   r   original_methodro   ru   rP   	functoolswraps)r3   rB   basesattrsbaserU   rV   base_constantsr   r   rE   s   `        @r4   rP   zScriptMeta.__init__  sH   ') or!BCUO 	JDj"5;;= $1"#Q$")$0@#%"HN!$!3!3!9!9.!IC		J 5;;=) 	=DAq!-.Q;<Q..778	=
 3.6 GT5%0Z1BC		'	( 
(	(> (ue,r6   ro   rp   rq   rP   r   r   s   @r4   r   r     s    :- :-r6   r   c                       e Zd Zd Zy)_CachedForwardc                 $    | j                  d      S )Nforward)__getattr__)rO   objr3   s      r4   __get__z_CachedForward.__get__]  s    	**r6   N)ro   rp   rq   r   r<   r6   r4   r   r   \  s    +r6   r   c                       e Zd Zy)ScriptWarningNro   rp   rq   r<   r6   r4   r   r   a  s    r6   r   c                    t         j                  dk\  rt        j                  dt               nt        j                  dt               t
        s| S t        j                  d      }t        | | j                  d      }t        |||       S )N      z}`torch.jit.script_method` is not supported in Python 3.14+ and may break. Please switch to `torch.compile` or `torch.export`.z\`torch.jit.script_method` is deprecated. Please switch to `torch.compile` or `torch.export`.   	frames_upr   )	self_name)sysversion_infowarningswarnDeprecationWarningr   _jit_internal!createResolutionCallbackFromFramer!   ro   r   )fn_rcbasts      r4   script_methodr   e  sv    
7"B	
 	j	
 	 ::QGD
b"++
@CD#r**r6   c                   6    e Zd Zdeeef   ddfdZdedefdZy)ConstMapconst_mappingreturnNc                     || _         y r;   r   )rO   r   s     r4   rP   zConstMap.__init__  s
    *r6   attrc                      | j                   |   S r;   r   )rO   r   s     r4   r   zConstMap.__getattr__  s    !!$''r6   )ro   rp   rq   r   strr   rP   r   r<   r6   r4   r   r     s1    +gc3h&7 +D +( ( (r6   r   importerscript_module_idr   c                 Z   t        | j                  t        j                  j                        st        d      t        j                  j                         }t        j                  j                  || j                  | j                  t        | j                        |      }t        |      S )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_readerrv   rw   PyTorchFileReaderrb   CompilationUnit_import_ir_module_from_packagestorage_contextr*   last_map_locationr   )r   r   cu
cpp_modules       r4   unpackage_script_moduler     s     h))588+E+EFN
 	
 
	!	!	#B88
  h889J :&&r6   )__iter__r_   __neg____mul__rk   __add____sub____pow____truediv____mod____ne____eq____lt____gt____le____ge____and____or____xor__rn   rh   __call____int__	__float____bool____str__	__enter____exit__c                   |     e Zd ZdZ fdZdedef fdZdededdf fdZd	ed
ededefdZ	d Z
dedefdZ xZS )RecursiveScriptClassaX  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         |           d| j                  d<   || _        | j                  j	                         D ci c]-  }|j
                  t        |j                  |j                        / c}| _	        d| j                  d<   y c c}w )NT_initializingF)
ru   rP   rF   rN   _propertiesrB   propertygettersetter_props)rO   	cpp_classproprE   s      r4   rP   zRecursiveScriptClass.__init__  sy    G-1DMM/*DG
 !GG//1 		8DKK==DK
 .3DMM/*s   2Br   r   c                     | j                   j                  d      rt        |   |      S || j                  v r| j                  |   j                         S t        | j                  |      S Nr   )rF   getru   r   r  fgetrA   rN   rO   r   rE   s     r4   r   z RecursiveScriptClass.__getattr__  sZ    }}  1w*400t{{"{{4(--//477D))r6   r8   Nc                     | j                   j                  d      rt        |   ||      S || j                  v r| j                  |   j                  |      S t        | j                  ||       y r	  )rF   r
  ru   __setattr__r  fsetrg   rN   rO   r   r8   rE   s      r4   r  z RecursiveScriptClass.__setattr__  s]    }}  1w*477t{{"{{4(--e44DGGT5)r6   method_namer   r   c                 v    | j                   j                  |      st        | j                  |      } ||i |S r;   )rN   _has_method	TypeErrorr   rO   r  r   r   self_methods        r4   forward_magic_methodz)RecursiveScriptClass.forward_magic_method  s;     77&&{3**;7K///r6   c                 ,    t        j                  d      )NzScriptClasses cannot be pickledr/   r^   s    r4   __getstate__z!RecursiveScriptClass.__getstate__  s    $$%FGGr6   otherc                     | j                   j                  d      r| j                  d|      S | j                  d|      S )N__iadd__r   )rN   r  r  )rO   r  s     r4   r  zRecursiveScriptClass.__iadd__  s:    ww"":.00UCC00EBBr6   )ro   rp   rq   __doc__rP   r   r   r   r  r  r  r   r  r   r   s   @r4   r   r     s{    		3	*C 	*C 	*	*C 	* 	* 	*	0"	0+.	0:=	0	0	H	C$ 	C4 	Cr6   r   c                 6     | j                   t        g|i |S r;   )r  r  rO   r   r   s      r4   method_templater     s    ,4,,[J4J6JJr6   c                        e Zd ZU dZg dZd fdZ e       Zede	f   e
d<   dede	f fd	Zded
e	ddf fdZd Zd ZdefdZ xZS )r   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_namer   Nc                 "    t         |           y r;   ru   rP   )rO   rE   s    r4   rP   zScriptModule.__init__$      Gr6   .r   r   c                 j    d| j                   vrt        | 	  |      S t        | j                  |      S )Nr   )rF   ru   r   rA   r   r  s     r4   r   zScriptModule.__getattr__)  s2    &dmm;w*400455t<<r6   r8   c                 ,   d| j                   vrnt        |t              rNd| j                  j                   vri | j                  _        |j
                  | j                  |<   |j                  }t        | !  ||      S t        | j                  ||       y )Nr   __annotations__)rF   r   r7   rE   r,  r9   r8   ru   r  rg   r   r  s      r4   r  zScriptModule.__setattr__.  s|    &dmm; eY/
 )0G0GG9;616D((.!KKEw*477D..e<r6   c                 $   d| j                   v r| j                  j                  |      S t        j                  d      }t
        j                  j                  |      }t        ||d       | j                  |j                         j                  <   y )Nr   r)   r   )rF   r   definer   r   rv   rw   _parse_source_defr   r   rB   )rO   srcrcbr   s       r4   r.  zScriptModule.defineC  sn    &$--7 1188==  AAANC((,,S1C-=c3-MDMM#((*//*r6   c                 6    | j                   j                         S r;   )r   _replicate_for_data_parallelr^   s    r4   r3  z)ScriptModule._replicate_for_data_parallelY  s    --JJLLr6   exporterc                     |j                         }|j                  j                  | j                  t	        |             t
        |ffS )a  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	serializerN   intr   )rO   r4  r   s      r4   __reduce_package__zScriptModule.__reduce_package__\  sB      (557--77EUAVW+.>-@AAr6   r   N)ro   rp   rq   r  __jit_unused_properties__rP   r   r   r   r   r,  r   r   r  r.  r3  r&   r:  r   r   s   @r4   r   r     st    	%
!	 '5&6#s(#6	=C 	=C 	=
	=C 	= 	= 	=*	N,	M	B 	Br6   r   )	metaclassc                       e Zd ZdZdZ fdZed        Zed        Zd Z	e
d        Ze
d        Ze
d	        Ze
d
        Zd Z ed      d        Z ed      d        ZdededefdZdededefdZdefdZdededefdZe
d        Zd Zdedef fdZdededdf fdZdefdZdee ef   dz  defdZ!d edededefd!Z"de#e   fd"Z$d#e defd$Z%d% Z&d& Z'de(e   f fd'Z)d( Z*d) Z+ xZ,S )*RecursiveScriptModuleaZ  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                 f    d| j                   d<   || _        t        |           t	        | d       y )NTr   training)rF   rN   ru   rP   r   )rO   r   rE   s     r4   rP   zRecursiveScriptModule.__init__  s/    -1DMM/* DGG D*%r6   c                 V    t        |       } ||       t         j                  |       |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_modules      r4   
_constructz RecursiveScriptModule._construct  s,     2*=MM"
 "88G  r6   c                 8   t        t        j                  j                  | j                              | _        t        t        j                  j                  | j                              | _        t        | j                  | j                        | _	        d| _
        y )NF)rL   rv   rw   ParameterDictrN   r   
BufferDictr   rs   r   r   rE  s    r4   rC  z,RecursiveScriptModule._finalize_scriptmodule  sx    (:&&}'7'78)M% &8##M$4$45&M" &7  -"8"8&M" +0M'r6   c                 :   | j                  |       t        j                  j                  j	                  | j
                  j                               | _        i }t        j                  j                  | j
                        j                         D ]  \  }}t        |      ||<    t        | j
                  |      | _        t        t        j                  j                  | j
                              | _        t        t        j                  j!                  | j
                              | _        | j$                  j                         D ci c],  \  }}t'        |t        j                  j(                        s||. c}}| _        d| j$                  d<   yc c}}w )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)rP   rv   rw   ConcreteModuleTypefrom_jit_typerN   _typer   rx   rS   r   rs   r   rL   rH  r   rI  r   rF   r   ScriptMethod)rO   r   modulesrB   rU   rV   s         r4   _reconstructz"RecursiveScriptModule._reconstruct  s.    MM*% #((("="="K"K#D
 G$)HH$7$7$@$F$F$H < j /
 ;<-dggw?DM  2%((2H2H2QRD.uxx/B/B477/KLDM
 !MM//1Aq!!UXX%:%:; 1DM
 .3DMM/*s   1Fc                 L    | j                   j                  d      j                  S )zPReturn a string representation of the internal graph for the ``forward`` method.r   )rN   _get_methodr$  r^   s    r4   r$  zRecursiveScriptModule.graph  s     77&&y1777r6   c                 .    | j                   j                  S )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.
            )r   r%  r^   s    r4   r%  z#RecursiveScriptModule.inlined_graph  s     <<---r6   c                 .    | j                   j                  S )z
            Return a pretty-printed representation (as valid Python syntax) of the internal graph for the ``forward`` method.

            )r   r"  r^   s    r4   r"  zRecursiveScriptModule.code  s     <<$$$r6   c                 T    | j                   j                  }|d   t        |d         fS )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.

            r   r)   )r   r#  r   r}   s     r4   r#  z)RecursiveScriptModule.code_with_constants  s*     00AaD(1Q4.))r6   c                 N     | j                   j                  t        |      fi |S )am  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.
            )rN   saver   )rO   fr   s      r4   rX  zRecursiveScriptModule.save  s"      477<<A1&11r6   zLite Interpreter is deprecated. Please consider switching to ExecuTorch.             https://docs.pytorch.org/executorch/stable/getting-started.htmlc                 r    t        j                  dt        d        | j                  j                  |i |S )az  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'.

            Lite Interpreter is deprecated. Please consider switching to ExecuTorch.                 https://docs.pytorch.org/executorch/stable/getting-started.htmlr   
stacklevel)r   r   r   rN   _save_for_mobiler  s      r4   _save_for_lite_interpreterz0RecursiveScriptModule._save_for_lite_interpreter  s:    " MMQ"	 ,477++T<V<<r6   c                 r    t        j                  dt        d        | j                  j                  |i |S )Nr[  r   r\  )r   r   r   rN   _save_to_buffer_for_mobiler  s      r4   $_save_to_buffer_for_lite_interpreterz:RecursiveScriptModule._save_to_buffer_for_lite_interpreter  s:    
 MMQ"	 647755tFvFFr6   r   r   r   c                 :     | j                   j                  |i |S r;   )rN   save_to_bufferr  s      r4   rd  z$RecursiveScriptModule.save_to_buffer,  s    )477))4:6::r6   c                 6    | j                   j                         S r;   )rN   get_debug_stater  s      r4   rf  z%RecursiveScriptModule.get_debug_state/  s    77**,,r6   c                      d| j                    S )Nzoriginal_name=)r&  r^   s    r4   
extra_reprz RecursiveScriptModule.extra_repr2  s    #D$6$6#788r6   c                 B     | j                   j                  | g|i |S r;   )r   	graph_forr  s      r4   rj  zRecursiveScriptModule.graph_for5  s#    )4<<))$@@@@r6   c                     t        |       t        | j                  j                         j	                               u ryt        | j                  j                         j	                               S N )r9   r   rN   rN  rB   r^   s    r4   r&  z#RecursiveScriptModule.original_name8  sI     DzS!5!5!788tww}}++-..r6   c                 ~    t        j                  d      }| j                  j                  | j                  ||       y )Nr)   r   )r   r   rN   _definer   )rO   r0  r1  s      r4   r.  zRecursiveScriptModule.define?  s.      AAANCGGOOD//c:r6   r   c                    d| j                   vrt        d      | j                  rt        |   |      S || j
                  v r| j
                  |   S | j                  j                  |      r| j                  j                  |      S | j                  j                  |      r,| j                  j                  |      }|| j                   |<   |S t        |   |      S )Nr   zKScriptModule has not been initialized, did you forget to call super's init?)rF   rb   r   ru   r   r   rN   rH   rA   r  rS  )rO   r   r   rE   s      r4   r   z!RecursiveScriptModule.__getattr__K  s    dmm3"a  !!w*400 t}}$}}T**&wwt,,$$T* $ 3 3D 9 '4d#$$7&t,,r6   r8   Nc                 |   | j                   rt        | 	  ||      S || j                  v r|| j                  |<   y | j                  j                  |      r| j                  j                  ||       y t        | d      r.|| j                  j                         v rt        d| d| d      t        | 	  ||      S )Nr   z+Cannot mutate TorchScript constant value: 'z'. Value: '')
r   ru   r  r   rN   rH   rg   r   get_constantsAttributeErrorr  s      r4   r  z!RecursiveScriptModule.__setattr__c  s    !!w*477t}}$&+d#&e,./D//==?? %A${SXRYYZ[  w*477r6   c                     t         j                  j                  j                  t	        j                  | j
                              S r;   )rv   r   r   r   copyrN   r^   s    r4   __copy__zRecursiveScriptModule.__copy__~  s*    99''77		$''8JKKr6   memoc                     t         j                  j                  j                  t	        j
                  | j                  |            S r;   )rv   r   r   r   rv  deepcopyrN   )rO   rx  s     r4   __deepcopy__z"RecursiveScriptModule.__deepcopy__  s,    99''77dggt8TUUr6   r  c                 r    t        | |      }t        |dd       t        t        |      k(  rt         ||i |S )N__func__)rA   r?  NotImplementedErrorr  s        r4   r  z*RecursiveScriptModule.forward_magic_method  sE     "$4K{J5%{:  *)///r6   c                 $    | j                  d      S )Nr   r  r^   s    r4   r   zRecursiveScriptModule.__iter__  s    ,,Z88r6   idxc                 &    | j                  d|      S )Nrn   r  )rO   r  s     r4   rn   z!RecursiveScriptModule.__getitem__  s    ,,]C@@r6   c                 $    | j                  d      S )Nr_   r  r^   s    r4   r_   zRecursiveScriptModule.__len__  s    ,,Y77r6   c                 &    | j                  d|      S )Nrk   r  )rO   keys     r4   rk   z"RecursiveScriptModule.__contains__  s    ,,^SAAr6   c                 ~    | j                   }|j                  t        t        d      u rt        |          S  |       S )N__dir__)r  r}  rC   r?  ru   )rO   r  rE   s     r4   r  zRecursiveScriptModule.__dir__  s=    ,,K$$*+@)LM w((= r6   c                 b    | j                   }|j                  t        t        d      u ry |       S )Nr   T)r   r}  rC   r?  )rO   r  s     r4   r   zRecursiveScriptModule.__bool__  s2    --K$$*+@*MN = r6   c                 d    d }t         j                  | j                  j                         |      S )Nc                      y r;   r<   rJ  s    r4   rD  zCRecursiveScriptModule._replicate_for_data_parallel.<locals>.init_fn  s    r6   )r?  rF  rN   r3  )rO   rD  s     r4   r3  z2RecursiveScriptModule._replicate_for_data_parallel  s.    
 )33446 r6   )-ro   rp   rq   r  r   rP   staticmethodrF  rC  rQ  r  r$  r%  r"  r#  rX  r
   r_  rb  r   rd  rf  r   rh  rj  r&  r.  r   r  r   rw  dictr9  r{  r  r   r   rn   r_   rk   r   r  r   r3  r   r   s   @r4   r?  r?  j  s   	0  $	& 
	! 
	!. 

	0 

	0	3@ 
	8 
	8 
	. 
	. 
	% 
	% 
	* 
	*		2 
M

	=	

	=* 
M

	G	

	G	; 	;s 	;s 	;	- 	- 	- 	-	9 	9	A3 	A# 	A# 	A 
	/ 
	/
	;	-C 	-C 	-0	8C 	8 	8 	86	Ld 	L	VT#s(^d%: 	Vt 	V	0"	0+.	0:=	0	0	9hsm 	9	A3 	A3 	A	8	B
	!Xc] 	!	!
	r6   r?  __c                 :    dd l  j                  | fd      S )Nr   c                 P     j                   |       xs  j                  |       S r;   )
isfunctionismethod)xinspects    r4   r   z_get_methods.<locals>.<lambda>  s(    %7W%7%7%:%Q>Ng>N>Nq>Q r6   )	predicate)r  
getmembers)r3   r  s    @r4   _get_methodsr    s#     "w!!Q
 	
r6   >%   tocpucudaevalhalfr9   applyfloattrain_applydoublebuffersr   rP  children	_get_name	zero_grad
add_modulerh  
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                       fd}|S )Nc                      t        dz         )Nz" is not supported on ScriptModulesra   )rO   r   r   rB   s      r4   failz_make_fail.<locals>.fail  s    t&JJKKr6   r<   )rB   r  s   ` r4   
_make_failr    s    	L r6   
_call_implc                       e Zd Zy)r   Nr   r<   r6   r4   r   r     s    r6   c                         e Zd Zd fd	Z xZS )r   c                 "    t         |           y r;   r(  rO   argrE   s     r4   rP   zScriptModule.__init__  r)  r6   r;   r   r   s   @r4   r   r         	 	r6   c                         e Zd Zd fd	Z xZS )r?  c                 "    t         |           y r;   r(  r  s     r4   rP   zRecursiveScriptModule.__init__  r)  r6   r;   r   r   s   @r4   r?  r?    r  r6   c                 X   t        | t        j                  j                        s| S t	        |       }||v r|t	        |          S t        | d      r| j                         n| } | ||<   i }| j                  j                         D ]  \  }}|dk(  r-|j                         D ]  \  }}t        ||      ||<    |||<   8t        |t        j                  j                        r t        |t              st        ||      ||<   ||||<    |j                         D ]  }|| j                  <    | S )N__prepare_scriptable__r   )r   rv   nnr"   idrH   r  rF   rS   !call_prepare_scriptable_func_implr   r[   )r   rx  obj_idnew_obj_dictrB   
sub_modulerU   rV   s           r4   r  r     s5   c588??+
WF ~BsG} )05M(N""$TW  DLLLL..0 
,j:"((* K1 A!T J
1K!+L
EHHOO4Z>
 "C:t!TL!+L
,   " T Jr6   c                     i }t        | |      S r;   )r  )r   rx  s     r4   call_prepare_scriptable_funcr  G  s    ')D,S$77r6   c                 @    t         j                  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.
    )rv   rw   
ScriptDict)r   s    r4   create_script_dictr  L  s     88s##r6   c                 @    t         j                  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.
    )rv   rw   
ScriptList)r   	type_hints     r4   create_script_listr  \  s     88s##r6   T	_TOPLEVELexample_inputsc                    |t        j                  dt        d       t        | t              r| S t        | t
              r| S t        | t              r| S |rt               at        rt        t              }t        |      5  t        |t              r%|j                         D ]  \  }}|D ]  } ||  	  n(t        |t              r|D ]  }	 | |	  	 nt        d      d d d        nt        j                  dd       t        | t        j                   j"                        rWt%        |       } t        j&                  j(                  j+                  | t        j&                  j(                  j,                        S t/        | d      r| j1                         n| } t        | t              rt3        |       S t        | t              rt5        |       S t7        j8                  |       rt;        |       }
t=        | t        j                   j"                        rt?        d|  d	      t=        | t@        jB                        r| S tE        |       st?        d
      tG        | jI                               dkD  rt?        d      |tK        jL                  |dz         }tO        | ||
       | S t7        jP                  |       st7        jR                  |       r	t;        |       }
t/        | d      r!| jT                  } tK        jV                  |       }t/        | d      rt?        d| jX                  z         t[        |        t]        |       }|r	| |_/        |S ta        | | jb                        }|tK        jV                  |       }t        jd                  jg                  |
||ti        |             }| jj                  |_5        d|_1        d|_6        | |_/        to        | |       |S t        j&                  j(                  jq                  |       S # 1 sw Y   xY w)Nz^`optimize` is deprecated and has no effect. Use `with torch.jit.optimized_execution()` insteadr   r\  zError: 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   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'.z\TorchScript classes does not support inheritance yet. Please directly inherit from 'object'.r)   __script_if_tracing_wrapper__script_unsupportedzTorchScript error: r,   r-   )9r   r   FutureWarningr   r   r   r,   r   r>   r   r   r  rS   list
ValueErrorrv   r  r"   r  r   r   r   r   rH   r  r  r  r  isclassr   
issubclassrb   enumEnumrJ   r]   mror   r   r   r  r  __original_fn#createResolutionCallbackFromClosurer  "_check_directly_compile_overloadedr   _torchdynamo_inliner!   ro   rw   _jit_script_compiler   r  rq   r   create_script_class)r   optimize
_frames_upr   r  monkeytype_configrz   example_inputexampleexamplesqualified_namemaybe_already_compiled_fnr   r   s                 r4   _script_implr  n  s    A		
 #+,
#|$
#~&

 *+ 2= A!"34 nd3 2@1E1E1G --'4 -G"G,--  5$2 'X' %W  & MMi 	 #uxx'*3/yy##88%%>>
 	
 s45 &&( 	 #t!#&&#t!#&&s(- c588??+lm  c499%J"3'0  swwy>A9  < BB:PQ>RD#C~>
			C	 G$4$4S$9(-356##C DDSID 3./4s7O7OOPP*3/$@$E!$<?%9,,#s||,< DDSIDXX))C'7'<
 [[
&4!$R(	yy##77<<M s   AP  P
r   r  r  r   c                     t         j                  dk\  rt        j                  dt               nt        j                  dt               t
        s| S 	 t        }dat        | ||dz   ||      }|rt        dt        |             ||aS # aw xY w)	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 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]))
    r   zv`torch.jit.script` is not supported in Python 3.14+ and may break. Please switch to `torch.compile` or `torch.export`.zU`torch.jit.script` is deprecated. Please switch to `torch.compile` or `torch.export`.Fr)   )r   r  r  r   r  script)model_id)
r   r   r   r   r   r   r  r  r   r   )r   r  r  r   r  prevrets          r4   r  r    s    ` 7"B	
 	c	
 
	!A~)
 !(]35GH	D	s   4B	 	Bc                     |j                         D ]>  \  }}|| vs	| |   |k7  st        j                  j                  j	                  |d|        y )NzDefault parameters on overloads do not affect the runtime so they must equal to the default parameter on the implementation function. Found on parameter )rS   rv   r   frontendFrontendError)impl_defaultsoverload_defaultslocrB   overload_values        r4   _check_overload_defaultsr    sb     1 7 7 9 n}$d(;~(M))$$22!F$ r6   c                    t        | | j                        j                         }t        j                  j
                  j                  | d d t        j                  |             }t        ||j                        }t        |       }t        |      }t        j                  |      }t        |||j                                t        j                  j                  ||||||      }	|	S r;   )r!   ro   declrv   r   annotationsget_signaturer  r  r   r   r  r  rangerw   _jit_script_compile_overload)
overload_fn	qual_nameimpl_fnoverload_decloverload_signatureimpl_astr  implementation_defaultsr   r   s
             r4   _compile_function_with_overloadr    s    [-A-ABGGIM..<<T4!1!1+!> 7G$4$45H(5.w7<<WED!2M4G4G4I 
	.	.
B Ir6   c                 8   t        |       }t        |       }t        j                  |      }||S | |v rt	        t        j
                  d|             |D cg c]  }t        |||        }}|r||z   }t        | |       t        j                  |       |S c c}w )Nfunction)	r   r   r   _get_fn_overloadsrb   ,get_overload_no_implementation_error_messager  r   _clear_fn_overloads)r   existing_compiled_fnsr  uncompiled_overloadsr  compiled_fnss         r4   _get_overloadsr    s    9#>$I(::9E#$$
""FFzSVW
 	
 0 	(YDL 
 ,|; C.%%i0s   Bc                 x    t        |       }t        j                  |      st        |       rt	        d| d      y )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   r  r   rb   )r   r  s     r4   r  r  +  sI    $I&&y15RSV5W	{ #F F
 	
 6Xr6   c                 :   t        j                  dt               t        j                  |       st        d      t        |       st        d      t        | t        j                  j                        xr t        | j                               dk(  }|s't        | j                               dkD  rt        d      t        |       }t        j                  d      }t!        | | j"                        }t        j$                  j'                  ||||      }|| _        | S )a  Decorate to annotate classes or modules of different types.

    .. deprecated:: 2.5
        TorchScript is deprecated, please use ``torch.compile`` instead.

    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)
    zH`torch.jit.interface` is deprecated. Please use `torch.compile` instead.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   r   r  r  rb   rJ   r  rv   r  r"   r]   r  r   r   r   r    ro   rw   _jit_script_interface_compile__torch_script_interface__)r   is_module_interfacer  r1  r   mangled_classnames         r4   	interfacer  5  s    f MMR ??3ABBs#NOO %S%((//:Rs3779~QR?R3swwy>A#5D
 	

 %S)N

9
9!
<C C
.C>>S"5 &7C"Jr6   c                     t        |       }t        j                  j                  ||      }t	        j
                  |       }t        | ||      S r;   )r   rv   rw   	CallStackr   'createResolutionCallbackForClassMethodsr   )r   r  
_qual_nameerror_stackr1  s        r4   _recursive_compile_classr"    sC     %J (($$Z5K

?
?
DC&sC<<r6   spaddingoffsetcharc                     |t        |       k\  r|t        |       z  }dj                  t        ||z         D cg c]  }| c}      | z   S c c}w rl  )r]   joinr  )r#  r$  r%  r&  r   s        r4   padr)    sH    #a&3q677%&(8"9:QD:;a??:s   	Ac                   8    e Zd Zd
dededefdZdedefdZd Zy	)_ScriptProfileColumnheader	alignmentr%  c                 <    || _         || _        || _        i | _        y r;   )r,  r-  r%  rows)rO   r,  r-  r%  s       r4   rP   z_ScriptProfileColumn.__init__  s    "$&	r6   linenor8   c                 "    || j                   |<   y r;   )r/  )rO   r0  r8   s      r4   add_rowz_ScriptProfileColumn.add_row  s    !		&r6   c           
         t        | j                        }g }| j                  j                         D ]8  \  }}t	        |      }|j                  ||f       t        t        |      |      }: | j                  dkD  r"|| j                  z   }||| j                  z  z  }nd}|D cg c]  \  }}|t        ||| j                        f  }}}t        | j                  || j                        |fS c c}}w )Nr   )
r]   r,  r/  rS   r   appendmaxr-  r)  r%  )rO   
max_lengthr/  r  r8   cellr$  s          r4   materializez _ScriptProfileColumn.materialize  s    %
&())//+ 	4JCu:DKKd$SY
3J	4
 >>A 4>>1Gw//GGHLM93c$56MM4;;5t;; Ns   %#C.N)   r   )	ro   rp   rq   r   r9  rP   r   r2  r8  r<   r6   r4   r+  r+    s4    's 's ' '"c "# "<r6   r+  c                   .    e Zd Zdee   dee   fdZd Zy)_ScriptProfileTablecolssource_rangec                      || _         || _        y r;   )r<  r=  )rO   r<  r=  s      r4   rP   z_ScriptProfileTable.__init__  s    	(r6   c           	         g }g }d}| j                   D ]6  }|j                         \  }}||z  }|j                  |t        |      f       8 |j                  |       |j                  t	        dt        |      dd             | j                  D ]P  }d}|D ]6  \  }}|j                  |      }	|	|t	        dt        |            z  }2||	z  }8 |j                  |       R dj                  |      S )Nrm  r   =
)	r<  r8  r4  r  r)  r]   r=  r
  r(  )
rO   outputscellsheader_buffercolr,  r/  line
row_bufferr7  s
             r4   dump_stringz_ScriptProfileTable.dump_string  s    2499 	/C??,LFDV#MLL&$t*-.	/
 	}%s2s=11c:;%% 	'DJ % 'xx~<#b#f+"66J$&J' NN:&	' yy!!r6   N)ro   rp   rq   r  r+  r9  rP   rH  r<   r6   r4   r;  r;    s$    )T"67 )tCy )"r6   r;  c                   2    e Zd ZddZd Zd ZdefdZd Zy)	_ScriptProfiler   Nc                 J    t         j                  j                         | _        y r;   )r   	profilingrJ  profiler^   s    r4   rP   z_ScriptProfile.__init__  s    ((779r6   c                 8    | j                   j                          y r;   )rM  enabler^   s    r4   rO  z_ScriptProfile.enable  s    r6   c                 8    | j                   j                          y r;   )rM  disabler^   s    r4   rQ  z_ScriptProfile.disable  s    r6   c                 b   g }| j                   j                         D ]z  }|j                         }|j                         j	                         }t        d |D              }|D cg c]  }||d  	 }}|j                         }|t        |      z   }t        ||      }	t        d      }
t        d      }t        d      }t        ddd      }|j                         }|	D ]  }|
j                  ||       |j                  ||||z
            |j                  |      }|A|j                  ||j                                |j                  ||j                                 t        |
|||gt!        |	            }|j#                  |j%                                } dj'                  |      S c c}w )	Nc              3   h   K   | ]*  }t        |      t        |j                  d             z
   , yw) N)r]   lstrip).0rF  s     r4   	<genexpr>z-_ScriptProfile.dump_string.<locals>.<genexpr>  s'     TtTSS)9%::Ts   02zLine #Hitsz	Time (ns)zLine Contentsr   r)   z

)rM  _dump_statssourcetext
splitlinesminstarting_linenor]   r  r+  line_mapr2  r
  countduration_nsr;  r  r4  rH  r(  )rO   rB  source_stats
source_refsource_linesdedentrF  
start_lineend_liner=  r0  hitstime_nsline_contentsstatsstattables                    r4   rH  z_ScriptProfile.dump_string  s    LL446 	0L%,,.J%??,779LT|TTF6BCdDMCLC#335J!C$55H X6L)(3F'/D*;7G0!QGM ))+E$ >tT*%%dL
9J,KLyy#LLtzz|4OOD$*:*:*<=> (w6\8JE NN5,,./3	04 {{7##- Ds   %F,c                 6    t        | j                                y r;   )printrH  r^   s    r4   dumpz_ScriptProfile.dump  s    d !r6   r;  )	ro   rp   rq   rP   rO  rQ  r   rH  rp  r<   r6   r4   rJ  rJ    s"    :$S $<"r6   rJ  c                      | t        d      | S )NzUnwrapping null optional)AssertionError)r  s    r4   _unwrap_optionalrs    s    y788Hr6   zaten::_unwrap_optionalzaten::is_scriptingzaten::has_torch_functionr;   )Nr   NN)r   rT  )r  collectionsrv  r  r   r  r0   r   r   collections.abcr   r   r   r   typingr   r   r	   typing_extensionsr
   r   rv   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*   r+   r>   rw   rO  rj  r,   ro   rq   r5   
__reduce__
namedtupler7   r?   rC   rJ   rL   rs   r9   r   r   Warningr   r   r   r   r  r   _magic_methodsr   r  r   rg   r   r?  rF   rS   rB   itemcallabler   r  
startswithrH   r  _compiled_methods_allowlistr  methodendswithr  r  r  r  r  boolr,  r  tupler  r  r9  r  r  r  r  r  r  r"  r   r)  r+  r;  rJ  rs  is_scriptingr<   r6   r4   <module>r     s         
  A A & & .  + " > 7 1 A 
   P O  
 ; " 1 T] "#":   $.   !((  + 8  
>; '
A $  &&&{Wf4EFII	 X$C( "  "F&'* &'b;- ;-|+ +
	G 	+>( (''14'
XX__'0 N>?C ?CB & D	K 	$k?CDTBv TBlU Uz
 ,44::< *
d~jx&@??4 GL$$? 	dD)*
&#P %UXX__5 Nf??4 DMM,$? -66677)6??Jt<LMN uxx  
$N8
$ $ 	4 
 	LPH=
 $u+tHd5k,A'BDHIH=Z (,LPn	nn n C5#:

%	n
 $u+tHd5k,A'BDHIn 	nj.6
R2 R" Rj= ((** 
?K (@3 @ @c @S @< <8" "8)" )"X "$< = -,,.B C $&@ A *,F G -/I Jr6   