
    /j/
                    v   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jE        jF        _G        e!ejE        jH        _G        ejE        jH        ZHdeH_         deH_I        deH_J         e@eHd           d ZKeKeH_L        e-r ejM        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\        j7        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          Zdedje        f                                D ]L\  ZgZh eieh          s ejehek          segl                    d=          s emeceg          r? ebecegeh           Md> Znh d?Zod@ Zp enej\        j7                  D ]X\  ZgZqegl                    d=          segr                    dA          r0egedje        vregeovr ebedeqjI         epeg                     Yn3 G dB d6          Z_ G dC d9ej\        j7                  Zc G dD d<ec          ZddE ZsdF ZtdG ZudhdHZvdIawexeydJ<   	 	 	 	 didKeeze{         e|e
eze{         f         df         fdLZ}	 	 	 	 didMe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jE        j        Z e@ed           djdYe[dZe~d[e~d\e[fd]Z G d^ d_          Z G d` da          Z G db dc          Zdd Z eede            eej        df            ee9dg            ee:dg            ee;dg           dS )kzTorchScript.

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    V/home/longshao/multi-rider-rag/.venv/lib/python3.11/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                 h    t          | d          r!dt          |           v pt          | d          S d S )N	__class____dict__	__slots__)hasattrdirr2   s    r4   _is_new_style_classrJ      sA    sK   CSXX%Bk)B)BBC Cr6   c                   D    e Zd Zd Zd Zd Zd Zd Zd Zd Z	d Z
d	 Zd
S )OrderedDictWrapperc                     || _         d S r;   )_c)selfrN   s     r4   __init__zOrderedDictWrapper.__init__   s    r6   c                 >    d |                                  D             S )Nc                     g | ]\  }}|S r<   r<   .0kvs      r4   
<listcomp>z+OrderedDictWrapper.keys.<locals>.<listcomp>       +++da+++r6   itemsrO   s    r4   keyszOrderedDictWrapper.keys       ++djjll++++r6   c                 >    d |                                  D             S )Nc                     g | ]\  }}|S r<   r<   rS   s      r4   rW   z-OrderedDictWrapper.values.<locals>.<listcomp>   rX   r6   rY   r[   s    r4   valueszOrderedDictWrapper.values   r]   r6   c                 D    t          |                                           S r;   )lenr`   r[   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TTr6   c                 4    | j                                         S r;   )rN   rZ   r[   s    r4   rZ   zOrderedDictWrapper.items   s    w}}r6   c                 h    || vrt          d|           | j                            ||           d S )NzICan't add a new parameter after ScriptModule construction. Tried to add ')rf   rN   setattrrO   rU   rV   s      r4   __setitem__zOrderedDictWrapper.__setitem__   sG    D==_\]__   	1r6   c                 6    | j                             |          S r;   )rN   containsrg   s     r4   __contains__zOrderedDictWrapper.__contains__   s    w"""r6   c                 \    || vrt          |          | j                            |          S r;   )KeyErrorrN   rA   rg   s     r4   __getitem__zOrderedDictWrapper.__getitem__   s+    D==1++wq!!!r6   N)__name__
__module____qualname__rP   r\   r`   rc   rh   rZ   rm   rp   rs   r<   r6   r4   rL   rL      s          , , ,, , ," " "U U U    # # #" " " " "r6   rL   c                   6     e Zd Z fdZd Zd Zd Zd Z xZS )OrderedModuleDictc                     t                                          t          j                            |                     || _        d S r;   )superrP   torch_C
ModuleDict_python_modules)rO   modulepython_dictrE   s      r4   rP   zOrderedModuleDict.__init__   s;    ,,V44555  +r6   c                 8    | j                                         }|S r;   )r~   rZ   rO   rs     r4   rZ   zOrderedModuleDict.items   s     &&((r6   c                     || j         v S r;   r~   rg   s     r4   rp   zOrderedModuleDict.__contains__   s    D(((r6   c                     t          |t                    r'| j                            ||           || j        |<   d S t          d| d|           )NzgCannot re-assign modules in a ScriptModule with non-scripted module, tried to replace existing module 'z': )
isinstanceScriptModulerN   rk   r~   rf   rl   s      r4   rm   zOrderedModuleDict.__setitem__   su     a&& 	GOOAq!!!&'D ###G=>G GCDG G  r6   c                     | j         |         S r;   r   rg   s     r4   rs   zOrderedModuleDict.__getitem__  s    #A&&r6   )	rt   ru   rv   rP   rZ   rp   rm   rs   __classcell__rE   s   @r4   rx   rx      st        + + + + +  ) ) )  &' ' ' ' ' ' 'r6   rx   c                        e Zd Z fdZ xZS )
ScriptMetac                 F   	 i  _         t          t           dd                     _        t	          |          D ]q}t          |di                                           D ]\  }}| j         |<   t          |dt                                } j                            |           _        rt          |                                          D ]>\  }}t          |t                    r$t           |           | j         |j        j        <   ?t           dd          r%t                                          |||           d S t           dd           	t          j        	           	fd	            }| _        t                                          |||           d S )
N__constants__r<   _methods_constants_set_disable_script_metaFrP   c                     d S r;   r<   r[   s    r4   <lambda>z%ScriptMeta.__init__.<locals>.<lambda>6  s    d r6   c                    t          	j                  } 
| g|R i | t          	j                  |k    }t          |           	u rd }t          j        j                            | ||           | j        d<   | j        j	        }|
                                D ]}t          | |           |                                D ]\  }}t          | |           dD ]}t          | |           d S d S )Nc                     t          |           }t          |d          r0d t          |j                                                  D             S t          |           S )Nr   c                     g | ]\  }}|S r<   r<   rS   s      r4   rW   zUScriptMeta.__init__.<locals>.init_then_script.<locals>.make_stubs.<locals>.<listcomp>C  s    KKKdaKKKr6   )r9   rH   sortedr   rZ   r   )r   r3   s     r4   
make_stubszAScriptMeta.__init__.<locals>.init_then_script.<locals>.make_stubs@  sX    v,,CsJ// @KKfS\5G5G5I5I.J.JKKKK7???r6   )share_types_actual_script_module)_parameters_buffers_modules)rb   r   r9   r{   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  sB   cl++KM$0000000$'$5$5$C!DzzS  @ @ @ I(==j:O6O >   56 !% : I)88:: ( (DD$'''',88:: ( (GD!D$''''C ( (DD$''''1 ! .( (r6   )r   setrA   r   reversedrZ   unionr   r   r   r   original_methodrt   rz   rP   	functoolswraps)r3   rB   basesattrsbaserU   rV   base_constantsr   r   rE   s   `        @r4   rP   zScriptMeta.__init__  s   ') or!B!BCCUOO 	J 	JDj"55;;== $ $1"#Q")$0@#%%"H"HN!$!3!9!9.!I!IC 5;;==)) 	= 	=DAq!-.. =Q;<Q.783.66 	 GGT5%000FZ1B1BCC		'	'	( 	( 	( 	( 	( 
(	'	(> (ue,,,,,r6   rt   ru   rv   rP   r   r   s   @r4   r   r     s8        :- :- :- :- :- :- :- :- :-r6   r   c                       e Zd Zd ZdS )_CachedForwardc                 ,    |                      d          S )Nforward)__getattr__)rO   objr3   s      r4   __get__z_CachedForward.__get__]  s    	***r6   N)rt   ru   rv   r   r<   r6   r4   r   r   \  s#        + + + + +r6   r   c                       e Zd ZdS )ScriptWarningNrt   ru   rv   r<   r6   r4   r   r   a  s        Dr6   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!   rt   r   )fn_rcbasts      r4   script_methodr   e  s    
7""B	
 	
 	
 	
 	j	
 	
 	
  	 :QGGGD
b"+
@
@
@CD#r***r6   c                   >    e Zd Zdeeef         ddfdZdedefdZdS )ConstMapconst_mappingreturnNc                     || _         d S 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   )rt   ru   rv   r   strr   rP   r   r<   r6   r4   r   r     sa        +gc3h&7 +D + + + +( ( ( ( ( ( ( (r6   r   importerscript_module_idr   c                 @   t          | j        t          j        j                  st          d          t          j                                        }t          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_readerr{   r|   PyTorchFileReaderrf   CompilationUnit_import_ir_module_from_packagestorage_contextr*   last_map_locationr   )r   r   cu
cpp_modules       r4   unpackage_script_moduler     s     h)58+EFF 
N
 
 	
 
	!	!	#	#B88
 h899 J :&&&r6   )__iter__rc   __neg____mul__rp   __add____sub____pow____truediv____mod____ne____eq____lt____gt____le____ge____and____or____xor__rs   rm   __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<   || _        d | j                                        D             | _        d| j        d<   d S )NT_initializingc                 N    i | ]"}|j         t          |j        |j                  #S r<   )rB   propertygettersetter)rT   props     r4   
<dictcomp>z1RecursiveScriptClass.__init__.<locals>.<dictcomp>  s:        	8DK==  r6   F)rz   rP   rF   rN   _properties_props)rO   	cpp_classrE   s     r4   rP   zRecursiveScriptClass.__init__  sn    GG-1DM/*DG  G//11  DK
 .3DM/***r6   r   r   c                     | j                             d          r!t                                          |          S || j        v r| j        |                                         S t          | j        |          S Nr  )rF   getrz   r   r  fgetrA   rN   rO   r   rE   s     r4   r   z RecursiveScriptClass.__getattr__  sk    }  11 1ww**4000t{""{4(--///47D)))r6   r8   Nc                     | j                             d          r"t                                          ||          S || j        v r | j        |                             |          S t          | j        ||           d S r  )rF   r  rz   __setattr__r  fsetrk   rN   rO   r   r8   rE   s      r4   r  z RecursiveScriptClass.__setattr__  sw    }  11 8ww**4777t{""{4(--e444DGT5)))))r6   method_namer   r   c                 ~    | j                             |          st          |                     |          } ||i |S r;   )rN   _has_method	TypeErrorr   rO   r  r   r   self_methods        r4   forward_magic_methodz)RecursiveScriptClass.forward_magic_method  sI     7&&{33  **;77K;////r6   c                 *    t          j        d          )NzScriptClasses cannot be pickledr/   r[   s    r4   __getstate__z!RecursiveScriptClass.__getstate__  s    $%FGGGr6   otherc                     | j                             d          r|                     d|          S |                     d|          S )N__iadd__r   )rN   r  r  )rO   r"  s     r4   r$  zRecursiveScriptClass.__iadd__  sG    w"":.. C00UCCC00EBBBr6   )rt   ru   rv   __doc__rP   r   r   r   r  r  r!  r   r$  r   r   s   @r4   r  r    s       	 		3 	3 	3 	3 	3	*C 	*C 	* 	* 	* 	* 	* 	*	*C 	* 	* 	* 	* 	* 	* 	* 	*	0"	0+.	0:=	0	0 	0 	0 	0	H 	H 	H	C$ 	C4 	C 	C 	C 	C 	C 	C 	C 	Cr6   r  c                 .     | j         t          g|R i |S r;   )r  r  rO   r   r   s      r4   method_templater(    s%    ,4,[J4JJJ6J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                 H    t                                                       d S r;   rz   rP   )rO   rE   s    r4   rP   zScriptModule.__init__$      GGr6   .r   r   c                     d| j         vr!t                                          |          S t          | j        |          S )Nr   )rF   rz   r   rA   r   r  s     r4   r   zScriptModule.__getattr__)  s;    &dm;;ww**400045t<<<r6   r8   c                    d| j         vrgt          |t                    r0d| j        j         vri | j        _        |j        | j        |<   |j        }t                                          ||          S t          | j
        ||           d S )Nr   __annotations__)rF   r   r7   rE   r4  r9   r8   rz   r  rk   r   r  s      r4   r  zScriptModule.__setattr__.  s    &dm;; eY// (
 )0GGG9;616D(.!KEww**4777D.e<<<<<r6   c                    d| j         v r| j                            |          S t          j        d          }t
          j                            |          }t          ||d           | j	        |
                                j
        <   d S )Nr   r)   r   )rF   r   definer   r   r{   r|   _parse_source_defr   r   rB   )rO   srcrcbr   s       r4   r6  zScriptModule.defineC  sz    &$-77 188===  AANNNC(,,S11C-=c3-M-MDM#((**/***r6   c                 4    | j                                         S r;   )r   _replicate_for_data_parallelr[   s    r4   r;  z)ScriptModule._replicate_for_data_parallelY  s    -JJLLLr6   exporterc                     |                                 }|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   r<  r   s      r4   __reduce_package__zScriptModule.__reduce_package__\  sI      (5577-77EUAVAVWWW+.>-@AAr6   r   N)rt   ru   rv   r%  __jit_unused_properties__rP   r   r   r   r   r4  r   r   r  r6  r;  r&   rB  r   r   s   @r4   r   r     s%        	 	%
 %
 %
!	 	 	 	 	 	 '5n&6&6#s(#666	=C 	=C 	= 	= 	= 	= 	= 	=
	=C 	= 	= 	= 	= 	= 	= 	= 	=*	N 	N 	N,	M 	M 	M	B 	B 	B 	B 	B 	B 	B 	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                     d| j         d<   || _        t                                                       t	          | d           d S )NTr  training)rF   rN   rz   rP   r   )rO   r   rE   s     r4   rP   zRecursiveScriptModule.__init__  sD    -1DM/* DGGG D*%%%%%r6   c                 n    t          |           } ||           t                               |           |S )a  
            Construct a RecursiveScriptModule that's ready for use.

            PyTorch code should use this to construct a RecursiveScriptModule instead
            of instead of calling `__init__` directly, as it makes sure the
            object is properly finalized (and in the future, we may take
            control of how the RecursiveScriptModule instance is created).

            Args:
                cpp_module:  The C++ Module that will hold the actual state of
                             this RecursiveScriptModule instance.
                init_fn:  Lambda that initializes the RecursiveScriptModule passed to it.
            )rG  _finalize_scriptmodule)r   init_fnscript_modules      r4   
_constructz RecursiveScriptModule._construct  s=     2*==MGM"""
 "88GGG  r6   c                 *   t          t          j                            | j                            | _        t          t          j                            | j                            | _        t          | j        | j	                  | _	        d| _
        d S )NF)rL   r{   r|   ParameterDictrN   r   
BufferDictr   rx   r   r  rM  s    r4   rK  z,RecursiveScriptModule._finalize_scriptmodule  s    (:&&}'788) )M% &8##M$455& &M" &7 -"8& &M" +0M'''r6   c                    |                      |           t          j        j                            | j                                                  | _        i }t          j                            | j                  	                                D ]\  }}t          |          ||<   t          | j        |          | _        t          t          j                            | j                            | _        t          t          j                            | j                            | _        d | j        	                                D             | _        d| j        d<   dS )z
            Re-construct an instance of RecursiveScriptModule using an instance of a C++ module.

            Args:
                cpp_module: The C++ module that this RecursiveScriptModule will be rebuilt around.
            c                 X    i | ]'\  }}t          |t          j        j                  $||(S r<   )r   r{   r|   ScriptMethodrS   s      r4   r  z6RecursiveScriptModule._reconstruct.<locals>.<dictcomp>  sC       Aq!!UX%:;;1  r6   Fr  N)rP   r{   r|   ConcreteModuleTypefrom_jit_typerN   _typer   r}   rZ   r   rx   r   rL   rP  r   rQ  r   rF   )rO   r   modulesrB   s       r4   _reconstructz"RecursiveScriptModule._reconstruct  s(    MM*%%% #(("="K"K# #D
 G$)H$7$7$@$@$F$F$H$H < < j /
 ; ;-dgw??DM  2%(2H2H2Q2QRRD.ux/B/B47/K/KLLDM  M//11  DM
 .3DM/***r6   c                 @    | 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     7&&y11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'     0AaD(1Q4..))r6   c                 B     | 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   ra  zRecursiveScriptModule.save  s&      47<A11&111r6   zLite Interpreter is deprecated. Please consider switching to ExecuTorch.             https://docs.pytorch.org/executorch/stable/getting-started.htmlc                 ^    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  sE    " MQ"	    ,47+T<V<<<r6   c                 ^    t          j        dt          d            | j        j        |i |S )Nrd  r   re  )r   r   r   rN   _save_to_buffer_for_mobiler'  s      r4   $_save_to_buffer_for_lite_interpreterz:RecursiveScriptModule._save_to_buffer_for_lite_interpreter  sE    
 MQ"	    6475tFvFFFr6   r   r   r   c                 &     | j         j        |i |S r;   )rN   save_to_bufferr'  s      r4   rm  z$RecursiveScriptModule.save_to_buffer,  s    )47)4:6:::r6   c                 4    | j                                         S r;   )rN   get_debug_stater'  s      r4   ro  z%RecursiveScriptModule.get_debug_state/  s    7**,,,r6   c                     d| j          S )Nzoriginal_name=)r.  r[   s    r4   
extra_reprz RecursiveScriptModule.extra_repr2  s    8D$6888r6   c                 .     | j         j        | g|R i |S r;   )r   	graph_forr'  s      r4   rs  zRecursiveScriptModule.graph_for5  s'    )4<)$@@@@@@@r6   c                    t          |           t          | j                                                                                  u rdS t          | j                                                                                  S )N )r9   r   rN   rX  rB   r[   s    r4   r.  z#RecursiveScriptModule.original_name8  s\     DzzS!5!5!7!78888rtw}}++--...r6   c                 r    t          j        d          }| j                            | j        ||           d S )Nr)   r   )r   r   rN   _definer   )rO   r8  r9  s      r4   r6  zRecursiveScriptModule.define?  s8      AANNNCGOOD/c:::::r6   r   c                    d| j         vrt          d          | j        r!t                                          |          S || j        v r| j        |         S | j                            |          r| j                            |          S | j        	                    |          r&| j        
                    |          }|| j         |<   |S t                                          |          S )Nr  zKScriptModule has not been initialized, did you forget to call super's init?)rF   rf   r  rz   r   r   rN   rH   rA   r  r\  )rO   r   r   rE   s      r4   r   z!RecursiveScriptModule.__getattr__K  s    dm33"a   ! 1ww**4000 t}$$}T**&& %wt,,,$$T** % $ 3 3D 9 9 '4d#$$77&&t,,,r6   r8   Nc                    | j         r"t                                          ||          S || j        v r|| j        |<   d S | j                            |          r| j                            ||           d S t          | d          r1|| j                                        v rt          d| d| d          t                                          ||          S )Nr   z+Cannot mutate TorchScript constant value: 'z'. Value: '')
r  rz   r  r   rN   rH   rk   r   get_constantsAttributeErrorr  s      r4   r  z!RecursiveScriptModule.__setattr__c  s    ! 8ww**4777t}$$&+d###&& 8e,,,,,.//8D/==???? %[$[[SX[[[   ww**4777r6   c                 x    t           j        j                            t	          j        | j                            S r;   )r{   r   r   r   copyrN   r[   s    r4   __copy__zRecursiveScriptModule.__copy__~  s'    9'77	$'8J8JKKKr6   memoc                 z    t           j        j                            t	          j        | j        |                    S r;   )r{   r   r   r   r~  deepcopyrN   )rO   r  s     r4   __deepcopy__z"RecursiveScriptModule.__deepcopy__  s)    9'77dgt8T8TUUUr6   r  c                     t          | |          }t          |dd           t          t          |          k    rt           ||i |S )N__func__)rA   rG  NotImplementedErrorr  s        r4   r  z*RecursiveScriptModule.forward_magic_method  sZ     "$44K{J55%{: :   *);////r6   c                 ,    |                      d          S )Nr   r  r[   s    r4   r   zRecursiveScriptModule.__iter__  s    ,,Z888r6   idxc                 .    |                      d|          S )Nrs   r  )rO   r  s     r4   rs   z!RecursiveScriptModule.__getitem__  s    ,,]C@@@r6   c                 ,    |                      d          S )Nrc   r  r[   s    r4   rc   zRecursiveScriptModule.__len__  s    ,,Y777r6   c                 .    |                      d|          S )Nrp   r  )rO   keys     r4   rp   z"RecursiveScriptModule.__contains__  s    ,,^SAAAr6   c                     | j         }|j        t          t          d          u r t	                                                       S  |            S )N__dir__)r  r  rC   rG  rz   )rO   r  rE   s     r4   r  zRecursiveScriptModule.__dir__  sL    ,K$*+@)LLM M ww(((;== r6   c                 `    | j         }|j        t          t          d          u rdS  |            S )Nr   T)r   r  rC   rG  )rO   r  s     r4   r   zRecursiveScriptModule.__bool__  s<    -K$*+@*MMN N t;== r6   c                 l    d }t                               | j                                        |          S )Nc                     d S r;   r<   rR  s    r4   rL  zCRecursiveScriptModule._replicate_for_data_parallel.<locals>.init_fn  s    r6   )rG  rN  rN   r;  )rO   rL  s     r4   r;  z2RecursiveScriptModule._replicate_for_data_parallel  s>      
 )334466  r6   )-rt   ru   rv   r%  r   rP   staticmethodrN  rK  rZ  r  r,  r-  r*  r+  ra  r
   rh  rk  r   rm  ro  r   rq  rs  r.  r6  r   r  r   r  dictrA  r  r  r   r   rs   rc   rp   r   r  r   r;  r   r   s   @r4   rG  rG  j  s       	 	0  $	& 	& 	& 	& 	& 
	! 	! 
	!. 

	0 
	0 

	0	3 	3 	3@ 
	8 	8 
	8 
	. 	. 
	. 
	% 	% 
	% 
	* 	* 
	*		2 		2 		2 
M

 

	= 	=	

 

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

 

	G 	G	

 

	G	; 	;s 	;s 	; 	; 	; 	;	- 	- 	- 	- 	- 	- 	-	9 	9 	9 	9 	9	A3 	A# 	A# 	A 	A 	A 	A 
	/ 	/ 
	/
	; 
	; 
	;	-C 	-C 	- 	- 	- 	- 	- 	-0	8C 	8 	8 	8 	8 	8 	8 	8 	86	Ld 	L 	L 	L 	L	VT#s(^d%: 	Vt 	V 	V 	V 	V	0"	0+.	0:=	0	0 	0 	0 	0	9hsm 	9 	9 	9 	9	A3 	A3 	A 	A 	A 	A	8 	8 	8	B 	B 	B
	!Xc] 	! 	! 	! 	! 	! 	!	! 	! 	!
	 
	 
	 
	 
	 
	 
	r6   rG  __c                 6    dd l  j        | fd          S )Nr   c                 D     j         |           p j        |           S r;   )
isfunctionismethod)xinspects    r4   r   z_get_methods.<locals>.<lambda>  s(    %7W%7%:%:%Q>Ng>Nq>Q>Q r6   )	predicate)r  
getmembers)r3   r  s    @r4   _get_methodsr    s9     "w!QQQQ
 
 
 	
r6   >%   tocpucudaevalhalfr9   applyfloattrain_applydoublebuffersr   rY  children	_get_name	zero_grad
add_modulerq  
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 ScriptModulesre   )rO   r   r   rB   s      r4   failz_make_fail.<locals>.fail  s    t&JJKKKr6   r<   )rB   r  s   ` r4   
_make_failr    s(    	L 	L 	L 	L 	L r6   
_call_implc                       e Zd ZdS )r  Nr   r<   r6   r4   r  r    s        r6   c                         e Zd Zd fd	Z xZS )r   Nc                 H    t                                                       d S r;   r0  rO   argrE   s     r4   rP   zScriptModule.__init__  r1  r6   r;   r   r   s   @r4   r   r     =        	 	 	 	 	 	 	 	 	 	r6   c                         e Zd Zd fd	Z xZS )rG  Nc                 H    t                                                       d S r;   r0  r  s     r4   rP   zRecursiveScriptModule.__init__  r1  r6   r;   r   r   s   @r4   rG  rG    r  r6   c                 ~   t          | t          j        j                  s| S t	          |           }||v r|t	          |                    S t          | d          r|                                 n| } | ||<   i }| j                                        D ]\  }}|dk    r3|                                D ]\  }}t          ||          ||<   |||<   >t          |t          j        j                  r)t          |t                    st          ||          ||<   |||<   |                                D ]}|| j        |<   | S )N__prepare_scriptable__r   )r   r{   nnr"   idrH   r  rF   rZ   !call_prepare_scriptable_func_implr   r`   )r   r  obj_idnew_obj_dictrB   
sub_modulerU   rV   s           r4   r  r     sq   c58?++ 
WWF ~~BsGG} )05M(N(NW""$$$TW  DLLL..00 
, 
,j:"((** K K1 A!T J J
1!+L
EHO44 	,Z>
 >
 	, "C:t!T!TL!+L  ""  TJr6   c                 &    i }t          | |          S r;   )r  )r   r  s     r4   call_prepare_scriptable_funcr  G  s    ')D,S$777r6   c                 @    t           j                            |           S )a  
    Create a ``torch._C.ScriptDict`` instance with the data from ``obj``.

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

    Returns:
        An instance of ``torch._C.ScriptDict`` that has the same data as ``obj``
        and can be passed between Python and TorchScript with reference semantics and
        zero copy overhead.
    )r{   r|   
ScriptDict)r   s    r4   create_script_dictr  L  s     8s###r6   c                 @    t           j                            |           S )a  
    Create a ``torch._C.ScriptList`` instance with the data from ``obj``.

    Args:
        obj (dict): The Python list that is used to initialize the ``ScriptList``
                    returned by this function.
    Returns:
        An instance of ``torch._C.ScriptList`` that has the same data as ``obj``
        and can be passed between Python and TorchScript with reference semantics and
        zero copy overhead.
    )r{   r|   
ScriptList)r   	type_hints     r4   create_script_listr  \  s     8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%|                                D ]\  }}|D ]} ||  n/t          |t                    r|D ]}	 | |	  nt          d          d d d            n# 1 swxY w Y   nt          j        dd           t          | t          j        j                  rHt%          |           } t          j        j                            | t          j        j        j                  S t/          | d          r|                                 n| } t          | t                    rt3          |           S t          | t                    rt5          |           S t7          j        |           rt;          |           }
t=          | t          j        j                  rt?          d|  d	          t=          | t@          j!                  r| S tE          |           st?          d
          tG          | $                                          dk    rt?          d          |tK          j&        |dz             }tO          | ||
           | S t7          j(        |           st7          j)        |           rt;          |           }
t/          | d          r| j*        } tK          j+        |           }t/          | d          rt?          d| j,        z             t[          |            t]          |           }|r	| |_/        |S ta          | | j1                  }|tK          j+        |           }t          j2        3                    |
||ti          |                     }| j5        |_5        d|_1        d|_6        | |_/        to          | |           |S t          j        j        8                    |           S )Nz^`optimize` is deprecated and has no effect. Use `with torch.jit.optimized_execution()` insteadr   re  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  rZ   list
ValueErrorr{   r  r"   r  r   r   r   r   rH   r  r  r  r  isclassr   
issubclassrf   enumEnumrJ   rb   mror   r   r   r  r  __original_fn#createResolutionCallbackFromClosurer  "_check_directly_compile_overloadedr   _torchdynamo_inliner!   rt   r|   _jit_script_compiler   r%  rv   r   create_script_class)r   optimize
_frames_upr   r  monkeytype_configr   example_inputexampleexamplesqualified_namemaybe_already_compiled_fnr   r   s                 r4   _script_implr  n  s    A		
 	
 	
 	
 #+,, 
#|$$ 
#~&& 
 !
 *++ 	 2= A A!"344  nd33  2@1E1E1G1G - --'4 - -G"FG,,,--  55 $2 ' 'X' %W                & Mi 	    #ux'' 

*3//y#88%>
 
 	
 s455C&&((( 	 #t '!#&&&#t '!#&&&s ;=(-- c58?++ 	mmmm   c49%% 	J"3'' 	0   swwyy>>A9   < B:PQ>RRD#C~>>>
		C	 	  =G$4S$9$9 =(--3566 	J#C DSIID 3.// 	Q4s7OOPPP*3///$@$E$E!$ 	-<?%9,,#s|,,< DSIIDX))C'7'<'<
 
 [
&4!$R(((	y#77<<<s   A*DDDr   r  r  r   c                 6   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~)
 
 
  	I!(]35G5GHHHH		D	s   AB Bc                     |                                 D ]=\  }}|| vs| |         |k    r(t          j        j                            |d|           >d S )NzDefault parameters on overloads do not affect the runtime so they must equal to the default parameter on the implementation function. Found on parameter )rZ   r{   r   frontendFrontendError)impl_defaultsoverload_defaultslocrB   overload_values        r4   _check_overload_defaultsr    s~     1 7 7 9 9  n}$$d(;~(M(M)$22$!$ $   )N r6   c                    t          | | j                                                  }t          j        j                            | d d t          j        |                     }t          ||j                  }t          |           }t          |          }t          j        |          }t          |||                                           t          j                            ||||||          }	|	S r;   )r!   rt   declr{   r   annotationsget_signaturer  r  r   r   r  r  ranger|   _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BBGGIIM.<<T4!1+!>!>  7G$455H(55.w77<WEED!2M4G4G4I4I   
	.	.
 
B Ir6   c                 6    t                     }t                     t          j                  }||S  |v r"t	          t          j        d                      fd|D             }|r||z   }t           |           t          j                   |S )Nfunctionc                 2    g | ]}t          |          S r<   )r  )rT   r  r   r  s     r4   rW   z"_get_overloads.<locals>.<listcomp>  s5        	(YDD  r6   )r   r   r   _get_fn_overloadsrf   ,get_overload_no_implementation_error_messager   _clear_fn_overloads)r   existing_compiled_fnsuncompiled_overloadscompiled_fnsr  s   `   @r4   _get_overloadsr    s    9#>>$$I(:9EE#$$
"""FzSVWW
 
 	
    /  L
  <,|; C...%i000r6   c                     t          |           }t          j        |          st          |           rt	          d| d          d S )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   rf   )r   r  s     r4   r  r  +  si    $$I&y11 
5RSV5W5W 
F	 F F F
 
 	

 
r6   c                 r   t          j        dt                     t          j        |           st          d          t          |           st          d          t          | t          j	        j
                  o$t          |                                           dk    }|s4t          |                                           dk    rt          d          t          |           }t          j        d          }t!          | | j                  }t          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  rf   rJ   r  r{   r  r"   rb   r  r   r   r   r    rt   r|   _jit_script_interface_compile__torch_script_interface__)r   is_module_interfacer  r9  r   mangled_classnames         r4   	interfacer%  5  s-   f MR   ?3 CABBBs## PNOOO %S%(/::Rs37799~~QR?R 
3swwyy>>A#5#5D
 
 	

 %S))N

9!
<
<C C
.
.C>>S"5  &7C"Jr6   c                     t          |           }t          j                            ||          }t	          j        |           }t          | ||          S r;   )r   r{   r|   	CallStackr   'createResolutionCallbackForClassMethodsr   )r   r  
_qual_nameerror_stackr9  s        r4   _recursive_compile_classr+    sJ     %%J ($$Z55K

?
D
DC&sC<<<r6    spaddingoffsetcharc                     |t          |           k    r|t          |           z  }d                    fdt          ||z             D                       | z   S )Nru  c                     g | ]}S r<   r<   )rT   r   r0  s     r4   rW   zpad.<locals>.<listcomp>  s    :::QD:::r6   )rb   joinr  )r-  r.  r/  r0  s      `r4   padr4    s]    #a&&3q6677::::%&(8"9"9:::;;a??r6   c                   :    e Zd ZddededefdZdedefd	Zd
 ZdS )_ScriptProfileColumn   r   header	alignmentr/  c                 >    || _         || _        || _        i | _        d S r;   )r8  r9  r/  rows)rO   r8  r9  r/  s       r4   rP   z_ScriptProfileColumn.__init__  s"    "$&			r6   linenor8   c                     || j         |<   d S r;   )r;  )rO   r<  r8   s      r4   add_rowz_ScriptProfileColumn.add_row  s    !	&r6   c                     t           j                  }g } j                                        D ]H\  }}t	          |          }|                    ||f           t          t          |          |          }I j        dk    r| j        z    j        z  z  nd fd|D             }t           j         j	                  |fS )Nr   c                 F    g | ]\  }}|t          |j                  fS r<   )r4  r/  )rT   r  cellr.  rO   s      r4   rW   z4_ScriptProfileColumn.materialize.<locals>.<listcomp>  s0    MMM93c$556MMMr6   )
rb   r8  r;  rZ   r   appendmaxr9  r4  r/  )rO   
max_lengthr;  r  r8   rA  r.  s   `     @r4   materializez _ScriptProfileColumn.materialize  s    %%
&()//++ 	4 	4JCu::DKKd$$$SYY
33JJ>A 4>1Gw//GGGMMMMMMMM4;55t;;r6   N)r7  r   )	rt   ru   rv   r   rA  rP   r   r>  rE  r<   r6   r4   r6  r6    ss        ' 's 's ' ' ' ' '"c "# " " " "< < < < <r6   r6  c                   <    e Zd Zdee         dee         fdZd ZdS )_ScriptProfileTablecolssource_rangec                 "    || _         || _        d S r;   )rH  rI  )rO   rH  rI  s      r4   rP   z_ScriptProfileTable.__init__  s    	(r6   c           	      &   g }g }d}| j         D ]B}|                                \  }}||z  }|                    |t          |          f           C|                    |           |                    t	          dt          |          dd                     | j        D ]^}d}|D ]B\  }}|                    |          }	|	!|t	          dt          |                    z  }=||	z  }C|                    |           _d                    |          S )Nru  r   =
)	rH  rE  rB  r  r4  rb   rI  r  r3  )
rO   outputscellsheader_buffercolr8  r;  line
row_bufferrA  s
             r4   dump_stringz_ScriptProfileTable.dump_string  s&   249 	/ 	/C??,,LFDV#MLL&$t**-....}%%%s2s=111c::;;;% 	' 	'DJ % ' 'xx~~<#b#f++"6"66JJ$&JJNN:&&&&yy!!!r6   N)rt   ru   rv   r  r6  rA  rP   rT  r<   r6   r4   rG  rG    sO        )T"67 )tCy ) ) ) )" " " " "r6   rG  c                   4    e Zd ZddZd Zd ZdefdZd ZdS )	_ScriptProfiler   Nc                 L    t           j                                        | _        d S r;   )r   	profilingrV  profiler[   s    r4   rP   z_ScriptProfile.__init__  s    (7799r6   c                 8    | j                                          d S r;   )rY  enabler[   s    r4   r[  z_ScriptProfile.enable  s    r6   c                 8    | j                                          d S r;   )rY  disabler[   s    r4   r]  z_ScriptProfile.disable  s    r6   c                    g }| j                                         D ]}|                                }|                                                                }t          d |D                       fd|D             }|                                }|t          |          z   }t          ||          }t          d          }t          d          }	t          d          }
t          ddd          }|
                                }|D ]}|                    ||           |                    ||||z
                      |                    |          }|P|	                    ||                                           |
                    ||                                           t          ||	|
|gt!          |                    }|                    |                                           d	                    |          S )
Nc              3   z   K   | ]6}t          |          t          |                    d                     z
  V  7dS )r,  N)rb   lstrip)rT   rR  s     r4   	<genexpr>z-_ScriptProfile.dump_string.<locals>.<genexpr>  sA      TTtTSS)9)9%:%::TTTTTTr6   c                 $    g | ]}|d          S r;   r<   )rT   rR  dedents     r4   rW   z._ScriptProfile.dump_string.<locals>.<listcomp>  s!    CCCdDMCCCr6   zLine #Hitsz	Time (ns)zLine Contentsr   r)   z

)rY  _dump_statssourcetext
splitlinesminstarting_linenorb   r  r6  line_mapr>  r  countduration_nsrG  r  rB  rT  r3  )rO   rN  source_stats
source_refsource_lines
start_lineend_linerI  r<  hitstime_nsline_contentsstatsrR  stattablerc  s                   @r4   rT  z_ScriptProfile.dump_string  s    L4466 	0 	0L%,,..J%??,,7799LTT|TTTTTFCCCClCCCL#3355J!C$5$55H X66L)(33F'//D*;77G0!QGGM ))++E$ > >tT***%%dL
9J,KLLLyy#LLtzz||444OOD$*:*:*<*<==='w6\8J8J E NN5,,..////{{7###r6   c                 H    t          |                                            d S r;   )printrT  r[   s    r4   dumpz_ScriptProfile.dump  s"    d  !!!!!r6   rC  )	rt   ru   rv   rP   r[  r]  r   rT  r{  r<   r6   r4   rV  rV    sp        : : : :    $S $ $ $ $<" " " " "r6   rV  c                 (    | t          d          | S )NzUnwrapping null optional)AssertionError)r  s    r4   _unwrap_optionalr~    s    y7888Hr6   zaten::_unwrap_optionalzaten::is_scriptingzaten::has_torch_functionr;   )Nr   NN)r   r,  )r%  collectionsr~  r  r   r  r0   r   r   collections.abcr   r   r   r   typingr   r   r	   typing_extensionsr
   r   r{   torch._jit_internalr   torch._classesr   r   r   torch._utils_internalr   torch.jit._builtinsr   torch.jit._fuserr   r   torch.jit._monkeytype_configr   r   r   torch.jit._recursiver   r   r   r   torch.jit._stater   r   r   r   r   torch.jit.frontendr   r    r!   torch.nnr"   torch.overridesr#   r$   r%   torch.packager&   r'   torch.utilsr(   _serializationr*   r+   r>   r|   rU  rs  r,   rt   rv   r5   
__reduce__
namedtupler7   r?   rC   rJ   rL   rx   r9   r   r   Warningr   r   r   r   r  r   _magic_methodsr  r  r(  rk   r   rG  rF   rZ   rB   itemcallabler   r  
startswithrH   r  _compiled_methods_allowlistr  methodendswithr  r  r  r  r  boolr4  r  tupler  r  rA  r  r  r  r  r  r%  r+  r   r4  r6  rG  rV  r~  is_scriptingr<   r6   r4   <module>r     s
                 



  A A A A A A A A A A A A & & & & & & & & & & . . . . . . . .  + + + + + + " " " " " " > > > > > > > > 7 7 7 7 7 7 1 1 1 1 1 1 A A A A A A A A         
                         P O O O O O O O O O               
 ; : : : : : : : " " " " " " 1 1 1 1 1 1 WT]] "!##":  $.  !(  + 8  

>; ' ' '
A A A $   &&{Wf4EFFII  I	 X  $ $ $C C C( "  "  "  "  "  "  "  "F&' &' &' &' &'* &' &' &'b;- ;- ;- ;- ;- ;- ;- ;-|+ + + + + + + +
	 	 	 	 	G 	 	 	+ + +>( ( ( ( ( ( ( (''14'
X_' ' ' '0  y	  N>?C ?C ?C ?C ?C ?C ?C ?CB & D D	K 	K 	K 	$k?CCCCTB TB TB TB TBv TB TB TB TBlU U U U U U U Uz
 ,4::<< * *
dx~~ 	jjx&@&@ 	??4   	GGL$$?$? 	 	dD))))
 
 
&# &# &#P   %UX_55 N Nf??4   	DMM,$?$? 	 -666777G)6?JJt<L<LMMMN           ux          
$ $ $N8 8 8
$ $ $ $ $ $ $ 	4   
 	LPH= H=
 $u+tHd5k,A'BDHIH= H= H= H=Z (,LPn n	nn n C5#:

%	n
 $u+tHd5k,A'BDHIn 	n n n nj    .  6
 
 
R2 R" R R R Rj= = = (* 

?K ( ( (@ @3 @ @c @S @ @ @ @< < < < < < < <8" " " " " " " "8)" )" )" )" )" )" )" )"X    "$< = = =  -,.B C C C  $&@ A A A  *,F G G G  -/I J J J J Jr6   