o �J�h/��@s$UddlZddlZddlZddlZddlZddlZddlZddlmZm Z m Z m Z m Z m Z mZmZmZddlmZddlZddlmZddlmZmZmZmZddlmZddlmZgd�Ze �a!ee"e#d<e �Z$ee"e#d <d gZ%d d �Z&Gd d�d�Z'dd�Z(ej)dd��Z*gZ+e e'e#d<e�,d�Z-ej.ddd�dd��Z/e/j0dRde'fdd��Z1ej.dSdd�dd��Z2dSdd d!�d"d#�Z3d$e"d%e"fd&d'�Z4e2j0dRde'fd(d��Z1ed)e5d*�dSdd+d,�d-d.��Z6ee"d/d0fZ7 dSdd�d1e7d2ed3e e de e'fd4d5�Z8 dSdd+d,�d1e7d3e e de e'd6e9fd7d8�Z:ddd9�d1e7d:e d;e e d%dfd<d=�Z; dSdd�d1e7d>ed3e e de e'fd?d@�Z< dSdd�d1e7d3e e fdAdB�Z=dCdD�Z>dTdFdG�Z?dHZ@ dSe@dIdJ�d1eejAjejAjBefdKeedLfdMe e e"efdNee"e e"fdOeCd%e e"e"ff dPdQ�ZDdS)U�N) �Any�Callable�Dict�List�Optional�Sequence�Set�Tuple�Union)� deprecated)�_maybe_get_opdef� custom_op� CustomOpDef�device_types_t)� infer_schema)� OpOverload) �Library�impl�define�fallthrough_kernel� impl_abstract� register_fake�register_torch_dispatch� register_vmap�get_ctxr r�_impls�_defsZprimcCstd��)zZ A dummy function to pass to ``Library.impl`` in order to register a fallthrough. z,fallthrough_kernel() should never be called.)�NotImplementedError�rr�KC:\pinokio\api\whisper-webui.git\app\env\lib\site-packages\torch\library.pyr1src@sveZdZdZddd�Zdd�Zddd�d d �Zdd d �Zdd�Zddd�Z ddd�dd�Z ddd�dd�Z dd�Z dS)raC 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 Cs�|dvr td|��|tvr|dks|dkrt|d��tjdd�d}|j|j}}tj�|||||�|_ ||_ t �|_ t �|_ g|_||_||_t�|tt|j t|j |j�dS) N)�IMPL�DEF�FRAGMENTzUnsupported 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�_C�_dispatch_library�m�ns�set�_op_defs� _op_impls�_registration_handles�kind� dispatch_key�weakref�finalize� _del_libraryrr)�selfr0r5r6�framer*r+rrr�__init__Ks6 � ��zLibrary.__init__cCsd|j�d|j�d|j�d�S)Nz Library(kind=z, ns=z, dispatch_key=z)>)r5r0r6)r:rrr�__repr__nszLibrary.__repr__r)�tagsc Cs�|dvr td|����|jdusJ�t|tj�r|f}|�d�d}d|vr-|�d�dn|}ttj|j�o?tt tj|j�|�}|j� ||t |��}|�d�d}|jd|}|rlt tj|j�} t | |�} tj � | �|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 CONSERVATIVEzInvalid alias_analysis type N�(r�.�::)� RuntimeErrorr/� isinstancer,�Tag�split�hasattr�opsr0�getattrr�tuple�_ops�_refresh_packetr2�addr) r:�schema�alias_analysisr>�nameZ packet_nameZhas_preexisting_packet�result�qualnamer0�packetrrrrqs( �    zLibrary.define�c Cs�tjj�|d�}t�|�}t�|�}|durdn|j}|dur'|� d�r'd}|j �d|��}tjj j � |�} |durBt|||�} n|} | j�| |�} |j�| �dS)z?Registers the fake impl for an operator defined in the library.rSNz torchvision.rA)r,�_library�utils� get_source�sys� _getframe�inspect� getmodule�__name__� startswithr0�simple_registry� singleton�find�_check_pystubs_once� fake_impl�registerr4�append) r:�op_name�fn� _stacklevel�sourcer;Z caller_moduleZcaller_module_namerQ�entryZfunc_to_register�handlerrr�_register_fake�s   �zLibrary._register_fakecCs>|j�d|��}tjjj�|�}|j�||�}|j� |�dS)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 rAN) r0r,rTr]r^r_Ztorch_dispatch_rulesrbr4rc)r:rd�torch_dispatch_classrerQrhrirrr�_register_torch_dispatch_rule�sz%Library._register_torch_dispatch_rulecCs�|dkr|j}t�|��tjjj�sJ�t|t�r|}nt|t �r4|j j }|j j }|dkr3|d|}nt d��|jd|�d�dd|}|tvr[t d�|�d�d||j���|jdusbJ�|jj}||j|�d�d|�t�|�|j�|�dS) 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�/rA�������This is not allowed since there's already a kernel registered from python overriding {}'s behavior for {} dispatch key and {} namespace.N)r6r,�DispatchKeySet�hasr-� DispatchKey�DenserC�strr�_schemarO� overload_namerBr0rEr�formatr/�impl_with_aoti_compilerLr3)r:rdr6rOrv�keyZimpl_fnrrr�_impl_with_aoti_compile�s6    �� �� zLibrary._impl_with_aoti_compileF�� with_keysetc Cs>t|�s tdt|�����|dkr|j}t|t�r|}nt|t�r4|jj}|jj }|dkr3|d|}nt d��|j d|� d�dd|}|t vr[t d�|� d�d||j ���|d kr||}d|vrm|j �d|��}tj�|d �r|t d |�d ���|jd us�J�|j�||dkr�|nd ||�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. 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") 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 argumentrmrArnro�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.N)�callable� TypeError�typer6rCrtrrurOrvrBr0rErrwr,r-�%_dispatch_has_kernel_for_dispatch_keyr/rrLr3) r:rdrer6r|rOrvryZdispatcher_op_namerrrr�sX �   �� ��� �� z Library.implcCsV|dkr|j}|jdkrtd|j����|dksJ�|jdus!J�|j�|||�dS)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") r �_z\Fallback can only be registered using libary fragment on the global namespace "_" but it is N)r6r0rBr/�fallback)r:rer6r|rrrr�Ms  � zLibrary.fallbackcCs�|jdur |j��d|_|jD]}|��q|j��t|j8a|jD](}|�d�\}}|�d�d}t t j |�s;q$t t j |�}t ||�sGq$t ||�q$dS)NrAr@r)r/�resetr4�destroy�clearrr3r2rErFr,rGrH�delattr)r:rirOr0Zname_with_overload� namespacerrr�_destroyns"           �zLibrary._destroyN�r )rS) r[� __module__� __qualname__�__doc__r<r=rrjrlrzrr�r�rrrrr8s # 0 /N !rcCs&||8}||8}|D]}|��q dS�N)r�)Zcaptured_implsZop_implsZ captured_defsZop_defsZregistration_handlesrirrrr9�s  �r9cos0�zt|i|��}|VW|��dS|��wr�)rr�)�args�kwargs�librrr�_scoped_library�s �r�� _keep_alivez \(.*\) -> .*r)r�r>cCs|t|t�stdt|�����tjj�|�\}}|dur%t|d�}t � |�t � |�s2td|�d���|j ||d|d�dS)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 )rNr>)rCrtr&r�r,rTrU�parse_namespacerr�rc�NAMELESS_SCHEMA� fullmatchr)rQrMr�r>r�rOrrrr�s" 1��   ��rr r�c����fdd�}|S)zOThe old torch.library.define. We're keeping this around for BC reasons cs�����}��||�|Sr�)rr)�frO�rNr�rMrr�wrap�s  �_.<locals>.wrapr)r�rMrNr�rr�rr��sr�)r�cCst||||dd�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)rQ�types�funcr�rrrr�s!rFr�csvt|t�r|f}ti��|D]}tj�|�}|r��|�q��t|��q����fdd�}|dur5|S||�dS)Ncs�tjj���\}}�durt|d�}t�|�n�}�r3tj�fdd��}�D] }|��||�q'dS�D] }|���|�q5dS)Nr#cs�|i|��Sr�r)r�r��r�rr�func_no_dynamo4sz/_impl.<locals>.register.<locals>.func_no_dynamo) r,rTrUr�rr�rc�_disable_dynamor)r�r�r��use_libr�ry�r��keysr�rQr�rrb*s  ��z_impl.<locals>.register)rCrtr1r,r-�_parse_dispatch_keyrL�_device_type_to_key)rQr�r�r�r��typZis_dispatch_keyrbrr�rr�s    r�� device_type�returncCs|dkrdStj�|�S)N�default�CompositeExplicitAutograd)r,r-�_dispatch_key_for_device)r�rrrr�Ds r�cr�)z1Legacy torch.library.impl API. Kept around for BCcs���|��|Sr�)r)r��r6r�rOrrr�Rsr�r)r�rOr6r�rr�rr�Nsz�`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.)�categoryrS�r�rfcCs |dur|d}t||||d�S)zmThis API was renamed to :func:`torch.library.register_fake` in PyTorch 2.4. Please use that instead. NrSr�)r)rQr�r�rfrrrrYs rztorch._ops.OpOverloadz%torch._library.custom_ops.CustomOpDef�op� device_typesr�cCs~t|ttjjtjjjf�std��t|tjj�r|j }t |�}|dur)|� ||�St|t�s0J�|dur6d}t ||||dd�S)a5Register 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�Tr�) rCrtr,rJrrT� custom_opsrr&�_namer �register_kernelr�)r�r�r�r��opdefrrrr�ls0� r�rfcs�t�ttjjtjjjf�std��t�tjj�r�j �t ��}|dur/|dur*|j S|� |�St�t�s6J�|����fdd�}|durF|S�d7�||�S)aRegister 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)}NcsLtjj���\}}�durt|d�}t�|�n�}|j||�dd�|S)Nr#rS)rf)r,rTrUr�rr�rcrj�r�r�rdr��r�r�� stacklevelrrrbs  zregister_fake.<locals>.registerrS) rCrtr,rJrrTr�rr&r�r r)r�r�r�rfr�rbrr�rr�s$X�  r)� setup_contextr��backwardr�c Cs$t|ttjjtjjjf�stdt |�����t|tjj�r |j }t |�}|dur1|j ||d�dSt|t�s8J�|}tjj �|�}|j}tj �|�sUtd|�d|�d���tj �|�rbtd|����tj�||�}tj�||�}tjj �|�\} } |dur�t| d�}t�|�|j| |d d d �dS) 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.z�register_autograd with kwarg-only Tensor args. In the original definition of the op, please make your tensors not kwarg-only. Got: r#�AutogradTr{)rCrtr,rJrrTr�rr&r�r�r �register_autogradrU� lookup_opruZis_functional_schemarB�has_kwarg_only_tensorsr�autograd�InfoZmake_autograd_implr�rr�rcr) r�r�r�r�r�rQrM�infoZautograd_kernelr��opnamerrrr�%sJW� � ��� ��  r�rkcs�t�ttjjtjjjf�std��t�tjj�r�j �t ��}|dur)|� �|�St�t�s0J����fdd�}|dur>|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)}NcsFtjj���\}}�durt|d�}t�|�n�}|�|�|�|S)Nr#)r,rTrUr�rr�rcrlr��r�r�rkrrrb�s  z)register_torch_dispatch.<locals>.register) rCrtr,rJrrTr�rr&r�r r)r�rkr�r�r�rbrr�rr�s 4��  rcs�t�ttjjtjjjf�stdt ������t�tjj�r �j �t ��}|dur-|� |�St�t�s4J���tjj �����j}tj �|�rMtd|�������fdd�}|dur[|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: Nzregister_vmap with kwarg-only Tensor args. In the original definition of the op, please make your tensors not kwarg-only. Got: csntjj���\}}�durt|d��t���ddlm�ddl m �����fdd�}�j ||ddd �dS) Nr#r)� custom_function_call_vmap_helper)�&retrieve_current_functorch_interpretercs ��}�|��g|�Ri|��Sr�r)�keysetr�r�� interpreter)r�r�r�r�rr� wrapped_funchs���z5register_vmap.<locals>.register.<locals>.wrapped_func�FuncTorchBatchedTr{) r,rTrUr�rr�rc�"torch._functorch.autograd_functionr��torch._functorch.pyfunctorchr�r)r�r�r�r��r�r�rQ)r�r�r�rrb]s    zregister_vmap.<locals>.register)rCrtr,rJrrTr�rr&r�r�r rrUr�rur�r)r�r�r�r�rMrbrr�rr�s.U�  ��rcsd�����fdd�}|S)NFc s��r �|i|��Stjj���}|jrd��|i|��Stj�|jj|jj �}|durKtjj� �rJ|j }|j � �}td��d��d|�d|�d� ��n|d}�|kri|j � �}td��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 (�)rz?' 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,rTrUr��_defined_in_pythonr-�_dispatch_pystubrurOrvZrequires_set_python_moduler��_handle�debugrB)r�r�r�Z maybe_pystubr�Z cpp_filenameZ pystub_module��actual_module_name�checkedr�rQrr�inner|sJ �  �����  ����z"_check_pystubs_once.<locals>.innerr)r�rQr�r�rr�rr`ys&r`�$torch._library.fake_impl.FakeImplCtxcCs tjj��S)z�get_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,rTraZglobal_ctx_getterrrrrr�s r)Z test_schemaZtest_autograd_registrationZtest_faketensorZtest_aot_dispatch_dynamicT�� test_utils�raise_exceptionr�.r�r�r�cCs,ddlmmm}|j|||||d�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_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) rNr�)Ztorch.testing._internal.optests�testing� _internal�optests�opcheck)r�r�r�r�r�r�rrrr��sk �r�r�r�)r�r�)E� contextlib� functoolsrY�rerWr(r7�typingrrrrrrrr r �typing_extensionsr r,Ztorch._libraryrTZtorch._library.custom_opsr r rrZtorch._library.infer_schemar� torch._opsr�__all__r1rrt�__annotations__rr'rrr9�contextmanagerr�r��compiler��singledispatchrrbr�rr�r�� FutureWarningrZ_op_identifierr��intrr�rrr`rZ_OPCHECK_DEFAULT_UTILSrJ�OpOverloadPacket�boolr�rrrr�<module>s� ,    R  B #+  � ������ �B����� �~���� ������ �S��� � 3  ��� ���� �
Memory