
    9j
                    &   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 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.m/Z/m0Z0 ddl1m2Z2m3Z3m4Z4 ddl5m6Z6 ddl7m8Z8m9Z9m:Z: ddl;m<Z<m=Z= ddl>m?Z? ddl@mAZA  ed      ZB e$       aCe!ej                  j                  _F        e ej                  j                  _F        ej                  j                  ZGdeG_         deG_H        deG_I         e?eGd       d ZJeJeG_K        e,r ej                  dddg      ZMnd ZMdeM_         d  ZNd! ZOd" ZP G d# d$      ZQ G d% d&eQ      ZR G d' d(eS      ZT G d) d*      ZU G d+ d,eV      ZWd- ZX G d. d/      ZYd0e=d1eZd2ej                  jl                  fd3Z\e,rg d4Z] G d5 d6      Z^e]D ]  Z_d7 Z` eae^e_e`         G d8 d9e6eT:      Zb G d; d<eb      Zcecj                  j                         D ]<  \  ZfZg eheg      s
 eiegej      sefj                  d=      s	 elebef      r3 eaebefeg       > d> Zmh d?Znd@ Zo emej                  jl                        D ]V  \  ZfZpefj                  d=      sefj                  dA      r)efecj                  vs8efenvs= eaecepj                   eoef             X n4 G dB d6      Z^ G dC d9ej                  jl                        Zb G dD d<eb      ZcdE ZrdF ZsdG ZtdgdHZudIavewexdJ<   	 	 	 	 dhdKeyez   e{e
eyez   f   z  dz  fdLZ|	 	 	 	 dhdMedNddOe}dPe
eZgef   dz  dKeyez   e{e
eyez   f   z  dz  d2efdQZ~dR ZdS ZdT ZdU ZdMeBd2eBfdVZdW Zej                  j
                  Z e?ed       didXeZdYe}dZe}d[eZfd\Z G d] d^      Z G d_ d`      Z G da db      Zdc Z eedd        eej                  de        ee8df        ee9df        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)
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    Q/media/conek/DATA/Code/OCR/venv/lib/python3.12/site-packages/torch/jit/_script.py_reducer4   O   s    


?
@@    	Attributevaluetypec                     | S N )r7   r8   s     r3   r6   r6   Z   s    r5   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;   r5   r3   _get_type_trace_dbr>      s    r5   c                     t        | |d       S r:   )getattr)r2   names     r3   _get_function_from_typerB      s    3d##r5   c                 R    t        | d      rdt        |       v xs t        | d      S y )N	__class____dict__	__slots__)hasattrdirr1   s    r3   _is_new_style_classrI      s,    sK SX%Bk)BB !r5   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)selfrM   s     r3   __init__zOrderedDictWrapper.__init__   s	    r5   c                 T    | j                         D cg c]  \  }}|	 c}}S c c}}w r:   itemsrN   kvs      r3   keyszOrderedDictWrapper.keys        "jjl+da+++   $c                 T    | j                         D cg c]  \  }}|	 c}}S c c}}w r:   rQ   rS   s      r3   valueszOrderedDictWrapper.values   rW   rX   c                 4    t        | j                               S r:   )lenrZ   rN   s    r3   __len__zOrderedDictWrapper.__len__   s    4;;=!!r5   c                     t        d      )Nz6cannot delete methods or parameters of a script moduleRuntimeErrorrN   rT   s     r3   __delitem__zOrderedDictWrapper.__delitem__   s    STTr5   c                 6    | j                   j                         S r:   )rM   rR   r]   s    r3   rR   zOrderedDictWrapper.items   s    ww}}r5   c                 `    || vrt        d|       | j                  j                  ||       y )NzICan't add a new parameter after ScriptModule construction. Tried to add ')ra   rM   setattrrS   s      r3   __setitem__zOrderedDictWrapper.__setitem__   s6    D=[\][^_  	1r5   c                 8    | j                   j                  |      S r:   )rM   containsrb   s     r3   __contains__zOrderedDictWrapper.__contains__   s    ww""r5   c                 V    || vrt        |      | j                  j                  |      S r:   )KeyErrorrM   r@   rb   s     r3   __getitem__zOrderedDictWrapper.__getitem__   s&    D=1+wwq!!r5   N)__name__
__module____qualname__rO   rV   rZ   r^   rc   rR   rg   rj   rm   r;   r5   r3   rK   rK      s0    ,,"U#"r5   rK   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:   )superrO   torch_C
ModuleDict_python_modules)rN   modulepython_dictrD   s      r3   rO   zOrderedModuleDict.__init__   s)    ,,V45  +r5   c                 :    | j                   j                         }|S r:   )rx   rR   rN   rs     r3   rR   zOrderedModuleDict.items   s      &&(r5   c                     || j                   v S r:   rx   rb   s     r3   rj   zOrderedModuleDict.__contains__   s    D((((r5   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ScriptModulerM   rf   rx   ra   rS   s      r3   rg   zOrderedModuleDict.__setitem__   sS     a&GGOOAq!&'D  #==>Cs1#G r5   c                      | j                   |   S r:   r   rb   s     r3   rm   zOrderedModuleDict.__getitem__  s    ##A&&r5   )	rn   ro   rp   rO   rR   rj   rg   rm   __classcell__rD   s   @r3   rr   rr      s    +)&'r5   rr   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_metaFrO   c                      y r:   r;   r]   s    r3   <lambda>z%ScriptMeta.__init__.<locals>.<lambda>6  s    r5   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   )r8   rG   sortedr   rR   r   )ry   r2   rT   rU   s       r3   
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   r8   ru   jit
_recursivecreate_script_modulerE   r   _concrete_typeget_attributesdelattrget_modules)rN   argskwargsnum_methodsadded_methods_in_initr   concrete_typerA   _r2   original_inits            r3   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$'(/ !r5   )r   setr@   r   reversedrR   unionr   r   r   r   original_methodrn   rt   rO   	functoolswraps)r2   rA   basesattrsbaserT   rU   base_constantsr   r   rD   s   `        @r3   rO   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,r5   rn   ro   rp   rO   r   r   s   @r3   r   r     s    :- :-r5   r   c                       e Zd Zd Zy)_CachedForwardc                 $    | j                  d      S )Nforward)__getattr__)rN   objr2   s      r3   __get__z_CachedForward.__get__]  s    	**r5   N)rn   ro   rp   r   r;   r5   r3   r   r   \  s    +r5   r   c                       e Zd Zy)ScriptWarningNrn   ro   rp   r;   r5   r3   r   r   a  s    r5   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    rn   r   )fn_rcbasts      r3   script_methodr   e  sv    
7"B	
 	j	
 	 ::QGD
b"++
@CD#r**r5   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   )rN   r   s     r3   rO   zConstMap.__init__  s
    *r5   attrc                      | j                   |   S r:   r   )rN   r   s     r3   r   zConstMap.__getattr__  s    !!$''r5   )rn   ro   rp   r   strr   rO   r   r;   r5   r3   r   r     s1    +gc3h&7 +D +( ( (r5   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_readerru   rv   PyTorchFileReaderra   CompilationUnit_import_ir_module_from_packagestorage_contextr)   last_map_locationr   )r   r   cu
cpp_modules       r3   unpackage_script_moduler     s     h))588+E+EFN
 	
 
	!	!	#B88
  h889J :&&r5   )__iter__r^   __neg____mul__rj   __add____sub____pow____truediv____mod____ne____eq____lt____gt____le____ge____and____or____xor__rm   rg   __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)
rt   rO   rE   rM   _propertiesrA   propertygettersetter_props)rN   	cpp_classproprD   s      r3   rO   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   )rE   getrt   r   r  fgetr@   rM   rN   r   rD   s     r3   r   z RecursiveScriptClass.__getattr__  sZ    }}  1w*400t{{"{{4(--//477D))r5   r7   Nc                     | j                   j                  d      rt        |   ||      S || j                  v r| j                  |   j                  |      S t        | j                  ||       y r  )rE   r	  rt   __setattr__r  fsetrf   rM   rN   r   r7   rD   s      r3   r  z RecursiveScriptClass.__setattr__  s]    }}  1w*477t{{"{{4(--e44DGGT5)r5   method_namer   r   c                 v    | j                   j                  |      st        | j                  |      } ||i |S r:   )rM   _has_method	TypeErrorr   rN   r  r   r   self_methods        r3   forward_magic_methodz)RecursiveScriptClass.forward_magic_method  s;     77&&{3**;7K///r5   c                 ,    t        j                  d      )NzScriptClasses cannot be pickledr.   r]   s    r3   __getstate__z!RecursiveScriptClass.__getstate__  s    $$%FGGr5   otherc                     | j                   j                  d      r| j                  d|      S | j                  d|      S )N__iadd__r   )rM   r  r  )rN   r  s     r3   r  zRecursiveScriptClass.__iadd__  s:    ww"":.00UCC00EBBr5   )rn   ro   rp   __doc__rO   r   r   r   r  r  r  r
   r  r   r   s   @r3   r   r     s{    		3	*C 	*C 	*	*C 	* 	* 	*	0"	0+.	0:=	0	0	H	C$ 	C4 	Cr5   r   c                 6     | j                   t        g|i |S r:   )r  r  rN   r   r   s      r3   method_templater    s    ,4,,[J4J6JJr5   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:   rt   rO   )rN   rD   s    r3   rO   zScriptModule.__init__$      Gr5   .r   r   c                 j    d| j                   vrt        | 	  |      S t        | j                  |      S )Nr   )rE   rt   r   r@   r   r  s     r3   r   zScriptModule.__getattr__)  s2    &dmm;w*400455t<<r5   r7   c                 ,   d| j                   vrnt        |t              rNd| j                  j                   vri | j                  _        |j
                  | j                  |<   |j                  }t        | !  ||      S t        | j                  ||       y )Nr   __annotations__)rE   r   r6   rD   r+  r8   r7   rt   r  rf   r   r  s      r3   r  zScriptModule.__setattr__.  s|    &dmm; eY/
 )0G0GG9;616D((.!KKEw*477D..e<r5   c                 $   d| j                   v r| j                  j                  |      S t        j                  d      }t
        j                  j                  |      }t        ||d       | j                  |j                         j                  <   y )Nr   r(   r   )rE   r   definer   r   ru   rv   _parse_source_defr   r   rA   )rN   srcrcbr   s       r3   r-  zScriptModule.defineC  sn    &$--7 1188==  AAANC((,,S1C-=c3-MDMM#((*//*r5   c                 6    | j                   j                         S r:   )r   _replicate_for_data_parallelr]   s    r3   r2  z)ScriptModule._replicate_for_data_parallelY  s    --JJLLr5   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	serializerM   intr   )rN   r3  r   s      r3   __reduce_package__zScriptModule.__reduce_package__\  sB      (557--77EUAVW+.>-@AAr5   r   N)rn   ro   rp   r  __jit_unused_properties__rO   r   r   r   r   r+  r   r   r  r-  r2  r%   r9  r   r   s   @r3   r   r     st    	%
!	 '5&6#s(#6	=C 	=C 	=
	=C 	= 	= 	=*	N,	M	B 	Br5   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)rE   rM   rt   rO   r   )rN   r   rD   s     r3   rO   zRecursiveScriptModule.__init__  s/    -1DMM/* DGG D*%r5   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      r3   
_constructz RecursiveScriptModule._construct  s,     2*=MM"
 "88G  r5   c                 8   t        t        j                  j                  | j                              | _        t        t        j                  j                  | j                              | _        t        | j                  | j                        | _	        d| _
        y )NF)rK   ru   rv   ParameterDictrM   r   
BufferDictr   rr   r   r   rD  s    r3   rB  z,RecursiveScriptModule._finalize_scriptmodule  sx    (:&&}'7'78)M% &8##M$4$45&M" &7  -"8"8&M" +0M'r5   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)rO   ru   rv   ConcreteModuleTypefrom_jit_typerM   _typer   rw   rR   r   rr   r   rK   rG  r   rH  r   rE   r   ScriptMethod)rN   r   modulesrA   rT   rU   s         r3   _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   )rM   _get_methodr#  r]   s    r3   r#  zRecursiveScriptModule.graph  s     77&&y1777r5   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    r3   r$  z#RecursiveScriptModule.inlined_graph  s     <<---r5   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    r3   r!  zRecursiveScriptModule.code  s     <<$$$r5   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     r3   r"  z)RecursiveScriptModule.code_with_constants  s*     00AaD(1Q4.))r5   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.
            )rM   saver   )rN   fr   s      r3   rW  zRecursiveScriptModule.save  s"      477<<A1&11r5   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   rM   _save_for_mobiler  s      r3   _save_for_lite_interpreterz0RecursiveScriptModule._save_for_lite_interpreter  s:    " MMQ"	 ,477++T<V<<r5   c                 r    t        j                  dt        d        | j                  j                  |i |S )NrZ  r   r[  )r   r   r   rM   _save_to_buffer_for_mobiler  s      r3   $_save_to_buffer_for_lite_interpreterz:RecursiveScriptModule._save_to_buffer_for_lite_interpreter  s:    
 MMQ"	 647755tFvFFr5   r   r   r   c                 :     | j                   j                  |i |S r:   )rM   save_to_bufferr  s      r3   rc  z$RecursiveScriptModule.save_to_buffer,  s    )477))4:6::r5   c                 6    | j                   j                         S r:   )rM   get_debug_stater  s      r3   re  z%RecursiveScriptModule.get_debug_state/  s    77**,,r5   c                      d| j                    S )Nzoriginal_name=)r%  r]   s    r3   
extra_reprz RecursiveScriptModule.extra_repr2  s    #D$6$6#788r5   c                 B     | j                   j                  | g|i |S r:   )r   	graph_forr  s      r3   ri  zRecursiveScriptModule.graph_for5  s#    )4<<))$@@@@r5   c                     t        |       t        | j                  j                         j	                               u ryt        | j                  j                         j	                               S N )r8   r   rM   rM  rA   r]   s    r3   r%  z#RecursiveScriptModule.original_name8  sI     DzS!5!5!788tww}}++-..r5   c                 ~    t        j                  d      }| j                  j                  | j                  ||       y )Nr(   r   )r   r   rM   _definer   )rN   r/  r0  s      r3   r-  zRecursiveScriptModule.define?  s.      AAANCGGOOD//c:r5   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?)rE   ra   r   rt   r   r   rM   rG   r@   r  rR  )rN   r   r   rD   s      r3   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,,r5   r7   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   rt   r  r   rM   rG   rf   r   get_constantsAttributeErrorr  s      r3   r  z!RecursiveScriptModule.__setattr__c  s    !!w*477t}}$&+d#&e,./D//==?? %A${SXRYYZ[  w*477r5   c                     t         j                  j                  j                  t	        j                  | j
                              S r:   )ru   r   r   r   copyrM   r]   s    r3   __copy__zRecursiveScriptModule.__copy__~  s*    99''77		$''8JKKr5   memoc                     t         j                  j                  j                  t	        j
                  | j                  |            S r:   )ru   r   r   r   ru  deepcopyrM   )rN   rw  s     r3   __deepcopy__z"RecursiveScriptModule.__deepcopy__  s,    99''77dggt8TUUr5   r  c                 r    t        | |      }t        |dd       t        t        |      k(  rt         ||i |S )N__func__)r@   r>  NotImplementedErrorr  s        r3   r  z*RecursiveScriptModule.forward_magic_method  sE     "$4K{J5%{:  *)///r5   c                 $    | j                  d      S )Nr   r  r]   s    r3   r   zRecursiveScriptModule.__iter__  s    ,,Z88r5   idxc                 &    | j                  d|      S )Nrm   r  )rN   r  s     r3   rm   z!RecursiveScriptModule.__getitem__  s    ,,]C@@r5   c                 $    | j                  d      S )Nr^   r  r]   s    r3   r^   zRecursiveScriptModule.__len__  s    ,,Y77r5   c                 &    | j                  d|      S )Nrj   r  )rN   keys     r3   rj   z"RecursiveScriptModule.__contains__  s    ,,^SAAr5   c                 ~    | j                   }|j                  t        t        d      u rt        |          S  |       S )N__dir__)r  r|  rB   r>  rt   )rN   r  rD   s     r3   r  zRecursiveScriptModule.__dir__  s=    ,,K$$*+@)LM w((= r5   c                 b    | j                   }|j                  t        t        d      u ry |       S )Nr   T)r   r|  rB   r>  )rN   r  s     r3   r   zRecursiveScriptModule.__bool__  s2    --K$$*+@*MN = r5   c                 d    d }t         j                  | j                  j                         |      S )Nc                      y r:   r;   rI  s    r3   rC  zCRecursiveScriptModule._replicate_for_data_parallel.<locals>.init_fn  s    r5   )r>  rE  rM   r2  )rN   rC  s     r3   r2  z2RecursiveScriptModule._replicate_for_data_parallel  s.    
 )33446 r5   )-rn   ro   rp   r  r   rO   staticmethodrE  rB  rP  r  r#  r$  r!  r"  rW  r	   r^  ra  r   rc  re  r   rg  ri  r%  r-  r   r  r
   rv  dictr8  rz  r  r   r   rm   r^   rj   r   r  r   r2  r   r   s   @r3   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] 	!	!
	r5   r>  __c                 :    dd l  j                  | fd      S )Nr   c                 P     j                   |       xs  j                  |       S r:   )
isfunctionismethod)xinspects    r3   r   z_get_methods.<locals>.<lambda>  s(    %7W%7%7%:%Q>Ng>N>Nq>Q r5   )	predicate)r  
getmembers)r2   r  s    @r3   _get_methodsr    s#     "w!!Q
 	
r5   >%   tocpucudaevalhalfr8   applyfloattrain_applydoublebuffersr   rO  children	_get_name	zero_grad
add_modulerg  
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 ScriptModulesr`   )rN   r   r   rA   s      r3   failz_make_fail.<locals>.fail  s    t&JJKKr5   r;   )rA   r  s   ` r3   
_make_failr    s    	L r5   
_call_implc                       e Zd Zy)r   Nr   r;   r5   r3   r   r     s    r5   c                         e Zd Zd fd	Z xZS )r   c                 "    t         |           y r:   r'  rN   argrD   s     r3   rO   zScriptModule.__init__  r(  r5   r:   r   r   s   @r3   r   r         	 	r5   c                         e Zd Zd fd	Z xZS )r>  c                 "    t         |           y r:   r'  r  s     r3   rO   zRecursiveScriptModule.__init__  r(  r5   r:   r   r   s   @r3   r>  r>    r  r5   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   ru   nnr!   idrG   r  rE   rR   !call_prepare_scriptable_func_implr   rZ   )r   rw  obj_idnew_obj_dictrA   
sub_modulerT   rU   s           r3   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 Jr5   c                     i }t        | |      S r:   )r  )r   rw  s     r3   call_prepare_scriptable_funcr  G  s    ')D,S$77r5   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.
    )ru   rv   
ScriptDict)r   s    r3   create_script_dictr  L  s     88s##r5   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.
    )ru   rv   
ScriptList)r   	type_hints     r3   create_script_listr  \  s     88s##r5   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  rR   list
ValueErrorru   r  r!   r  r   r   r   r   rG   r  r  r  r  isclassr   
issubclassra   enumEnumrI   r\   mror   r   r   r  r  __original_fn#createResolutionCallbackFromClosurer  "_check_directly_compile_overloadedr   _torchdynamo_inliner    rn   rv   _jit_script_compiler   r  rp   r   create_script_class)r   optimize
_frames_upr   r  monkeytype_configry   example_inputexampleexamplesqualified_namemaybe_already_compiled_fnr   r   s                 r3   _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          r3   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 )rR   ru   r   frontendFrontendError)impl_defaultsoverload_defaultslocrA   overload_values        r3   _check_overload_defaultsr    sb     1 7 7 9 n}$d(;~(M))$$22!F$ r5   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    rn   declru   r   annotationsget_signaturer  r  r   r   r  r  rangerv   _jit_script_compile_overload)
overload_fn	qual_nameimpl_fnoverload_decloverload_signatureimpl_astr  implementation_defaultsr   r   s
             r3   _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 Ir5   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_overloadsra   ,get_overload_no_implementation_error_messager  r   _clear_fn_overloads)r   existing_compiled_fnsr  uncompiled_overloadsr  compiled_fnss         r3   _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   ra   )r   r  s     r3   r  r  +  sI    $I&&y15RSV5W	{ #F F
 	
 6Xr5   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  ra   rI   r  ru   r  r!   r\   r  r   r   r   r   rn   rv   _jit_script_interface_compile__torch_script_interface__)r   is_module_interfacer  r0  r   mangled_classnames         r3   	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"Jr5   c                     t        |       }t        j                  j                  ||      }t	        j
                  |       }t        | ||      S r:   )r   ru   rv   	CallStackr   'createResolutionCallbackForClassMethodsr   )r   r  
_qual_nameerror_stackr0  s        r3   _recursive_compile_classr!    sC     %J (($$Z5K

?
?
DC&sC<<r5   spaddingoffsetcharc                     |t        |       k\  r|t        |       z  }dj                  t        ||z         D cg c]  }| c}      | z   S c c}w rk  )r\   joinr  )r"  r#  r$  r%  r   s        r3   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)rN   r+  r,  r$  s       r3   rO   z_ScriptProfileColumn.__init__  s    "$&	r5   linenor7   c                 "    || j                   |<   y r:   )r.  )rN   r/  r7   s      r3   add_rowz_ScriptProfileColumn.add_row  s    !		&r5   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.  rR   r   appendmaxr,  r(  r$  )rN   
max_lengthr.  r  r7   cellr#  s          r3   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   )	rn   ro   rp   r   r8  rO   r   r1  r7  r;   r5   r3   r*  r*    s4    's 's ' '"c "# "<r5   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<  )rN   r;  r<  s      r3   rO   z_ScriptProfileTable.__init__  s    	(r5   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 )Nrl  r   =
)	r;  r7  r3  r  r(  r\   r<  r	  r'  )
rN   outputscellsheader_buffercolr+  r.  line
row_bufferr6  s
             r3   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!!r5   N)rn   ro   rp   r  r*  r8  rO   rG  r;   r5   r3   r:  r:    s$    )T"67 )tCy )"r5   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   	profilingrI  profiler]   s    r3   rO   z_ScriptProfile.__init__  s    ((779r5   c                 8    | j                   j                          y r:   )rL  enabler]   s    r3   rN  z_ScriptProfile.enable  s    r5   c                 8    | j                   j                          y r:   )rL  disabler]   s    r3   rP  z_ScriptProfile.disable  s    r5   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).0rE  s     r3   	<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

)rL  _dump_statssourcetext
splitlinesminstarting_linenor\   r  r*  line_mapr1  r	  countduration_nsr:  r  r3  rG  r'  )rN   rA  source_stats
source_refsource_linesdedentrE  
start_lineend_liner<  r/  hitstime_nsline_contentsstatsstattables                    r3   rG  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:   )printrG  r]   s    r3   dumpz_ScriptProfile.dump  s    d !r5   r:  )	rn   ro   rp   rO   rN  rP  r   rG  ro  r;   r5   r3   rI  rI    s"    :$S $<"r5   rI  c                      | t        d      | S )NzUnwrapping null optional)AssertionError)r  s    r3   _unwrap_optionalrr    s    y788Hr5   zaten::_unwrap_optionalzaten::is_scriptingzaten::has_torch_functionr:   )Nr   NN)r   rS  )r  collectionsru  r  r   r  r/   r   r   collections.abcr   r   r   r   typingr   r   typing_extensionsr	   r
   ru   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=   rv   rN  ri  r+   rn   rp   r4   
__reduce__
namedtupler6   r>   rB   rI   rK   rr   r8   r   r   Warningr   r   r   r   r  r   _magic_methodsr   r  r  rf   r   r>  rE   rR   rA   itemcallabler   r  
startswithrG   r  _compiled_methods_allowlistr  methodendswithr  r  r  r  r  boolr+  r  tupler  r  r8  r  r  r  r  r  r  r!  r   r(  r*  r:  rI  rr  is_scriptingr;   r5   r3   <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 
 	GKH=
 K$xe'<"==DH=Z (,GKn	nn n C5#:

%	n
 K$xe'<"==Dn 	nj.6
R2 R" Rj= ((** 
?K (@3 @ @c @S @< <8" "8)" )"X "$< = -,,.B C $&@ A *,F G -/I Jr5   