
    c,j
                    f   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jD        jE        _F        e ejD        jG        _F        ejD        jG        ZGdeG_         deG_H        deG_I         e?eGd           d ZJeJeG_K        e,r ejL        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[        j6        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          Zcecjd        e                                D ]L\  ZfZg eheg          s eiegej          sefk                    d=          s elebef          r? eaebefeg           Md> Zmh d?Znd@ Zo emej[        j6                  D ]X\  ZfZpefk                    d=          sefq                    dA          r0efecjd        vrefenvr eaecepjH         eoef                     Yn3 G dB d6          Z^ G dC d9ej[        j6                  Zb G dD d<eb          ZcdE ZrdF ZsdG ZtdhdHZudIavewexdJ<   	 	 	 	 didKeyez         e{e
eyez         f         z  dz  fdLZ|	 	 	 	 didMe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jD        j        Z e?ed           djdYeZdZe}d[e}d\eZfd]Z G d^ d_          Z G d` da          Z G db dc          Zdd Z eede            eej        df            ee8dg            ee9dg            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)
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/var/www/html/banglarbhumi/venv/lib/python3.11/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                 h    t          | d          r!dt          |           v pt          | d          S d S )N	__class____dict__	__slots__)hasattrdirr1   s    r3   _is_new_style_classrI      sA    sK   CSXX%Bk)B)BBC Cr5   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)selfrM   s     r3   __init__zOrderedDictWrapper.__init__   s    r5   c                 >    d |                                  D             S )Nc                     g | ]\  }}|S r;   r;   .0kvs      r3   
<listcomp>z+OrderedDictWrapper.keys.<locals>.<listcomp>       +++da+++r5   itemsrN   s    r3   keyszOrderedDictWrapper.keys       ++djjll++++r5   c                 >    d |                                  D             S )Nc                     g | ]\  }}|S r;   r;   rR   s      r3   rV   z-OrderedDictWrapper.values.<locals>.<listcomp>   rW   r5   rX   rZ   s    r3   valueszOrderedDictWrapper.values   r\   r5   c                 D    t          |                                           S r:   )lenr_   rZ   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TTr5   c                 4    | j                                         S r:   )rM   rY   rZ   s    r3   rY   zOrderedDictWrapper.items   s    w}}r5   c                 h    || vrt          d|           | j                            ||           d S )NzICan't add a new parameter after ScriptModule construction. Tried to add ')re   rM   setattrrN   rT   rU   s      r3   __setitem__zOrderedDictWrapper.__setitem__   sG    D==_\]__   	1r5   c                 6    | j                             |          S r:   )rM   containsrf   s     r3   __contains__zOrderedDictWrapper.__contains__   s    w"""r5   c                 \    || vrt          |          | j                            |          S r:   )KeyErrorrM   r@   rf   s     r3   __getitem__zOrderedDictWrapper.__getitem__   s+    D==1++wq!!!r5   N)__name__
__module____qualname__rO   r[   r_   rb   rg   rY   rl   ro   rr   r;   r5   r3   rK   rK      s          , , ,, , ," " "U U U    # # #" " " " "r5   rK   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:   )superrO   torch_C
ModuleDict_python_modules)rN   modulepython_dictrD   s      r3   rO   zOrderedModuleDict.__init__   s;    ,,V44555  +r5   c                 8    | j                                         }|S r:   )r}   rY   rN   rs     r3   rY   zOrderedModuleDict.items   s     &&((r5   c                     || j         v S r:   r}   rf   s     r3   ro   zOrderedModuleDict.__contains__   s    D(((r5   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ScriptModulerM   rj   r}   re   rk   s      r3   rl   zOrderedModuleDict.__setitem__   su     a&& 	GOOAq!!!&'D ###G=>G GCDG G  r5   c                     | j         |         S r:   r   rf   s     r3   rr   zOrderedModuleDict.__getitem__  s    #A&&r5   )	rs   rt   ru   rO   rY   ro   rl   rr   __classcell__rD   s   @r3   rw   rw      st        + + + + +  ) ) )  &' ' ' ' ' ' 'r5   rw   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_metaFrO   c                     d S r:   r;   rZ   s    r3   <lambda>z%ScriptMeta.__init__.<locals>.<lambda>6  s    d r5   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;   rR   s      r3   rV   zUScriptMeta.__init__.<locals>.init_then_script.<locals>.make_stubs.<locals>.<listcomp>C  s    KKKdaKKKr5   )r8   rG   sortedr   rY   r   )r~   r2   s     r3   
make_stubszAScriptMeta.__init__.<locals>.init_then_script.<locals>.make_stubs@  sX    v,,CsJ// @KKfS\5G5G5I5I.J.JKKKK7???r5   )share_types_actual_script_module)_parameters_buffers_modules)ra   r   r8   rz   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  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 ! .( (r5   )r   setr@   r   reversedrY   unionr   r   r   r   original_methodrs   ry   rO   	functoolswraps)r2   rA   basesattrsbaserT   rU   base_constantsr   r   rD   s   `        @r3   rO   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,,,,,r5   rs   rt   ru   rO   r   r   s   @r3   r   r     s8        :- :- :- :- :- :- :- :- :-r5   r   c                       e Zd Zd ZdS )_CachedForwardc                 ,    |                      d          S )Nforward)__getattr__)rN   objr2   s      r3   __get__z_CachedForward.__get__]  s    	***r5   N)rs   rt   ru   r   r;   r5   r3   r   r   \  s#        + + + + +r5   r   c                       e Zd ZdS )ScriptWarningNrs   rt   ru   r;   r5   r3   r   r   a  s        Dr5   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    rs   r   )fn_rcbasts      r3   script_methodr   e  s    
7""B	
 	
 	
 	
 	j	
 	
 	
  	 :QGGGD
b"+
@
@
@CD#r***r5   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   )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   )rs   rt   ru   r   strr   rO   r   r;   r5   r3   r   r     sa        +gc3h&7 +D + + + +( ( ( ( ( ( ( (r5   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_readerrz   r{   PyTorchFileReaderre   CompilationUnit_import_ir_module_from_packagestorage_contextr)   last_map_locationr   )r   r   cu
cpp_modules       r3   unpackage_script_moduler     s     h)58+EFF 
N
 
 	
 
	!	!	#	#B88
 h899 J :&&&r5   )__iter__rb   __neg____mul__ro   __add____sub____pow____truediv____mod____ne____eq____lt____gt____le____ge____and____or____xor__rr   rl   __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;   )rA   propertygettersetter)rS   props     r3   
<dictcomp>z1RecursiveScriptClass.__init__.<locals>.<dictcomp>  s:        	8DK==  r5   F)ry   rO   rE   rM   _properties_props)rN   	cpp_classrD   s     r3   rO   zRecursiveScriptClass.__init__  sn    GG-1DM/*DG  G//11  DK
 .3DM/***r5   r   r   c                     | j                             d          r!t                                          |          S || j        v r| j        |                                         S t          | j        |          S Nr  )rE   getry   r   r  fgetr@   rM   rN   r   rD   s     r3   r   z RecursiveScriptClass.__getattr__  sk    }  11 1ww**4000t{""{4(--///47D)))r5   r7   Nc                     | j                             d          r"t                                          ||          S || j        v r | j        |                             |          S t          | j        ||           d S r  )rE   r  ry   __setattr__r  fsetrj   rM   rN   r   r7   rD   s      r3   r  z RecursiveScriptClass.__setattr__  sw    }  11 8ww**4777t{""{4(--e444DGT5)))))r5   method_namer   r   c                 ~    | j                             |          st          |                     |          } ||i |S r:   )rM   _has_method	TypeErrorr   rN   r  r   r   self_methods        r3   forward_magic_methodz)RecursiveScriptClass.forward_magic_method  sI     7&&{33  **;77K;////r5   c                 *    t          j        d          )NzScriptClasses cannot be pickledr.   rZ   s    r3   __getstate__z!RecursiveScriptClass.__getstate__  s    $%FGGGr5   otherc                     | j                             d          r|                     d|          S |                     d|          S )N__iadd__r   )rM   r  r  )rN   r!  s     r3   r#  zRecursiveScriptClass.__iadd__  sG    w"":.. C00UCCC00EBBBr5   )rs   rt   ru   __doc__rO   r   r   r   r  r  r   r
   r#  r   r   s   @r3   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r5   r  c                 .     | j         t          g|R i |S r:   )r  r  rN   r   r   s      r3   method_templater'    s%    ,4,[J4JJJ6J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                 H    t                                                       d S r:   ry   rO   )rN   rD   s    r3   rO   zScriptModule.__init__$      GGr5   .r   r   c                     d| j         vr!t                                          |          S t          | j        |          S )Nr   )rE   ry   r   r@   r   r  s     r3   r   zScriptModule.__getattr__)  s;    &dm;;ww**400045t<<<r5   r7   c                    d| j         vrgt          |t                    r0d| j        j         vri | j        _        |j        | j        |<   |j        }t                                          ||          S t          | j
        ||           d S )Nr   __annotations__)rE   r   r6   rD   r3  r8   r7   ry   r  rj   r   r  s      r3   r  zScriptModule.__setattr__.  s    &dm;; eY// (
 )0GGG9;616D(.!KEww**4777D.e<<<<<r5   c                    d| j         v r| j                            |          S t          j        d          }t
          j                            |          }t          ||d           | j	        |
                                j
        <   d S )Nr   r(   r   )rE   r   definer   r   rz   r{   _parse_source_defr   r   rA   )rN   srcrcbr   s       r3   r5  zScriptModule.defineC  sz    &$-77 188===  AANNNC(,,S11C-=c3-M-MDM#((**/***r5   c                 4    | j                                         S r:   )r   _replicate_for_data_parallelrZ   s    r3   r:  z)ScriptModule._replicate_for_data_parallelY  s    -JJLLLr5   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	serializerM   intr   )rN   r;  r   s      r3   __reduce_package__zScriptModule.__reduce_package__\  sI      (5577-77EUAVAVWWW+.>-@AAr5   r   N)rs   rt   ru   r$  __jit_unused_properties__rO   r   r   r   r   r3  r   r   r  r5  r:  r%   rA  r   r   s   @r3   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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                     d| j         d<   || _        t                                                       t	          | d           d S )NTr  training)rE   rM   ry   rO   r   )rN   r   rD   s     r3   rO   zRecursiveScriptModule.__init__  sD    -1DM/* DGGG D*%%%%%r5   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.
            )rF  _finalize_scriptmodule)r   init_fnscript_modules      r3   
_constructz RecursiveScriptModule._construct  s=     2*==MGM"""
 "88GGG  r5   c                 *   t          t          j                            | j                            | _        t          t          j                            | j                            | _        t          | j        | j	                  | _	        d| _
        d S )NF)rK   rz   r{   ParameterDictrM   r   
BufferDictr   rw   r   r  rL  s    r3   rJ  z,RecursiveScriptModule._finalize_scriptmodule  s    (:&&}'788) )M% &8##M$455& &M" &7 -"8& &M" +0M'''r5   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   rz   r{   ScriptMethodrR   s      r3   r  z6RecursiveScriptModule._reconstruct.<locals>.<dictcomp>  sC       Aq!!UX%:;;1  r5   Fr  N)rO   rz   r{   ConcreteModuleTypefrom_jit_typerM   _typer   r|   rY   r   rw   r   rK   rO  r   rP  r   rE   )rN   r   modulesrA   s       r3   _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/***r5   c                 @    | j                             d          j        S )zPReturn a string representation of the internal graph for the ``forward`` method.r   )rM   _get_methodr+  rZ   s    r3   r+  zRecursiveScriptModule.graph  s     7&&y11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,  rZ   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)  rZ   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'     0AaD(1Q4..))r5   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.
            )rM   saver   )rN   fr   s      r3   r`  zRecursiveScriptModule.save  s&      47<A11&111r5   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   rM   _save_for_mobiler&  s      r3   _save_for_lite_interpreterz0RecursiveScriptModule._save_for_lite_interpreter  sE    " MQ"	    ,47+T<V<<<r5   c                 ^    t          j        dt          d            | j        j        |i |S )Nrc  r   rd  )r   r   r   rM   _save_to_buffer_for_mobiler&  s      r3   $_save_to_buffer_for_lite_interpreterz:RecursiveScriptModule._save_to_buffer_for_lite_interpreter  sE    
 MQ"	    6475tFvFFFr5   r   r   r   c                 &     | j         j        |i |S r:   )rM   save_to_bufferr&  s      r3   rl  z$RecursiveScriptModule.save_to_buffer,  s    )47)4:6:::r5   c                 4    | j                                         S r:   )rM   get_debug_stater&  s      r3   rn  z%RecursiveScriptModule.get_debug_state/  s    7**,,,r5   c                     d| j          S )Nzoriginal_name=)r-  rZ   s    r3   
extra_reprz RecursiveScriptModule.extra_repr2  s    8D$6888r5   c                 .     | j         j        | g|R i |S r:   )r   	graph_forr&  s      r3   rr  zRecursiveScriptModule.graph_for5  s'    )4<)$@@@@@@@r5   c                    t          |           t          | j                                                                                  u rdS t          | j                                                                                  S )N )r8   r   rM   rW  rA   rZ   s    r3   r-  z#RecursiveScriptModule.original_name8  s\     DzzS!5!5!7!78888rtw}}++--...r5   c                 r    t          j        d          }| j                            | j        ||           d S )Nr(   r   )r   r   rM   _definer   )rN   r7  r8  s      r3   r5  zRecursiveScriptModule.define?  s8      AANNNCGOOD/c:::::r5   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?)rE   re   r  ry   r   r   rM   rG   r@   r  r[  )rN   r   r   rD   s      r3   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,,,r5   r7   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  ry   r  r   rM   rG   rj   r   get_constantsAttributeErrorr  s      r3   r  z!RecursiveScriptModule.__setattr__c  s    ! 8ww**4777t}$$&+d###&& 8e,,,,,.//8D/==???? %[$[[SX[[[   ww**4777r5   c                 x    t           j        j                            t	          j        | j                            S r:   )rz   r   r   r   copyrM   rZ   s    r3   __copy__zRecursiveScriptModule.__copy__~  s'    9'77	$'8J8JKKKr5   memoc                 z    t           j        j                            t	          j        | j        |                    S r:   )rz   r   r   r   r}  deepcopyrM   )rN   r  s     r3   __deepcopy__z"RecursiveScriptModule.__deepcopy__  s)    9'77dgt8T8TUUUr5   r  c                     t          | |          }t          |dd           t          t          |          k    rt           ||i |S )N__func__)r@   rF  NotImplementedErrorr  s        r3   r  z*RecursiveScriptModule.forward_magic_method  sZ     "$44K{J55%{: :   *);////r5   c                 ,    |                      d          S )Nr   r  rZ   s    r3   r   zRecursiveScriptModule.__iter__  s    ,,Z888r5   idxc                 .    |                      d|          S )Nrr   r  )rN   r  s     r3   rr   z!RecursiveScriptModule.__getitem__  s    ,,]C@@@r5   c                 ,    |                      d          S )Nrb   r  rZ   s    r3   rb   zRecursiveScriptModule.__len__  s    ,,Y777r5   c                 .    |                      d|          S )Nro   r  )rN   keys     r3   ro   z"RecursiveScriptModule.__contains__  s    ,,^SAAAr5   c                     | j         }|j        t          t          d          u r t	                                                       S  |            S )N__dir__)r  r  rB   rF  ry   )rN   r  rD   s     r3   r  zRecursiveScriptModule.__dir__  sL    ,K$*+@)LLM M ww(((;== r5   c                 `    | j         }|j        t          t          d          u rdS  |            S )Nr   T)r   r  rB   rF  )rN   r  s     r3   r   zRecursiveScriptModule.__bool__  s<    -K$*+@*MMN N t;== r5   c                 l    d }t                               | j                                        |          S )Nc                     d S r:   r;   rQ  s    r3   rK  zCRecursiveScriptModule._replicate_for_data_parallel.<locals>.init_fn  s    r5   )rF  rM  rM   r:  )rN   rK  s     r3   r:  z2RecursiveScriptModule._replicate_for_data_parallel  s>      
 )334466  r5   )-rs   rt   ru   r$  r   rO   staticmethodrM  rJ  rY  r  r+  r,  r)  r*  r`  r	   rg  rj  r   rl  rn  r   rp  rr  r-  r5  r   r  r
   r~  dictr@  r  r  r   r   rr   rb   ro   r   r  r   r:  r   r   s   @r3   rF  rF  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] 	! 	! 	! 	! 	! 	!	! 	! 	!
	 
	 
	 
	 
	 
	 
	r5   rF  __c                 6    dd l  j        | fd          S )Nr   c                 D     j         |           p j        |           S r:   )
isfunctionismethod)xinspects    r3   r   z_get_methods.<locals>.<lambda>  s(    %7W%7%:%:%Q>Ng>Nq>Q>Q r5   )	predicate)r  
getmembers)r2   r  s    @r3   _get_methodsr    s9     "w!QQQQ
 
 
 	
r5   >%   tocpucudaevalhalfr8   applyfloattrain_applydoublebuffersr   rX  children	_get_name	zero_grad
add_modulerp  
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 ScriptModulesrd   )rN   r   r   rA   s      r3   failz_make_fail.<locals>.fail  s    t&JJKKKr5   r;   )rA   r  s   ` r3   
_make_failr    s(    	L 	L 	L 	L 	L r5   
_call_implc                       e Zd ZdS )r  Nr   r;   r5   r3   r  r    s        r5   c                         e Zd Zd fd	Z xZS )r   Nc                 H    t                                                       d S r:   r/  rN   argrD   s     r3   rO   zScriptModule.__init__  r0  r5   r:   r   r   s   @r3   r   r     =        	 	 	 	 	 	 	 	 	 	r5   c                         e Zd Zd fd	Z xZS )rF  Nc                 H    t                                                       d S r:   r/  r  s     r3   rO   zRecursiveScriptModule.__init__  r0  r5   r:   r   r   s   @r3   rF  rF    r  r5   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   rz   nnr!   idrG   r  rE   rY   !call_prepare_scriptable_func_implr   r_   )r   r  obj_idnew_obj_dictrA   
sub_modulerT   rU   s           r3   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Jr5   c                 &    i }t          | |          S r:   )r  )r   r  s     r3   call_prepare_scriptable_funcr  G  s    ')D,S$777r5   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.
    )rz   r{   
ScriptDict)r   s    r3   create_script_dictr  L  s     8s###r5   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.
    )rz   r{   
ScriptList)r   	type_hints     r3   create_script_listr  \  s     8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%|                                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   rd  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  rY   list
ValueErrorrz   r  r!   r  r   r   r   r   rG   r  r  r  r  isclassr   
issubclassre   enumEnumrI   ra   mror   r   r   r  r  __original_fn#createResolutionCallbackFromClosurer  "_check_directly_compile_overloadedr   _torchdynamo_inliner    rs   r{   _jit_script_compiler   r$  ru   r   create_script_class)r   optimize
_frames_upr   r  monkeytype_configr~   example_inputexampleexamplesqualified_namemaybe_already_compiled_fnr   r   s                 r3   _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          r3   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 )rY   rz   r   frontendFrontendError)impl_defaultsoverload_defaultslocrA   overload_values        r3   _check_overload_defaultsr    s~     1 7 7 9 9  n}$$d(;~(M(M)$22$!$ $   )N r5   c                    t          | | j                                                  }t          j        j                            | d d t          j        |                     }t          ||j                  }t          |           }t          |          }t          j        |          }t          |||                                           t          j                            ||||||          }	|	S r:   )r    rs   declrz   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
             r3   _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 Ir5   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  )rS   r  r   r  s     r3   rV   z"_get_overloads.<locals>.<listcomp>  s5        	(YDD  r5   )r   r   r   _get_fn_overloadsre   ,get_overload_no_implementation_error_messager   _clear_fn_overloads)r   existing_compiled_fnsuncompiled_overloadscompiled_fnsr  s   `   @r3   _get_overloadsr    s    9#>>$$I(:9EE#$$
"""FzSVWW
 
 	
    /  L
  <,|; C...%i000r5   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   re   )r   r  s     r3   r  r  +  si    $$I&y11 
5RSV5W5W 
F	 F F F
 
 	

 
r5   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  re   rI   r  rz   r  r!   ra   r  r   r   r   r   rs   r{   _jit_script_interface_compile__torch_script_interface__)r   is_module_interfacer  r8  r   mangled_classnames         r3   	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"Jr5   c                     t          |           }t          j                            ||          }t	          j        |           }t          | ||          S r:   )r   rz   r{   	CallStackr   'createResolutionCallbackForClassMethodsr   )r   r  
_qual_nameerror_stackr8  s        r3   _recursive_compile_classr*    sJ     %%J ($$Z55K

?
D
DC&sC<<<r5    spaddingoffsetcharc                     |t          |           k    r|t          |           z  }d                    fdt          ||z             D                       | z   S )Nrt  c                     g | ]}S r;   r;   )rS   r   r/  s     r3   rV   zpad.<locals>.<listcomp>  s    :::QD:::r5   )ra   joinr
  )r,  r-  r.  r/  s      `r3   padr3    s]    #a&&3q6677::::%&(8"9"9:::;;a??r5   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:   )r7  r8  r.  rows)rN   r7  r8  r.  s       r3   rO   z_ScriptProfileColumn.__init__  s"    "$&			r5   linenor7   c                     || j         |<   d S r:   )r:  )rN   r;  r7   s      r3   add_rowz_ScriptProfileColumn.add_row  s    !	&r5   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;   )r3  r.  )rS   r  cellr-  rN   s      r3   rV   z4_ScriptProfileColumn.materialize.<locals>.<listcomp>  s0    MMM93c$556MMMr5   )
ra   r7  r:  rY   r   appendmaxr8  r3  r.  )rN   
max_lengthr:  r  r7   r@  r-  s   `     @r3   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;;r5   N)r6  r   )	rs   rt   ru   r   r@  rO   r   r=  rD  r;   r5   r3   r5  r5    ss        ' 's 's ' ' ' ' '"c "# " " " "< < < < <r5   r5  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:   )rG  rH  )rN   rG  rH  s      r3   rO   z_ScriptProfileTable.__init__  s    	(r5   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 )Nrt  r   =
)	rG  rD  rA  r  r3  ra   rH  r  r2  )
rN   outputscellsheader_buffercolr7  r:  line
row_bufferr@  s
             r3   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!!!r5   N)rs   rt   ru   r  r5  r@  rO   rS  r;   r5   r3   rF  rF    sO        )T"67 )tCy ) ) ) )" " " " "r5   rF  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   	profilingrU  profilerZ   s    r3   rO   z_ScriptProfile.__init__  s    (7799r5   c                 8    | j                                          d S r:   )rX  enablerZ   s    r3   rZ  z_ScriptProfile.enable  s    r5   c                 8    | j                                          d S r:   )rX  disablerZ   s    r3   r\  z_ScriptProfile.disable  s    r5   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)ra   lstrip)rS   rQ  s     r3   	<genexpr>z-_ScriptProfile.dump_string.<locals>.<genexpr>  sA      TTtTSS)9)9%:%::TTTTTTr5   c                 $    g | ]}|d          S r:   r;   )rS   rQ  dedents     r3   rV   z._ScriptProfile.dump_string.<locals>.<listcomp>  s!    CCCdDMCCCr5   zLine #Hitsz	Time (ns)zLine Contentsr   r(   z

)rX  _dump_statssourcetext
splitlinesminstarting_linenora   r
  r5  line_mapr=  r  countduration_nsrF  r  rA  rS  r2  )rN   rM  source_stats
source_refsource_lines
start_lineend_linerH  r;  hitstime_nsline_contentsstatsrQ  stattablerb  s                   @r3   rS  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###r5   c                 H    t          |                                            d S r:   )printrS  rZ   s    r3   dumpz_ScriptProfile.dump  s"    d  !!!!!r5   rB  )	rs   rt   ru   rO   rZ  r\  r   rS  rz  r;   r5   r3   rU  rU    sp        : : : :    $S $ $ $ $<" " " " "r5   rU  c                 (    | t          d          | S )NzUnwrapping null optional)AssertionError)r  s    r3   _unwrap_optionalr}    s    y7888Hr5   zaten::_unwrap_optionalzaten::is_scriptingzaten::has_torch_functionr:   )Nr   NN)r   r+  )r$  collectionsr}  r  r   r  r/   r   r   collections.abcr   r   r   r   typingr   r   typing_extensionsr	   r
   rz   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{   rT  rr  r+   rs   ru   r4   
__reduce__
namedtupler6   r>   rB   rI   rK   rw   r8   r   r   Warningr   r   r   r   r  r   _magic_methodsr  r  r'  rj   r   rF  rE   rY   rA   itemcallabler   r  
startswithrG   r  _compiled_methods_allowlistr  methodendswithr  r  r  r  r  boolr3  r  tupler  r  r@  r  r  r  r  r  r$  r*  r   r3  r5  rF  rU  r}  is_scriptingr;   r5   r3   <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   
 	GKH= H=
 K$xe'<"==DH= H= H= H=Z (,GKn n	nn n C5#:

%	n
 K$xe'<"==D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 Jr5   