U
    zhQ                  
   @   s  U d dl m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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 ddd	d
ddddgZe aee  e!d< e Z"ee  e!d< dgZ#dd
 Z$G dd dZ%dd Z&ej'dd Z(g Z)ee% e!d< e*dZ+ej,ddddd	Z-e-j.dAe%ddd Z/ej,dBddd!dZ0e e d"d#d$Z1e0j.dCe%dd%d Z/ed&e2d'dDdd d(d)dZ3ee d*d+f Z4dEdde4eee ee% d,d-d.Z5dFdd d(e4ee ee% e6d/d0dZ7ddd1e4eee dd2d3d4Z8d5d6 Z9d7d8d9dZ:d:Z;dGe;d;d<eej jej j<ef e	ed=f ee
e ef  ee ee  f e=e
e e f d>d?d@Z>dS )H   )
OpOverload    )	AnyOptionalSetListUnionCallableTupleDictSequence)
deprecatedN)	custom_op_maybe_get_opdefdevice_types_tCustomOpDefLibraryimpldefinefallthrough_kernelimpl_abstractregister_fakeget_ctxr   _impls_defsZprimc                   C   s   t ddS )zZ
    A dummy function to pass to ``Library.impl`` in order to register a fallthrough.
    z,fallthrough_kernel() should never be called.N)NotImplementedError r   r   ?/var/www/html/venv/lib/python3.8/site-packages/torch/library.pyr   &   s    c                   @   s^   e Zd ZdZdddZdd Zdddd	d
ZdddZdddZdddddZ	dd Z
dS )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              	   C   s   |dkrt d||tkr4|dks*|dkr4t |dtjddd }|j|j }}tj|||||| _	|| _
t | _t | _g | _|| _|| _t| tt| jt| j| j d S )	N)ZIMPLDEFFRAGMENTzUnsupported kind: r   r    zJ is a reserved namespace. Please try creating a library with another name.   )limitr   )
ValueError_reserved_namespaces	tracebackextract_stackfilenamelinenotorch_CZ_dispatch_librarymnsset_op_defs	_op_impls_registration_handleskinddispatch_keyweakreffinalize_del_libraryr   r   )selfr,   r1   r2   framer'   r(   r   r   r   __init__>   s    

zLibrary.__init__c                 C   s   d| j  d| j d| j dS )NzLibrary(kind=z, ns=z, dispatch_key=z)>)r1   r,   r2   )r6   r   r   r   __repr__T   s    zLibrary.__repr__r   )tagsc                C   s   |dkrt d| | jdk	s$tt|tjr6|f}|dd }d|krZ|dd n|}ttj| j	o~tt
tj| j	|}| j||t|}|dd }| j	d | }|rt
tj| j	}	t
|	|}
tj|
 | j| t| |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")
        )r   ZFROM_SCHEMAZCONSERVATIVEzInvalid alias_analysis type N(r   .::)RuntimeErrorr+   AssertionError
isinstancer)   Tagsplithasattropsr,   getattrr   tuple_opsZ_refresh_packetr.   addr   )r6   schemaalias_analysisr:   nameZpacket_nameZhas_preexisting_packetresultqualnamer,   packetr   r   r   r   W   s$    "

zLibrary.definer   c                 C   s   t jj|d }t|}t|}|dkr2dn|j}|dk	rN|	drNd}| j
 d| }t jjj|}	|dk	rt|||}
n|}
|	j|
|}| j| dS )z?Registers the fake impl for an operator defined in the library.r   Nztorchvision.r=   )r)   _libraryutils
get_sourcesys	_getframeinspect	getmodule__name__
startswithr,   Zsimple_registryZ	singletonfind_check_pystubs_onceabstract_implregisterr0   append)r6   op_namefn_stacklevelsourcer7   Zcaller_moduleZcaller_module_namerM   entryZfunc_to_registerhandler   r   r   _register_fake   s    

zLibrary._register_fakec                 C   s   |dkr| j }t|tjjjs(tt|t	r8|}n8t|t
rh|jj}|jj}|dkrp|d | }ntd| jd |dd  d | }|tkrtd|dd || j| jdk	st| jj}|| j|dd | t| | j| dS )	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")
        r   r<   zd_impl_with_aoti_compile should be passed either a name or an OpOverload object as the first argument/r=   This is not allowed since there's already a kernel registered from python overriding {}'s behavior for {} dispatch key and {} namespace.N)r2   r)   ZDispatchKeySethasr*   ZDispatchKeyZDenser?   r@   strr   _schemarK   overload_namer>   r,   rB   r   formatr+   Zimpl_with_aoti_compilerH   r/   )r6   r]   r2   rK   rj   keyZimpl_fnr   r   r   _impl_with_aoti_compile   s.    

   
zLibrary._impl_with_aoti_compileFwith_keysetc          	      C   sB  t |stdt| |dkr(| j}t|tr8|}n8t|trh|jj}|jj	}|dkrp|d | }nt
d| jd |dd  d | }|tkrt
d|dd || j|d	kr|}d|kr| j d| }tj|d
rt
d| d| jdk	st| j||dkr|nd
|| t| | j| dS )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.

        Example::
            >>> my_lib = Library("aten", "IMPL")
            >>> def div_cpu(self, other):
            >>>     return self * (1 / other)
            >>> my_lib.impl("div.Tensor", div_cpu, "CPU")
        z;Input function is required to be a callable but found type r   r<   zQimpl should be passed either a name or an OpOverload object as the first argumentrd   r=   re   rf   ZMetaZ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.N)callable	TypeErrortyper2   r@   rh   r   ri   rK   rj   r>   r,   rB   r   rk   r)   r*   Z%_dispatch_has_kernel_for_dispatch_keyr+   r?   r   rH   r/   )	r6   r]   r^   r2   ro   rK   rj   rl   Zdispatcher_op_namer   r   r   r      s>    

   
 
zLibrary.implc                 C   s   | j d k	r| j   d | _ | jD ]}|  q | j  t| j8 a| jD ]P}|d\}}|dd }t	t
j|svqHtt
j|}t	||sqHt|| qHd S )Nr=   r<   r   )r+   resetr0   destroyclearr   r/   r.   rB   rC   r)   rD   rE   delattr)r6   rb   rK   r,   Zname_with_overload	namespacer   r   r   _destroy  s     







zLibrary._destroyN)r   )r   )r   )r   )r   )rV   
__module____qualname____doc__r8   r9   r   rc   rm   r   rx   r   r   r   r   r   ,   s   
.

*=c                 C   s&   | |8 } ||8 }|D ]}|   qd S N)rt   )Zcaptured_implsZop_implsZcaptured_defsZop_defsZregistration_handlesrb   r   r   r   r5     s    r5   c                  o   s$   zt| |}|V  W 5 |   X d S r|   )rx   r   )argskwargslibr   r   r   _scoped_library%  s    

r   _keep_alivez\(.*\) -> .*r   )r   r:   c                C   s|   t | tstdt|  tjj| \}}|dkrJt|d}t	
| t|sdtd| d|j|| d|d dS )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 ""r   )rJ   r:   )r@   rh   r#   rr   r)   rO   rP   parse_namespacer   r   r\   NAMELESS_SCHEMA	fullmatchr   )rM   rI   r   r:   rw   rK   r   r   r   r   4  s    1




r   r   c                    s    fdd}|S )zOThe old torch.library.define.
    We're keeping this around for BC reasons
    c                    s     }||  | S r|   )r   r   )frK   rJ   r   rI   r   r   wrapz  s    _.<locals>.wrapr   )r   rI   rJ   r   r   r   r   _u  s    r   c                   st   t |tr|f}ti  |D ].}tj|}|r< | q t| q fdd}|dkrh|S || 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())
    c                    sP   t jj\}}d kr0t|d}t| n} D ]}|| | q8d S )Nr    )r)   rO   rP   r   r   r   r\   r   )funcrw   r   use_librl   keysr   rM   r   r   r[     s    
zimpl.<locals>.registerN)r@   rh   r-   r)   r*   Z_parse_dispatch_keyrH   _device_type_to_key)rM   typesr   r   typZis_dispatch_keyr[   r   r   r   r     s    !

)device_typereturnc                 C   s   | dkrdS t j| S )NdefaultCompositeExplicitAutograd)r)   r*   Z_dispatch_key_for_device)r   r   r   r   r     s    r   c                    s    fdd}|S )z1Legacy torch.library.impl API. Kept around for BCc                    s    |   | S r|   )r   )r   r2   r   rK   r   r   r     s    r   r   )r   rK   r2   r   r   r   r   r     s    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.)categoryr   r_   c                C   s    |dk	r|d }t | |||dS )zmThis API was renamed to :func:`torch.library.register_fake` in PyTorch 2.4.
    Please use that instead.
    Nr   r   )r   )rM   r   r   r_   r   r   r   r     s    	ztorch._ops.OpOverloadz%torch._library.custom_ops.CustomOpDef)opdevice_typesr   r   c               C   s|   t | ttjjtjjjfs"tdt | tjjr6| j	} t
| }|dk	rR|||S t | ts`t|dkrld}t| |||dS )a5  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:
        fn (Callable): The function to register as the implementation for
            the given device types.
        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.

    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)}Nr   r   )r@   rh   r)   rG   r   rO   
custom_opsr   r#   _namer   register_kernelr?   r   )r   r   r   r   opdefr   r   r   r     s    /r   )r   r   r   r_   c                  s   t ttjjtjjjfs"tdt tjjr6j	t
}|dk	r^|dkrT|jS ||S t tslt| fdd}|dkr|S d7 ||S d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)}Nc                    sL   t jj\}} d kr0t|d}t| n }|j|| d d | S )Nr    r   )r_   )r)   rO   rP   r   r   r   r\   rc   )r   rw   r]   r   r   r   
stacklevelr   r   r[     s    
zregister_fake.<locals>.registerr   )r@   rh   r)   rG   r   rO   r   r   r#   r   r   r   r?   )r   r   r   r_   r   r[   r   r   r   r   "  s     W

)setup_contextr   )r   backwardr   r   c               C   s&  t | ttjjtjjjfs,tdt	|  t | tjjr@| j
} t| }|dk	rb|j||d dS t | tspt| }tjj|} | j}tj|std|  d| dtj|rtd| tj||}tj| |}tjj|\}	}
|dkrt|	d}t| |j|
|d	d
d dS )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``.

    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    ZAutogradTrn   )r@   rh   r)   rG   r   rO   r   r   r#   rr   r   r   register_autogradr?   rP   	lookup_opri   Zis_functional_schemar>   Zhas_kwarg_only_tensorsr   ZautogradZInfoZmake_autograd_implr   r   r   r\   r   )r   r   r   r   r   rM   rI   infoZautograd_kernelrw   opnamer   r   r   r     s6    L


r   c                    s   d fdd}|S )NFc               
      s   r| |S t jj}|jr0d| |S t j|jj|jj	}|d krt jj
 r|j}|j }td d  d| d| d	n<|d } |kr|j }td d| d	  d
| d	d| |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)   rO   rP   r   Z_defined_in_pythonr*   Z_dispatch_pystubri   rK   rj   Zrequires_set_python_modulerw   Z_handledebugr>   )r}   r~   r   Zmaybe_pystubrw   Zcpp_filenameZpystub_moduleactual_module_namecheckedr   rM   r   r   inner  s2    



z"_check_pystubs_once.<locals>.innerr   )r   rM   r   r   r   r   r   rY   	  s    #rY   z,torch._library.abstract_impl.AbstractImplCtx)r   c                   C   s   t 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)   rO   rZ   Zglobal_ctx_getterr   r   r   r   r   9  s    )Ztest_schemaZtest_autograd_registrationZtest_faketensorZtest_aot_dispatch_dynamicT
test_utilsraise_exception.)r   r}   r~   r   r   r   c                C   s,   ddl m  m  m} |j| ||||dS )aA  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 operator's schema is correct.
    - test_autograd_registration: if autograd was registered correctly.
    - 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).
    - 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``.

    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_add(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_sin.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_sin.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(foo, args)

    r   Nr   )Ztorch.testing._internal.optestsZtesting	_internaloptestsopcheck)r   r}   r~   r   r   r   r   r   r   r   J  s    Yr   )r   )N)r   )N)N)N)N)?rG   r   typingr   r   r   r   r   r	   r
   r   r   typing_extensionsr   r%   r)   r3   	functoolsrT   re
contextlibrR   Ztorch._library.custom_opsr   r   r   r   Ztorch._libraryrO   __all__r-   r   rh   __annotations__r   r$   r   r   r5   contextmanagerr   r   compiler   singledispatchr   r[   r   r   r   FutureWarningr   Z_op_identifierr   intr   r   rY   r   Z_OPCHECK_DEFAULT_UTILSZOpOverloadPacketboolr   r   r   r   r   <module>   s    , s

@@
	 > v q0	 

