
    Pg                     :   U 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mZmZmZmZmZ d dlmZ d dlZd dlmZ d dlmZmZmZmZ d dlmZ d dlmZmZ d dl m!Z! g dZ" e#       a$ee%   e&d	<    e#       Z'ee%   e&d
<   dgZ(d Z) G d d      Z*d Z+e jX                  d        Z-g Z.ee*   e&d<    ej^                  d      Z0ejb                  dddd       Z2e2jf                  d@de*fd       Z4ejb                  dAddd       Z5dAddddZ6de%de%fdZ7e5jf                  d@de*fd        Z4 ed!e8"      dAdd#d$d%       Z9ee%d&d'f   Z:	 dAddd(e:d)ed*ee	   dee*   fd+Z;	 dAdd#d$d(e:d*ee	   dee*   d,e<fd-Z=ddd.d(e:d/e	d0ee	   ddfd1Z>	 dAddd(e:d2ed*ee	   dee*   fd3Z?	 dAddd(e:d*ee	   fd4Z@d5 ZAdBd6ZBd7ZC	 dAeCd8d9d(eej                  jB                  ej                  j                  ef   d:eed;f   d<ee
e%ef      d=ee%ee%   f   d>eFde
e%e%f   fd?ZGy)C    N)	AnyCallableDictListOptionalSequenceSetTupleUnion)
deprecated)_maybe_get_opdef	custom_opCustomOpDefdevice_types_t)infer_schema)	triton_opwrap_triton)
OpOverload)Libraryimpldefinefallthrough_kernelimpl_abstractregister_fakeregister_torch_dispatchregister_vmapget_ctxr   r   r   r   _impls_defsprimc                      t        d      )zZ
    A dummy function to pass to ``Library.impl`` in order to register a fallthrough.
    z,fallthrough_kernel() should never be called.)NotImplementedError     T/var/www/html/suriana-translation/venv/lib/python3.12/site-packages/torch/library.pyr   r   4   s     L
MMr$   c                   d    e Zd ZdZddZd ZddddZddZd Zdd	Z	dd
ddZ
dd
ddZd Zy)r   aC  
    A class to create libraries that can be used to register new operators or
    override operators in existing libraries from Python.
    A user can optionally pass in a dispatch keyname if they only want to register
    kernels corresponding to only one specific dispatch key.

    To create a library to override operators in an existing library (with name ns), set the kind to "IMPL".
    To create a new library (with name ns) to register new operators, set the kind to "DEF".
    To create a fragment of a possibly existing library to register operators (and bypass
    the limitation that there is only one library for a given namespace), set the kind to
    "FRAGMENT".

    Args:
        ns: library name
        kind: "DEF", "IMPL" (default: "IMPL"), "FRAGMENT"
        dispatch_key: PyTorch dispatch key (default: "")
    c           	      v   |dvrt        d|      |t        v r|dk(  s|dk(  rt        |d      t        j                         rt        j
                  j                          y t        j                  d      d   }|j                  |j                  }}t        j                  j                  |||||      | _        || _        t               | _        t               | _        g | _        || _        || _        t+        j,                  | t.        t0        | j"                  t2        | j                   | j$                         y )	N)IMPLDEFFRAGMENTzUnsupported kind: r)   r*   zJ is a reserved namespace. Please try creating a library with another name.   )limitr   )
ValueError_reserved_namespacestorch_running_with_deploy_libraryutilswarn_deploy	tracebackextract_stackfilenamelineno_C_dispatch_librarymnsset_op_defs	_op_impls_registration_handleskinddispatch_keyweakreffinalize_del_libraryr   r   )selfr;   r@   rA   framer6   r7   s          r%   __init__zLibrary.__init__N   s   221488%%45=DJ<N\  %%'NN&&(''a03 >>5<<& % : :"lHf!
 "%%#&5TV"	(
 	NNMM&&	
r$   c                 V    d| j                    d| j                   d| j                   dS )NzLibrary(kind=z, ns=z, dispatch_key=z)>)r@   r;   rA   )rE   s    r%   __repr__zLibrary.__repr__t   s-    tyyktwwitGXGXFYY[\\r$   r#   )tagsc                   t        j                         rt        j                  j	                          y|dvrt        d|       | j                  J t        |t         j                        r|f}|j                  d      d   }d|v r|j                  d      d   n|}t        t         j                  | j                        xr. t        t        t         j                  | j                        |      }| j                  j                  ||t        |            }|j                  d      d   }| j                  dz   |z   }|rOt        t         j                  | j                        }	t        |	|      }
t         j                   j#                  |
       | j$                  j'                  |       t(        j'                  |       |S )a  Defines a new operator and its semantics in the ns namespace.

        Args:
            schema: function schema to define a new operator.
            alias_analysis (optional): Indicates if the aliasing properties of the operator arguments can be
                                       inferred from the schema (default behavior) or not ("CONSERVATIVE").
            tags (Tag | Sequence[Tag]): one or more torch.Tag to apply to this
                                       operator. Tagging an operator changes the operator's behavior
                                       under various PyTorch subsystems; please read the docs for the
                                       torch.Tag carefully before applying it.

        Returns:
            name of the operator as inferred from the schema.

        Example::
            >>> my_lib = Library("mylib", "DEF")
            >>> my_lib.define("sum(Tensor self) -> Tensor")
        N) FROM_SCHEMACONSERVATIVEzInvalid alias_analysis type (r   .::)r/   r0   r1   r2   r3   RuntimeErrorr:   
isinstanceTagsplithasattropsr;   getattrr   tuple_ops_refresh_packetr=   addr   )rE   schemaalias_analysisrJ   namepacket_namehas_preexisting_packetresultqualnamer;   packets              r%   r   zLibrary.definew   se   & %%'NN&&( !DD!=n=MNOOvv!!!dEII&7D||C #,/4Kdjjoa(T!(DGG!< "
EIItww'B
 v~uT{C||C #77T>D( "DGG,BR-FJJ&&v.(#		(r$   c                 z   t        j                         rt        j                  j	                          yt         j                  j                  j                  |dz         }t        j                  |      }t        j                  |      }|dn|j                  }||j                  d      rd}| j                   d| }t         j                  j                  j                  j                  |      }	|t!        |||      }
n|}
|	j"                  j%                  |
|      }| j&                  j)                  |       y)z?Registers the fake impl for an operator defined in the library.N   ztorchvision.rQ   )r/   r0   r1   r2   r3   
get_sourcesys	_getframeinspect	getmodule__name__
startswithr;   simple_registry	singletonfind_check_pystubs_once	fake_implregisterr?   append)rE   op_namefn_stacklevelsourcerF   caller_modulecaller_module_namerc   entryfunc_to_registerhandles               r%   _register_fakezLibrary._register_fake   s   %%'NN&&(%%00qAk*))%0 &3%:T@V@V ).@.K.K/
 "&ggYb	*..88==hG)22xAST!))*:FC""))&1r$   c                 `   t        j                         rt        j                  j	                          y| j
                   d| }t         j                  j                  j                  j                  |      }|j                  j                  ||      }| j                  j                  |       y)a  Registers a torch_dispatch rule for the given operator and torch_dispatch_class.

        This allows for open registration to specify the behavior between the operator
        and the torch_dispatch_class without needing to modify the torch_dispatch_class
        or the operator directly.

        The torch_dispatch_class is either a Tensor subclass with `__torch_dispatch__` or a
        TorchDispatchMode.

        If it is a Tensor subclass, we expect fn to have the following signature:
        (cls, func: OpOverload, types: Tuple[type, ...], args, kwargs) -> Any

        If it is a TorchDispatchMode, we expect fn to have the following signature:
        (mode, func: OpOverload, types: Tuple[type, ...], args, kwargs) -> Any
        NrQ   )r/   r0   r1   r2   r3   r;   rn   ro   rp   torch_dispatch_rulesrs   r?   rt   )rE   ru   torch_dispatch_classrv   rc   r{   r}   s          r%   _register_torch_dispatch_rulez%Library._register_torch_dispatch_rule   s      %%'NN&&(ggYb	*..88==hG++445I2N""))&1r$   c                    t        j                         rt        j                  j	                          y|dk(  r| j
                  }t        j                  |      j                  t         j                  j                  j                        sJ t        |t              r|}nUt        |t              r:|j                  j                  }|j                  j                   }|dk7  r|dz   |z   }nt#        d      | j$                  dz   |j'                  d      d   z   dz   |z   }|t(        v r8t#        dj+                  |j'                  d      d   || j$                              | j,                  J | j,                  j.                  } || j$                  |j'                  d      d   |       t(        j1                  |       | j2                  j1                  |       y)	a  Register the operator to use the AOTI-compiled implementation.

        Args:
            op_name: operator name (along with the overload) or OpOverload object.
            dispatch_key: dispatch key that the input function should be registered for. By default, it uses
                          the dispatch key that the library was created with.

        Example::
            >>> my_lib = Library("aten", "IMPL")
            >>> my_lib._impl_with_aoti_compile("div.Tensor", "CPU")
        NrL   rP   zd_impl_with_aoti_compile should be passed either a name or an OpOverload object as the first argument/rQ   This is not allowed since there's already a kernel registered from python overriding {}'s behavior for {} dispatch key and {} namespace.)r/   r0   r1   r2   r3   rA   DispatchKeySethasr8   DispatchKeyDenserS   strr   _schemar_   overload_namerR   r;   rU   r   formatr:   impl_with_aoti_compiler\   r>   )rE   ru   rA   r_   r   keyimpl_fns          r%   _impl_with_aoti_compilezLibrary._impl_with_aoti_compile   s    %%'NN&&(2,,L##L155ehh6J6J6P6PQQQgs#D,??''D#OO99M"czM1( 
 ggmdjj.r22S8<G&= DDJFJJt$R(,E  vv!!! FF99D)"-|<

33r$   Fwith_keysetc                   t        j                         rt        j                  j	                          yt        |      st        dt        |             |dk(  r| j                  }t        |t              r|}nUt        |t              r:|j                  j                  }|j                  j                  }|dk7  r|dz   |z   }nt        d      | j                   dz   |j#                  d      d   z   dz   |z   }|t$        v r8t        d	j'                  |j#                  d      d   || j                               |d
k(  rF|}d|vr| j                    d| }t         j(                  j+                  |d      rt        d| d      | j,                  J | j,                  j/                  ||dk7  r|nd||       t$        j1                  |       | j2                  j1                  |       y)a  Registers the function implementation for an operator defined in the library.

        Args:
            op_name: operator name (along with the overload) or OpOverload object.
            fn: function that's the operator implementation for the input dispatch key or :func:`~fallthrough_kernel`
                to register a fallthrough.
            dispatch_key: dispatch key that the input function should be registered for. By default, it uses
                          the dispatch key that the library was created with.
            with_keyset: flag controlling if the current dispatcher call keyset should be passed as the first argument
                         to :attr:`fn` when calling. This should be used to create the appropriate keyset for redispatch calls.

        Example::
            >>> my_lib = Library("aten", "IMPL")
            >>> def div_cpu(self, other):
            >>>     return self * (1 / other)
            >>> my_lib.impl("div.Tensor", div_cpu, "CPU")
        Nz;Input function is required to be a callable but found type rL   rP   zQimpl should be passed either a name or an OpOverload object as the first argumentr   rQ   r   r   MetaCompositeImplicitAutogradz?We should not register a meta kernel directly to the operator 'z', because it has a CompositeImplicitAutograd kernel in core. Instead we should let the operator decompose, and ensure that we have meta kernels for the base ops that it decomposes into.)r/   r0   r1   r2   r3   callable	TypeErrortyperA   rS   r   r   r   r_   r   rR   r;   rU   r   r   r8   %_dispatch_has_kernel_for_dispatch_keyr:   r   r\   r>   )	rE   ru   rv   rA   r   r_   r   r   dispatcher_op_names	            r%   r   zLibrary.impl  s   $ %%'NN&&(|MdSUhZX  2,,Lgs#D,??''D#OO99M"czM1c  ggmdjj.r22S8<G&= DDJFJJt$R(,E  6!!%--(,y3E2F%G" xx=="$? #UVZU[ \A A  vv!!!(B.L4O		
 	

33r$   c                >   t        j                         rt        j                  j	                          y|dk(  r| j
                  }| j                  dk7  rt        d| j                         |dk7  sJ | j                  J | j                  j                  |||       y)a  Registers the function implementation as the fallback for the given key.

        This function only works for a library with global namespace ("_").

        Args:
            fn: function used as fallback for the given dispatch key or :func:`~fallthrough_kernel`
                to register a fallthrough.
            dispatch_key: dispatch key that the input function should be registered for. By default, it uses
                          the dispatch key that the library was created with.
            with_keyset: flag controlling if the current dispatcher call keyset should be passed as the first argument
                         to :attr:`fn` when calling. This should be used to create the appropriate keyset for redispatch calls.

        Example::
            >>> my_lib = Library("_", "IMPL")
            >>> def fallback_kernel(op, *args, **kwargs):
            >>>     # Handle all autocast ops generically
            >>>     # ...
            >>> my_lib.fallback(fallback_kernel, "Autocast")
        NrL   _z\Fallback can only be registered using libary fragment on the global namespace "_" but it is )
r/   r0   r1   r2   r3   rA   r;   rR   r:   fallback)rE   rv   rA   r   s       r%   r   zLibrary.fallbackg  s    ( %%'NN&&(2,,L77c>pquqxqxpy|  r!!!vv!!!b+6r$   c                 >   | j                   | j                   j                          d | _         | j                  D ]  }|j                           | j                  j	                          t
        | j                  z  a| j                  D ]  }|j                  d      \  }}|j                  d      d   }t        t        j                  |      sFt        t        j                  |      }t        ||      smt        ||       |j                  j                  |        y )NrQ   rP   r   )r:   resetr?   destroyclearr   r>   r=   rU   rV   r/   rW   rX   delattr_dirremove)rE   r}   r_   r;   name_with_overload	namespaces         r%   _destroyzLibrary._destroy  s    66FFLLN00 	FNN	""((*$.. MM 	(D &*ZZ%5"B"%++C03D599b)		2.I9d+It$NN!!$'	(r$   NrL   )rf   )rl   
__module____qualname____doc__rG   rI   r   r~   r   r   r   r   r   r#   r$   r%   r   r   ;   sQ    $$
L]2 2h2<221 fP  P d#75 #7J(r$   r   c                 F    | |z  } ||z  }|D ]  }|j                           y N)r   )captured_implsop_implscaptured_defsop_defsregistration_handlesr}   s         r%   rD   rD     s1     hNWM& r$   c               /   v   K   	 t        | i |}| |j                          y # j                          w xY wwr   )r   r   )argskwargslibs      r%   _scoped_libraryr     s1     t&v&	s   9$ 969_keep_alivez\(.*\) -> .*r#   )r   rJ   c                f   t        | t              st        dt        |              t        j
                  j                  j                  |       \  }}|!t        |d      }t        j                  |       t        j                  |      st        d| d      |j                  ||z   d|       y)a  Defines a new operator.

    In PyTorch, defining an op (short for "operator") is a two step-process:
    - we need to define the op (by providing an operator name and schema)
    - we need to implement behavior for how the operator interacts with
    various PyTorch subsystems, like CPU/CUDA Tensors, Autograd, etc.

    This entrypoint defines the custom operator (the first step)
    you must then perform the second step by calling various
    ``impl_*`` APIs, like :func:`torch.library.impl` or
    :func:`torch.library.register_fake`.

    Args:
        qualname (str): The qualified name for the operator. Should be
            a string that looks like "namespace::name", e.g. "aten::sin".
            Operators in PyTorch need a namespace to
            avoid name collisions; a given operator may only be created once.
            If you are writing a Python library, we recommend the namespace to
            be the name of your top-level module.
        schema (str): The schema of the operator. E.g. "(Tensor x) -> Tensor"
            for an op that accepts one Tensor and returns one Tensor. It does
            not contain the operator name (that is passed in ``qualname``).
        lib (Optional[Library]): If provided, the lifetime of this operator
            will be tied to the lifetime of the Library object.
        tags (Tag | Sequence[Tag]): one or more torch.Tag to apply to this
            operator. Tagging an operator changes the operator's behavior
            under various PyTorch subsystems; please read the docs for the
            torch.Tag carefully before applying it.

    Example::
        >>> import torch
        >>> import numpy as np
        >>>
        >>> # Define the operator
        >>> torch.library.define("mylib::sin", "(Tensor x) -> Tensor")
        >>>
        >>> # Add implementations for the operator
        >>> @torch.library.impl("mylib::sin", "cpu")
        >>> def f(x):
        >>>     return torch.from_numpy(np.sin(x.numpy()))
        >>>
        >>> # Call the new operator from torch.ops.
        >>> x = torch.randn(3)
        >>> y = torch.ops.mylib.sin(x)
        >>> assert torch.allclose(y, x.sin())

    zGdefine(qualname, schema): expected qualname to be instance of str, got Nr*   zadefine(qualname, schema, ...): expected schema to look like e.g. "(Tensor x) -> Tensor" but got ""rL   )r^   rJ   )rS   r   r-   r   r/   r1   r2   parse_namespacer   r   rt   NAMELESS_SCHEMA	fullmatchr   )rc   r]   r   rJ   r   r_   s         r%   r   r     s    b h$**.x.)9;
 	
 nn**::8DOIt
{i,3$$V,81
 	

 JJtf}RdJ;r$   r   c                       fd}|S )zOThe old torch.library.define.
    We're keeping this around for BC reasons
    c                 P    j                        }j                  ||        | S r   )r   r   )fr_   r^   r   r]   s     r%   wrapz_.<locals>.wrap  s&    zz&.1qr$   r#   )r   r]   r^   r   s   ``` r%   r   r     s    
 Kr$   )r   c                "    t        | |||d      S )a  Register an implementation for a device type for this operator.

    You may pass "default" for ``types`` to register this implementation as the
    default implementation for ALL device types.
    Please only use this if the implementation truly supports all device types;
    for example, this is true if it is a composition of built-in PyTorch operators.

    Some valid types are: "cpu", "cuda", "xla", "mps", "ipu", "xpu".

    Args:
        qualname (str): Should be a string that looks like "namespace::operator_name".
        types (str | Sequence[str]): The device types to register an impl to.
        lib (Optional[Library]): If provided, the lifetime of this registration
            will be tied to the lifetime of the Library object.

    Examples:
        >>> import torch
        >>> import numpy as np
        >>>
        >>> # Define the operator
        >>> torch.library.define("mylib::mysin", "(Tensor x) -> Tensor")
        >>>
        >>> # Add implementations for the cpu device
        >>> @torch.library.impl("mylib::mysin", "cpu")
        >>> def f(x):
        >>>     return torch.from_numpy(np.sin(x.numpy()))
        >>>
        >>> x = torch.randn(3)
        >>> y = torch.ops.mylib.mysin(x)
        >>> assert torch.allclose(y, x.sin())
    Fr   disable_dynamo)_impl)rc   typesfuncr   s       r%   r   r     s    B 5$CFFr$   Fr   c                    t        |t              r|f}t        i       |D ]O  }t        j                  j                  |      }|rj                  |       6j                  t        |             Q  fd}||S  ||       y )Nc                 J    t         j                  j                  j                  	      \  }}"t	        |d      }t
        j                  |       n}r3t         j                   fd       }D ]  }|j                  	||        y D ]  }|j                  	 |        y )Nr*   c                       | i |S r   r#   )r   r   r   s     r%   func_no_dynamoz/_impl.<locals>.register.<locals>.func_no_dynamoS  s    T,V,,r$   )	r/   r1   r2   r   r   r   rt   _disable_dynamor   )
r   r   r   use_libr   r   r   keysr   rc   s
   `     r%   rs   z_impl.<locals>.registerI  s    ~~++;;HE	1;i4Gw'G""- #-  <X~s;<  2XtS12r$   )rS   r   r<   r/   r8   _parse_dispatch_keyr\   _device_type_to_key)	rc   r   r   r   r   typis_dispatch_keyrs   r   s	   `  ``   @r%   r   r   8  sz    %r7D /((66s; HHSMHH(-./2( |r$   device_typereturnc                 L    | dk(  ryt         j                  j                  |       S )NdefaultCompositeExplicitAutograd)r/   r8   _dispatch_key_for_device)r   s    r%   r   r   c  s$    i
 +88,,[99r$   c                       fd}|S )z1Legacy torch.library.impl API. Kept around for BCc                 .    j                  |        | S r   )r   )r   rA   r   r_   s    r%   r   z_.<locals>.wrapq  s    q,'r$   r#   )r   r_   rA   r   s   ``` r%   r   r   m  s     Kr$   z`torch.library.impl_abstract` was renamed to `torch.library.register_fake`. Please use that instead; we will remove `torch.library.impl_abstract` in a future version of PyTorch.)categoryrf   r   rw   c                .    ||dz   }t        | |||      S )zmThis API was renamed to :func:`torch.library.register_fake` in PyTorch 2.4.
    Please use that instead.
    rf   r   )r   )rc   r   r   rw   s       r%   r   r   x  s$     !Ao4SkJJr$   ztorch._ops.OpOverloadz%torch._library.custom_ops.CustomOpDefopdevice_typesr   c                  t        | t        t        j                  j                  t        j
                  j                  j                  f      st        d      t        | t        j                  j                        r| j                  } t        |       }||j                  ||      S t        | t              sJ |d}t        | |||d      S )a  Register an implementation for a device type for this operator.

    Some valid device_types are: "cpu", "cuda", "xla", "mps", "ipu", "xpu".
    This API may be used as a decorator.

    Args:
        op (str | OpOverload): The operator to register an impl to.
        device_types (None | str | Sequence[str]): The device_types to register an impl to.
            If None, we will register to all device types -- please only use
            this option if your implementation is truly device-type-agnostic.
        func (Callable): The function to register as the implementation for
            the given device types.
        lib (Optional[Library]): If provided, the lifetime of this registration

    Examples::
        >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA)
        >>> import torch
        >>> from torch import Tensor
        >>> from torch.library import custom_op
        >>> import numpy as np
        >>>
        >>> # Create a custom op that works on cpu
        >>> @custom_op("mylib::numpy_sin", mutates_args=(), device_types="cpu")
        >>> def numpy_sin(x: Tensor) -> Tensor:
        >>>     x_np = x.numpy()
        >>>     y_np = np.sin(x_np)
        >>>     return torch.from_numpy(y_np)
        >>>
        >>> # Add implementations for the cuda device
        >>> @torch.library.register_kernel("mylib::numpy_sin", "cuda")
        >>> def _(x):
        >>>     x_np = x.cpu().numpy()
        >>>     y_np = np.sin(x_np)
        >>>     return torch.from_numpy(y_np).to(device=x.device)
        >>>
        >>> x_cpu = torch.randn(3)
        >>> x_cuda = x_cpu.cuda()
        >>> assert torch.allclose(numpy_sin(x_cpu), x_cpu.sin())
        >>> assert torch.allclose(numpy_sin(x_cuda), x_cuda.sin())

    z;register_kernel(op): got unexpected type for op: {type(op)}r   Tr   )rS   r   r/   rZ   r   r1   
custom_opsr   r-   _namer   register_kernelr   )r   r   r   r   opdefs        r%   r   r     s    d 
S%**'')B)B)N)NO VWW"ejj++,XXR E$$\488b#2\4SFFr$   rw   c                   t         t        t        j                  j                  t        j
                  j                  j                  f      st        d      t         t        j                  j                        r j                   t               }|||j                  S |j                  |      S t         t              sJ | fd}||S dz   ||      S )a  Register a FakeTensor implementation ("fake impl") for this operator.

    Also sometimes known as a "meta kernel", "abstract impl".

    An "FakeTensor implementation" specifies the behavior of this operator on
    Tensors that carry no data ("FakeTensor"). Given some input Tensors with
    certain properties (sizes/strides/storage_offset/device), it specifies
    what the properties of the output Tensors are.

    The FakeTensor implementation has the same signature as the operator.
    It is run for both FakeTensors and meta tensors. To write a FakeTensor
    implementation, assume that all Tensor inputs to the operator are
    regular CPU/CUDA/Meta tensors, but they do not have storage, and
    you are trying to return regular CPU/CUDA/Meta tensor(s) as output.
    The FakeTensor implementation must consist of only PyTorch operations
    (and may not directly access the storage or data of any input or
    intermediate Tensors).

    This API may be used as a decorator (see examples).

    For a detailed guide on custom ops, please see
    https://pytorch.org/tutorials/advanced/custom_ops_landing_page.html

    Examples:
        >>> import torch
        >>> import numpy as np
        >>> from torch import Tensor
        >>>
        >>> # Example 1: an operator without data-dependent output shape
        >>> @torch.library.custom_op("mylib::custom_linear", mutates_args=())
        >>> def custom_linear(x: Tensor, weight: Tensor, bias: Tensor) -> Tensor:
        >>>     raise NotImplementedError("Implementation goes here")
        >>>
        >>> @torch.library.register_fake("mylib::custom_linear")
        >>> def _(x, weight, bias):
        >>>     assert x.dim() == 2
        >>>     assert weight.dim() == 2
        >>>     assert bias.dim() == 1
        >>>     assert x.shape[1] == weight.shape[1]
        >>>     assert weight.shape[0] == bias.shape[0]
        >>>     assert x.device == weight.device
        >>>
        >>>     return (x @ weight.t()) + bias
        >>>
        >>> with torch._subclasses.fake_tensor.FakeTensorMode():
        >>>     x = torch.randn(2, 3)
        >>>     w = torch.randn(3, 3)
        >>>     b = torch.randn(3)
        >>>     y = torch.ops.mylib.custom_linear(x, w, b)
        >>>
        >>> assert y.shape == (2, 3)
        >>>
        >>> # Example 2: an operator with data-dependent output shape
        >>> @torch.library.custom_op("mylib::custom_nonzero", mutates_args=())
        >>> def custom_nonzero(x: Tensor) -> Tensor:
        >>>     x_np = x.numpy(force=True)
        >>>     res = np.stack(np.nonzero(x_np), axis=1)
        >>>     return torch.tensor(res, device=x.device)
        >>>
        >>> @torch.library.register_fake("mylib::custom_nonzero")
        >>> def _(x):
        >>> # Number of nonzero-elements is data-dependent.
        >>> # Since we cannot peek at the data in an fake impl,
        >>> # we use the ctx object to construct a new symint that
        >>> # represents the data-dependent size.
        >>>     ctx = torch.library.get_ctx()
        >>>     nnz = ctx.new_dynamic_size()
        >>>     shape = [nnz, x.dim()]
        >>>     result = x.new_empty(shape, dtype=torch.int64)
        >>>     return result
        >>>
        >>> from torch.fx.experimental.proxy_tensor import make_fx
        >>>
        >>> x = torch.tensor([0, 1, 2, 3, 4, 0])
        >>> trace = make_fx(torch.ops.mylib.custom_nonzero, tracing_mode="symbolic")(x)
        >>> trace.print_readable()
        >>>
        >>> assert torch.allclose(trace(x), torch.ops.mylib.custom_nonzero(x))

    z9register_fake(op): got unexpected type for op: {type(op)}c                     t         j                  j                  j                        \  }}"t	        |d      }t
        j                  |       n}|j                  || dz          | S )Nr*   rf   )rw   )r/   r1   r2   r   r   r   rt   r~   )r   r   ru   r   r   r   
stacklevels       r%   rs   zregister_fake.<locals>.register5  sd    "^^11AA"E	7;i4Gw'Gw*q.Ir$   rf   )rS   r   r/   rZ   r   r1   r   r   r-   r   r   r   )r   r   r   rw   r   rs   r   s   ` `   @r%   r   r     s    p 
S%**'')B)B)N)NO TUU"ejj++,XXR E<&&&&&t,,b#J |a
~r$   )setup_contextr   backwardr   c                  t        | t        t        j                  j                  t        j
                  j                  j                  f      st        dt        |              t        | t        j                  j                        r| j                  } t        |       }||j                  ||       yt        | t              sJ | }t        j
                  j                  j                  |      } | j                  }t
        j                  j!                  |      st#        d|  d| d      t
        j                  j%                  |      rt'        d|       t
        j(                  j+                  ||      }t
        j(                  j-                  | |      }t        j
                  j                  j/                  |      \  }	}
|!t1        |	d      }t2        j5                  |       |j7                  |
|d	d
       y)a  Register a backward formula for this custom op.

    In order for an operator to work with autograd, you need to register
    a backward formula:
    1. You must tell us how to compute gradients during the backward pass
    by providing us a "backward" function.
    2. If you need any values from the forward to compute gradients, you can
    use `setup_context` to save values for backward.

    ``backward`` runs during the backward pass. It accepts ``(ctx, *grads)``:
    - ``grads`` is one or more gradients. The number of gradients matches
    the number of outputs of the operator.
    The ``ctx`` object is `the same ctx object <context_method_mixins>`_ used by
    :class:`torch.autograd.Function`. The semantics of ``backward_fn`` are the
    same as :meth:`torch.autograd.Function.backward`.

    ``setup_context(ctx, inputs, output)`` runs during the forward pass.
    Please save quantities needed for backward onto the ``ctx`` object via
    either :meth:`torch.autograd.function.FunctionCtx.save_for_backward`
    or assigning them as attributes of ``ctx``. If your custom op has
    kwarg-only arguments, we expect the signature of ``setup_context``
    to be ``setup_context(ctx, inputs, keyword_only_inputs, output)``.

    Both ``setup_context_fn`` and ``backward_fn`` must be traceable. That is,
    they may not directly access :meth:`torch.Tensor.data_ptr` and they must
    not depend on or mutate global state. If you need a non-traceable backward,
    you can make it a separate custom_op that you call inside ``backward_fn``.

    If you need different autograd behavior on different devices, then we
    recommend creating two different custom operators, one for each device
    that needs different behavior, and switching between them at runtime.

    Examples:
        >>> import torch
        >>> import numpy as np
        >>> from torch import Tensor
        >>>
        >>> @torch.library.custom_op("mylib::numpy_sin", mutates_args=())
        >>> def numpy_sin(x: Tensor) -> Tensor:
        >>>     x_np = x.cpu().numpy()
        >>>     y_np = np.sin(x_np)
        >>>     return torch.from_numpy(y_np).to(device=x.device)
        >>>
        >>> def setup_context(ctx, inputs, output) -> Tensor:
        >>>     x, = inputs
        >>>     ctx.save_for_backward(x)
        >>>
        >>> def backward(ctx, grad):
        >>>     x, = ctx.saved_tensors
        >>>     return grad * x.cos()
        >>>
        >>> torch.library.register_autograd(
        ...     "mylib::numpy_sin", backward, setup_context=setup_context
        ... )
        >>>
        >>> x = torch.randn(3, requires_grad=True)
        >>> y = numpy_sin(x)
        >>> (grad_x,) = torch.autograd.grad(y, x, torch.ones_like(y))
        >>> assert torch.allclose(grad_x, x.cos())
        >>>
        >>> # Example with a keyword-only arg
        >>> @torch.library.custom_op("mylib::numpy_mul", mutates_args=())
        >>> def numpy_mul(x: Tensor, *, val: float) -> Tensor:
        >>>     x_np = x.cpu().numpy()
        >>>     y_np = x_np * val
        >>>     return torch.from_numpy(y_np).to(device=x.device)
        >>>
        >>> def setup_context(ctx, inputs, keyword_only_inputs, output) -> Tensor:
        >>>     ctx.val = keyword_only_inputs["val"]
        >>>
        >>> def backward(ctx, grad):
        >>>     return grad * ctx.val
        >>>
        >>> torch.library.register_autograd(
        ...     "mylib::numpy_mul", backward, setup_context=setup_context
        ... )
        >>>
        >>> x = torch.randn(3, requires_grad=True)
        >>> y = numpy_mul(x, val=3.14)
        >>> (grad_x,) = torch.autograd.grad(y, x, torch.ones_like(y))
        >>> assert torch.allclose(grad_x, torch.full_like(x, 3.14))

    z3register_autograd(op): got unexpected type for op: N)r   z=Cannot register autograd formula for non-functional operator z with schema zP. Please create a functional operator and register an autograd formula for that.zregister_autograd with kwarg-only Tensor args. In the original definition of the op, please make your tensors not kwarg-only. Got: r*   AutogradTr   )rS   r   r/   rZ   r   r1   r   r   r-   r   r   r   register_autogradr2   	lookup_opr   is_functional_schemarR   has_kwarg_only_tensorsr"   autogradInfomake_autograd_implr   r   r   rt   r   )r   r   r   r   r   rc   r]   infoautograd_kernelr   opnames              r%   r   r   F  s   v 
S%**'')B)B)N)NO A$r(L
 	
 "ejj++,XXR EFb#H				'	'	1BZZF>>..v6Kd-x (OP
 	

 ~~,,V4!8
 	
 !!(M:D''::2tDO,,<<XFIv
{i,3HHV_jdHCr$   r   c                   t         t        t        j                  j                  t        j
                  j                  j                  f      st        d      t         t        j                  j                        r j                   t               }||j                  |      S t         t              sJ  fd}||S  ||      S )a  Registers a torch_dispatch rule for the given operator and ``torch_dispatch_class``.

    This allows for open registration to specify the behavior between the operator
    and the ``torch_dispatch_class`` without needing to modify the ``torch_dispatch_class``
    or the operator directly.

    The ``torch_dispatch_class`` is either a Tensor subclass with ``__torch_dispatch__`` or a
    TorchDispatchMode.

    If it is a Tensor subclass, we expect ``func`` to have the following signature:
    ``(cls, func: OpOverload, types: Tuple[type, ...], args, kwargs) -> Any``

    If it is a TorchDispatchMode, we expect ``func`` to have the following signature:
    ``(mode, func: OpOverload, types: Tuple[type, ...], args, kwargs) -> Any``

    ``args`` and ``kwargs`` will have been normalized the same way they are
    in ``__torch_dispatch__`` (see :ref:`torch-dispatch-calling-convention`).

    Examples:

        >>> import torch
        >>>
        >>> @torch.library.custom_op("mylib::foo", mutates_args={})
        >>> def foo(x: torch.Tensor) -> torch.Tensor:
        >>>     return x.clone()
        >>>
        >>> class MyMode(torch.utils._python_dispatch.TorchDispatchMode):
        >>>     def __torch_dispatch__(self, func, types, args=(), kwargs=None):
        >>>         return func(*args, **kwargs)
        >>>
        >>> @torch.library.register_torch_dispatch("mylib::foo", MyMode)
        >>> def _(mode, func, types, args, kwargs):
        >>>     x, = args
        >>>     return x + 1
        >>>
        >>> x = torch.randn(3)
        >>> y = foo(x)
        >>> assert torch.allclose(y, x)
        >>>
        >>> with MyMode():
        >>>     y = foo(x)
        >>> assert torch.allclose(y, x + 1)

    zCregister_torch_dispatch(op): got unexpected type for op: {type(op)}c                     t         j                  j                  j                        \  }}"t	        |d      }t
        j                  |       n}|j                  ||        | S )Nr*   )r/   r1   r2   r   r   r   rt   r   )r   r   ru   r   r   r   r   s       r%   rs   z)register_torch_dispatch.<locals>.register	  s^    "^^11AA"E	7;i4Gw'G--g7KTRr$   )rS   r   r/   rZ   r   r1   r   r   r-   r   r   r   )r   r   r   r   r   rs   s   `` `  r%   r   r     s    h 
S%**'')B)B)N)NO Q
 	
 "ejj++,XXR E,,-A4HHb# |~r$   c               ~    t         t        t        j                  j                  t        j
                  j                  j                  f      st        dt                      t         t        j                  j                        r j                   t               }||j                  |      S t         t              sJ  t        j
                  j                  j                          j                  }t
        j                  j!                  |      rt#        d|        fd}||S  ||      S )a  Register a vmap implementation to support :func:`torch.vmap` for this custom op.

    This API may be used as a decorator (see examples).

    In order for an operator to work with :func:`torch.vmap`, you may need to register a
    vmap implementation in the following signature:

        ``vmap_func(info, in_dims: Tuple[Optional[int]], *args, **kwargs)``,

    where ``*args`` and ``**kwargs`` are the arguments and kwargs for ``op``.
    We do not support kwarg-only Tensor args.

    It specifies how do we compute the batched version of ``op`` given inputs with an additional
    dimension (specified by ``in_dims``).

    For each arg in ``args``, ``in_dims`` has a corresponding ``Optional[int]``. It is ``None``
    if the arg is not a Tensor or if the arg is not being vmapped over, otherwise, it is an integer
    specifying what dimension of the Tensor is being vmapped over.

    ``info`` is a collection of additional metadata that may be helpful:
    ``info.batch_size`` specifies the size of the dimension being vmapped over, while
    ``info.randomness`` is the ``randomness`` option that was passed to :func:`torch.vmap`.

    The return of the function ``func`` is a tuple of ``(output, out_dims)``. Similar to ``in_dims``,
    ``out_dims`` should be of the same structure as ``output`` and contain one ``out_dim``
    per output that specifies if the output has the vmapped dimension and what index it is in.

    Examples:
        >>> import torch
        >>> import numpy as np
        >>> from torch import Tensor
        >>> from typing import Tuple
        >>>
        >>> def to_numpy(tensor):
        >>>     return tensor.cpu().numpy()
        >>>
        >>> lib = torch.library.Library("mylib", "FRAGMENT")
        >>> @torch.library.custom_op("mylib::numpy_cube", mutates_args=())
        >>> def numpy_cube(x: Tensor) -> Tuple[Tensor, Tensor]:
        >>>     x_np = to_numpy(x)
        >>>     dx = torch.tensor(3 * x_np ** 2, device=x.device)
        >>>     return torch.tensor(x_np ** 3, device=x.device), dx
        >>>
        >>> def numpy_cube_vmap(info, in_dims, x):
        >>>     result = numpy_cube(x)
        >>>     return result, (in_dims[0], in_dims[0])
        >>>
        >>> torch.library.register_vmap(numpy_cube, numpy_cube_vmap)
        >>>
        >>> x = torch.randn(3)
        >>> torch.vmap(numpy_cube)(x)
        >>>
        >>> @torch.library.custom_op("mylib::numpy_mul", mutates_args=())
        >>> def numpy_mul(x: Tensor, y: Tensor) -> Tensor:
        >>>     return torch.tensor(to_numpy(x) * to_numpy(y), device=x.device)
        >>>
        >>> @torch.library.register_vmap("mylib::numpy_mul")
        >>> def numpy_mul_vmap(info, in_dims, x, y):
        >>>     x_bdim, y_bdim = in_dims
        >>>     x = x.movedim(x_bdim, -1) if x_bdim is not None else x.unsqueeze(-1)
        >>>     y = y.movedim(y_bdim, -1) if y_bdim is not None else y.unsqueeze(-1)
        >>>     result = x * y
        >>>     result = result.movedim(-1, 0)
        >>>     return result, 0
        >>>
        >>>
        >>> x = torch.randn(3)
        >>> y = torch.randn(3)
        >>> torch.vmap(numpy_mul)(x, y)

    .. note::
        The vmap function should aim to preserve the semantics of the entire custom operator.
        That is, ``grad(vmap(op))`` should be replaceable with a ``grad(map(op))``.

        If your custom operator has any custom behavior in the backward pass, please
        keep this in mind.

    z/register_vmap(op): got unexpected type for op: zregister_vmap with kwarg-only Tensor args. In the original definition of the op, please make your tensors not kwarg-only. Got: c                      t         j                  j                  j                        \  }}!t	        |d      t
        j                         ddlm ddl	m
  fd}j                  ||dd       y )	Nr*   r   ) custom_function_call_vmap_helper)&retrieve_current_functorch_interpreterc                 .            } |g|i |S r   r#   )keysetr   r   interpreterr   r   r   r   s       r%   wrapped_funcz5register_vmap.<locals>.register.<locals>.wrapped_func  s/    @BK3T2(,06 r$   FuncTorchBatchedTr   )r/   r1   r2   r   r   r   rt   "torch._functorch.autograd_functionr   torch._functorch.pyfunctorchr   r   )	r   r   r   r  r   r   r   r   rc   s	   `   @@r%   rs   zregister_vmap.<locals>.register  se     "NN00@@J	6;)Z0Cs#WW	 	'9tLr$   )rS   r   r/   rZ   r   r1   r   r   r-   r   r   r   r   r2   r   r   r   r"   )r   r   r   r   r]   rs   rc   s   ` `   @r%   r   r     s   j 
S%**'')B)B)N)NO J4PR8*UVV"ejj++,XXR E""4((b#H				'	'	1BZZF~~,,V4!8
 	
M& |~r$   c                 "     d fd}|S )NFc                     r 	| i |S t         j                  j                  j                  
      }|j                  r
d 	| i |S t         j
                  j                  |j                  j                  |j                  j                        }|ft         j                  j                  j                         rz|j                  }|j                  j                         }t        d
 d d| d| d	      |d   }|k7  r2|j                  j                         }t        d
 d| d	 d
| d	      d 	| i |S )NTz
Operator 'z' was defined in C++ and has a Python fake impl. In this situation, we require there to also be a companion C++ `m.set_python_module("z\")` call, but we could not find one. Please add that to to the top of the C++ TORCH_LIBRARY(z-, ...) block the operator was registered in ()r   z?' specified that its python fake impl is in the Python module 'z ' but it was actually found in 'zM'. Please either move the fake impl or correct the m.set_python_module call ()r/   r1   r2   r   _defined_in_pythonr8   _dispatch_pystubr   r_   r   requires_set_python_moduler   _handledebugrR   )r   r   r   maybe_pystubr   cpp_filenamepystub_moduleactual_module_namecheckedr   rc   s          r%   innerz"_check_pystubs_once.<locals>.inner  sg   (((^^!!++H5  G(((xx00JJOORZZ55
 ~~##>>@LL	!zz//1" 
 +;;M:N O;;D+ F33?.C  )OM!]2!zz//1" 
 +00= ?-. /@@L~QP  T$V$$r$   r#   )r   rc   r  r  r  s   ``` @r%   rq   rq     s    G$%L Lr$   c                  R    t         j                  j                  j                         S )zget_ctx() returns the current AbstractImplCtx object.

    Calling ``get_ctx()`` is only valid inside of an fake impl
    (see :func:`torch.library.register_fake` for more usage details.
    )r/   r1   rr   global_ctx_getterr#   r$   r%   r   r     s     >>##5577r$   )test_schematest_autograd_registrationtest_faketensortest_aot_dispatch_dynamicT
test_utilsraise_exceptionr   .r   r  r  c                F    ddl mc mc m} |j	                  | ||||      S )a  Given an operator and some sample arguments, tests if the operator is
    registered correctly.

    That is, when you use the torch.library/TORCH_LIBRARY APIs to create a
    custom op, you specified metadata (e.g. mutability info) about the custom op
    and these APIs require that the functions you pass them satisfy certain
    properties (e.g. no data pointer access in the fake/meta/abstract kernel)
    ``opcheck`` tests these metadata and properties.

    Concretely, we test the following:

    - test_schema: If the schema matches the implementation of
      the operator. For example: if the schema specifies a Tensor is mutated,
      then we check the implementation mutates the Tensor. If the schema
      specifies that we return a new Tensor, then we check that the
      implementation returns a new Tensor (instead of an existing one or
      a view of an existing one).
    - test_autograd_registration: If the operator supports training
      (autograd): we check that its autograd formula is registered via
      torch.library.register_autograd or a manual registration to one
      or more DispatchKey::Autograd keys. Any other DispatchKey-based
      registrations may lead to undefined behavior.
    - test_faketensor: If the operator has a FakeTensor kernel
      (and if it is correct). The FakeTensor kernel is necessary (
      but not sufficient) for the operator to work with PyTorch compilation
      APIs (torch.compile/export/FX). We check that a FakeTensor kernel
      (also sometimes known as a meta kernel) was registered for the
      operator and that it is correct. This test takes the result of
      running the operator on real tensors and the result of running
      the operator on FakeTensors and checks that they have the same
      Tensor metadata (sizes/strides/dtype/device/etc).
    - test_aot_dispatch_dynamic: If the operator has correct behavior
      with PyTorch compilation APIs (torch.compile/export/FX).
      This checks that the outputs (and gradients, if applicable) are the
      same under eager-mode PyTorch and torch.compile.
      This test is a superset of ``test_faketensor`` and is an e2e test;
      other things it tests are that the operator supports
      functionalization and that the backward pass (if it exists) also
      supports FakeTensor and functionalization.

    For best results, please call ``opcheck`` multiple times with a
    representative set of inputs. If your operator supports
    autograd, please use ``opcheck`` with inputs with ``requires_grad = True``;
    if your operator supports multiple devices (e.g. CPU and CUDA), please
    use ``opcheck`` with inputs on all supported devices.

    Args:
        op: The operator. Must either be a function decorated with
            :func:`torch.library.custom_op` or an OpOverload/OpOverloadPacket
            found in torch.ops.* (e.g. torch.ops.aten.sin, torch.ops.mylib.foo)
        args: The args to the operator
        kwargs: The kwargs to the operator
        test_utils: Tests that we should run. Default: all of them.
            Example: ("test_schema", "test_faketensor")
        raise_exception: If we should raise an exception on the first
            error. If False, we will return a dict with information
            on if each test passed or not.

    .. warning::

        opcheck and :func:`torch.autograd.gradcheck` test different things;
        opcheck tests if your usage of torch.library APIs is correct while
        :func:`torch.autograd.gradcheck` tests if your autograd formula is
        mathematically correct. Use both to test custom ops that support
        gradient computation.

    Example:

        >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA)
        >>> @torch.library.custom_op("mylib::numpy_mul", mutates_args=())
        >>> def numpy_mul(x: Tensor, y: float) -> Tensor:
        >>>     x_np = x.numpy(force=True)
        >>>     z_np = x_np * y
        >>>     return torch.from_numpy(z_np).to(x.device)
        >>>
        >>> @numpy_mul.register_fake
        >>> def _(x, y):
        >>>     return torch.empty_like(x)
        >>>
        >>> def setup_context(ctx, inputs, output):
        >>>     y, = inputs
        >>>     ctx.y = y
        >>>
        >>> def backward(ctx, grad):
        >>>     return grad * ctx.y, None
        >>>
        >>> numpy_mul.register_autograd(backward, setup_context=setup_context)
        >>>
        >>> sample_inputs = [
        >>>     (torch.randn(3), 3.14),
        >>>     (torch.randn(2, 3, device='cuda'), 2.718),
        >>>     (torch.randn(1, 10, requires_grad=True), 1.234),
        >>>     (torch.randn(64, 64, device='cuda', requires_grad=True), 90.18),
        >>> ]
        >>>
        >>> for args in sample_inputs:
        >>>     torch.library.opcheck(numpy_mul, args)

    r   Nr  )torch.testing._internal.opteststesting	_internaloptestsopcheck)r   r   r   r  r  r   s         r%   r!  r!    s,    V 65??
D&Z   r$   r   r   )r   z$torch._library.fake_impl.FakeImplCtx)H
contextlib	functoolsrj   rerh   r4   rB   typingr   r   r   r   r   r   r	   r
   r   typing_extensionsr   r/   torch._libraryr1   torch._library.custom_opsr   r   r   r   torch._library.infer_schemar   torch._library.tritonr   r   
torch._opsr   __all__r<   r   r   __annotations__r   r.   r   r   rD   contextmanagerr   r   compiler   singledispatchr   rs   r   r   r   r   FutureWarningr   _op_identifierr   intr   r   r   r   rq   r   _OPCHECK_DEFAULT_UTILSrZ   OpOverloadPacketboolr!  r#   r$   r%   <module>r7     s      	 
   S S S (  !  5 8 !( 5C %s3x  x Ni( i(X
    T']  "**_- $(r ?< ?<D 
7 
 
  GD  G  GF(T% (V:S :S : 7   \
Kd K
K 	 "II  $?G "?G?G ?G 8
?G 
'	?GH  $v
 "vv
8
v
 
'	v v| )-DDD
 H%D 
DJ  $N "NNN 8
N 
'	Nf  $
 	
8
J)f8  (,o
 -C oejj##UZZ%@%@+MNo
S/o T#s(^$o
 c8C=()o o 
#s(^or$   