torch.library is a collection of APIs for extending PyTorch’s core library
of operators. It contains utilities for testing custom operators, creating new
custom operators, and extending operators defined with PyTorch’s C++ operator
registration APIs (e.g. aten operators).
For a detailed guide on effectively using these APIs, please see
PyTorch Custom Operators Landing Page
for more details on how to effectively use these APIs.
Testing custom ops
Use torch.library.opcheck() to test custom ops for incorrect usage of the
Python torch.library and/or C++ TORCH_LIBRARY APIs. Also, if your operator supports
training, use torch.autograd.gradcheck() to test that the gradients are
mathematically correct.
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.
Parameters:
op (OpOverload | OpOverloadPacket | CustomOpDef) – The operator. Must either be a function decorated with
torch.library.custom_op() or an OpOverload/OpOverloadPacket
found in torch.ops.* (e.g. torch.ops.aten.sin, torch.ops.mylib.foo)
When defining a custom op, first decide what aliasing and mutation behavior the
operator has. This choice determines the mutates_args, tags, return schema,
and fake-kernel behavior.
Does the operator mutate anyTensor input?
|+-- no -->Functional operator
|Use mutates_args=().|Return new Tensor objects that do not alias inputs or each other.|+-- yes -->Does it mutate the first positional Tensor argument andreturn it?
|+-- yes -->In-place operator
|Use tags=torch.Tag.inplace.|Use mutates_args with exactly the first argument name.|Return that same first argument.|+-- no -->Does it mutate keyword-only Tensor out= arguments andreturn them?
|+-- yes --> out= operator
|Use tags=torch.Tag.out.|Donot read from the out= tensors.|Put mutable output tensors after *as keyword-only args.|Returnall out= tensors in declaration order.|+-- no -->Mutable operator
Use mutates_args for the mutated arguments.Donotreturn mutated inputs or aliases of inputs.
Functional operators are the simplest and should be preferred when possible.
They should not mutate inputs, and their outputs should be fresh values that do
not alias any input or other output.
Use tags=torch.Tag.inplace only for the conventional in-place shape: the first
positional argument is a Tensor, it is the only mutated argument, and the
operator returns that same Tensor. For example, an inferred in-place custom op
has a schema shaped like:
(Tensor(a!) x, ...) -> Tensor(a!)
Use tags=torch.Tag.out only for conventional out= variants: all mutable
output tensors are keyword-only arguments, and the operator returns those
outputs in declaration order. The implementation must write to out= tensors,
but must not read from them. For example:
In-place and out= custom ops get an autogenerated fake kernel from their tag
and schema. Registering a fake kernel for these ops is usually unnecessary,
though it is still allowed if you need to override the autogenerated behavior.
out= custom ops follow the same autograd rule as built-in out= operators:
they do not support automatic differentiation when any argument requires grad.
Arbitrary aliasing, such as returning an alias of an input that is not one of
the in-place or out= patterns above, is not supported by custom_op.
PyTorch compiler transforms such as functionalization need to reason precisely
about mutations and aliases, so custom op aliasing is intentionally limited to
the conventional forms described here. If your operator mutates inputs but is
not an in-place or out= operator, model it as a mutable operator and return no
aliases of inputs.
The same operation can have different contracts depending on how it handles its
outputs:
More details on mutation, aliasing, and transforms
custom_op asks for a precise mutation and aliasing contract because PyTorch
uses that contract in FakeTensor, autograd, functionalization, and
torch.compile.
For a functional custom op, PyTorch assumes the operator does not mutate any
input and that returned tensors are fresh values. This is the easiest kind of op
for PyTorch transforms to reason about.
For an in-place custom op, torch.Tag.inplace gives PyTorch a stronger and more
specific contract: the first Tensor argument is mutated and the returned Tensor
is the same object. This lets PyTorch derive the fake behavior from the schema
instead of requiring a separate fake kernel.
For an out= custom op, torch.Tag.out gives PyTorch the corresponding
out=-variant contract: keyword-only output tensors are mutated and returned in
schema order. The tensors are output buffers only: the implementation
must not use their current values as inputs. Like built-in operators,
these custom ops do not support automatic differentiation when any argument
requires grad.
Reasons why you may want to create a custom op include:
- Wrapping a third-party library or custom kernel to work with PyTorch
subsystems like Autograd.
- Preventing torch.compile/export/FX tracing from peeking inside your function.
This API is used as a decorator around a function (please see examples).
The provided function must have type hints; these are needed to interface
with PyTorch’s various subsystems.
Create a custom operator whose implementation is backed by 1+ triton kernels.
This is a more structured way of using triton kernels with PyTorch.
Prefer using triton kernels with no torch.library custom operator wrappers
(like torch.library.custom_op(), ) because
that is simpler;
only use / if you
want to create an operator that behaves like PyTorch built-in operators.
For example, you may use a wrapper API to define the
behavior of the triton kernel when passed a tensor subclass or under
a TorchDispatchMode.
torch.library.wrap_triton(triton_kernel, /)
Allows capture of a triton kernel into a graph via make_fx or
non-strict torch.export.
These technologies perform Dispatcher-based tracing (via
__torch_dispatch__) and cannot see calls to raw triton kernels.
The wrap_triton API wraps a triton kernel into a callable that
can actually be traced into a graph.
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.
Parameters:
op (str | OpOverload) – The operator to register an impl to.
device_types (str | None | 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[) – If provided, the lifetime of this registration
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):
- is one or more gradients. The number of gradients matches
the number of outputs of the operator.
The object is used by
. The semantics of are the
same as .
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).
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 is either a Tensor subclass with or a
TorchDispatchMode.
Parses the schema of a given function with type hints. The schema is inferred from the
function’s type hints, and can be used to define a new operator.
We make the following assumptions:
None of the outputs alias any of the inputs or each other.
String type annotations “device, dtype, Tensor, types” without library specification are
assumed to be torch.*. Similarly, string type annotations “Optional, List, Sequence, Union”
without library specification are assumed to be typing.*.
Only the args listed in are being mutated. If is “unknown”,
Returns the computed kernel for a given operator and dispatch key.
This function retrieves the kernel that would be executed for a given
operator and dispatch key combination. The returned SafeKernelFunction
can be used to call the kernel in a boxed fashion. The intended use
case for this function is to retrieve the original kernel for a given
dispatch key and then register another kernel to the same dispatch key
that calls into the original kernel for certain cases.
Parameters:
op (str | OpOverload | CustomOpDef) – Operator name (along with the overload) or OpOverload object
Can be a string (e.g., “aten::add.Tensor”), an OpOverload, or a CustomOpDef.
dispatch_key () – The dispatch key to get the kernel for.
Can be a string (e.g., “CPU”, “CUDA”) or a DispatchKey enum value.
Low-level APIs
The following APIs are direct bindings to PyTorch’s C++ low-level
operator registration APIs.
A tutorial that walks you through some examples on how to use this API is available on Google Colab.
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”.
Parameters:
ns – library name
kind – “DEF”, “IMPL”, “FRAGMENT”
dispatch_key – PyTorch dispatch key (default: “”)
define(schema, alias_analysis='', *, tags
torch.library.fallthrough_kernel()
A dummy function to pass to Library.impl in order to register a fallthrough.
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.
test_utils (str | Sequence[str]) – Tests that we should run. Default: all of them.
Example: (“test_schema”, “test_faketensor”)
raise_exception (bool) – 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.
rtol (Optional[float]) – Relative tolerance for floating point comparisons.
If specified atol must also be specified.
If omitted, default values based on the dtype are selected
(see the table in torch.testing.assert_close()).
atol (Optional[float]) – Absolute tolerance for floating point comparisons.
If specified rtol must also be specified.
If omitted, default values based on the dtype are selected
(see the table in torch.testing.assert_close()).
For other mutable custom ops, use mutates_args to name the mutated arguments,
but do not return mutated inputs or aliases of inputs. Arbitrary aliasing is
hard for transforms because functionalization rewrites mutating programs into
functional programs and must know exactly which returned tensors share storage
with which inputs. custom_op therefore supports the conventional in-place and
out= aliasing patterns directly, but does not model arbitrary view or alias
relationships.
Parameters:
name (str) – A name for the custom op that looks like “{namespace}::{name}”,
e.g. “mylib::my_linear”. The name is used as the op’s stable identifier
in PyTorch subsystems (e.g. torch.export, FX graphs).
To avoid name collisions, please use your project name as the namespace;
e.g. all custom ops in pytorch/fbgemm use “fbgemm” as the namespace.
mutates_args (Iterable[str] or "unknown") – The names of args that the function mutates.
This MUST be accurate, otherwise, the behavior is undefined. If “unknown”,
it pessimistically assumes that all inputs to the operator are being mutated.
device_types (str | None | Sequence[str]) – The device type(s) the function
is valid for. If no device type is provided, then the function
is used as the default implementation for all device types.
Examples: “cpu”, “cuda”.
When registering a device-specific implementation for an operator that accepts no Tensors,
we require the operator to have a “device: torch.device argument”.
schema (str | None) – A schema string for the operator. If None
(recommended) we’ll infer a schema for the operator from its type
annotations. We recommend letting us infer a schema unless you
have a specific reason not to.
Example: “(Tensor x, int y) -> (Tensor, Tensor)”.
tags (Tag | Sequence[Tag] | None) – one or more tags to apply to the
operator. Use torch.Tag.inplace for operators that mutate their
first Tensor argument and return it. Use torch.Tag.out for
operators that mutate keyword-only output tensors and return them.
Like PyTorch’s built-in out= operators, torch.Tag.out
custom ops do not support autograd.
>>> importtorch>>> fromtorchimportTensor>>> fromtorch.libraryimportcustom_op>>> importnumpyasnp>>>>>> @custom_op("mylib::numpy_sin",mutates_args=())>>> defnumpy_sin(x:Tensor)->Tensor:>>> x_np=x.cpu().numpy()>>> y_np=np.sin(x_np)>>> returntorch.from_numpy(y_np).to(device=x.device)>>>>>> x=torch.randn(3)>>> y=numpy_sin(x)>>> asserttorch.allclose(y,x.sin())>>>>>> # Example of a custom op that only works for one device type.>>> @custom_op("mylib::numpy_sin_cpu",mutates_args=(),device_types="cpu")>>> defnumpy_sin_cpu(x:Tensor)->Tensor:>>> x_np=x.numpy()>>> y_np=np.sin(x_np)>>> returntorch.from_numpy(y_np)>>>>>> x=torch.randn(3)>>> y=numpy_sin_cpu(x)>>> asserttorch.allclose(y,x.sin())>>>>>> # Example of a custom op that mutates an input>>> @custom_op("mylib::numpy_sin_inplace",mutates_args={"x"},device_types="cpu")>>> defnumpy_sin_inplace(x:Tensor)->None:>>> x_np=x.numpy()>>> np.sin(x_np,out=x_np)>>>>>> x=torch.randn(3)>>> expected=x.sin()>>> numpy_sin_inplace(x)>>> asserttorch.allclose(x,expected)>>>>>> # Example of a custom op with inplace semantics>>> @custom_op(>>> "mylib::numpy_sin_",>>> mutates_args={"x"},>>> device_types="cpu",>>> tags=torch.Tag.inplace,>>> )>>> defnumpy_sin_(x:Tensor)->Tensor:>>> x_np=x.numpy()>>> np.sin(x_np,out=x_np)>>> returnx>>>>>> x=torch.randn(3)>>> expected=x.sin()>>> result=numpy_sin_(x)>>> assertresultisx>>> asserttorch.allclose(x,expected)>>>>>> # Example of a custom op with out= semantics>>> @custom_op(>>> "mylib::numpy_sin_out",>>> mutates_args={"out"},>>> device_types="cpu",>>> tags=torch.Tag.out,>>> )>>> defnumpy_sin_out(x:Tensor,*,out:Tensor)->Tensor:>>> x_np=x.numpy()>>> out_np=out.numpy()>>> np.sin(x_np,out=out_np)>>> returnout>>>>>> x=torch.randn(3)>>> out=torch.empty_like(x)>>> result=numpy_sin_out(x,out=out)>>> assertresultisout>>> asserttorch.allclose(out,x.sin())>>>>>> # Example of a factory function>>> @torch.library.custom_op("mylib::bar",mutates_args={},device_types="cpu")>>> defbar(device:torch.device)->Tensor:>>> returntorch.ones(3)>>>>>> bar("cpu")>>>>>> # Example of a custom op with list inputs>>> @custom_op("mylib::weighted_sum",mutates_args=())>>> defweighted_sum(>>> tensors:list[Tensor],>>> weights:list[float],>>> )->Tensor:>>> returnsum(t*wfort,winzip(tensors,weights))>>>>>> x=torch.randn(3)>>> y=torch.randn(3)>>> out=weighted_sum([x,y],[0.3,0.7])
Note that fn must only consist of calls to PyTorch-understood
operators and triton kernels. Any triton kernels called inside fn
must be wrapped in a call to torch.library.wrap_triton().
Parameters:
name (str) – A name for the custom op that looks like “{namespace}::{name}”,
e.g. “mylib::my_linear”. The name is used as the op’s stable identifier
in PyTorch subsystems (e.g. torch.export, FX graphs).
To avoid name collisions, please use your project name as the namespace;
e.g. all custom ops in pytorch/fbgemm use “fbgemm” as the namespace.
mutates_args (Iterable[str] or "unknown") – The names of args that the function mutates.
This MUST be accurate, otherwise, the behavior is undefined. If “unknown”,
it pessimistically assumes that all inputs to the operator are being mutated.
schema (str | None) – A schema string for the operator. If None
(recommended) we’ll infer a schema for the operator from its type
annotations. We recommend letting us infer a schema unless you
have a specific reason not to.
Example: “(Tensor x, int y) -> (Tensor, Tensor)”.
>>> importtorch>>> fromtorchimportTensor>>> fromtorch.libraryimportcustom_op>>> importnumpyasnp>>>>>> # Create a custom op that works on cpu>>> @custom_op("mylib::numpy_sin",mutates_args=(),device_types="cpu")>>> defnumpy_sin(x:Tensor)->Tensor:>>> x_np=x.numpy()>>> y_np=np.sin(x_np)>>> returntorch.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)>>> returntorch.from_numpy(y_np).to(device=x.device)>>>>>> x_cpu=torch.randn(3)>>> x_cuda=x_cpu.cuda()>>> asserttorch.allclose(numpy_sin(x_cpu),x_cpu.sin())>>> asserttorch.allclose(numpy_sin(x_cuda),x_cuda.sin())
str
|
OpOverload
device_type (str) – Device type to use. ‘cuda’, ‘cpu’, ‘xpu’, or any other device type that supports autocast.
The type is the same as the type attribute of a torch.device.
Thus, you may obtain the device type of a tensor using Tensor.device.type.
cast_inputs (torch.dtype) – When custom op runs in an autocast-enabled region,
casts incoming floating-point Tensors to the target dtype (non-floating-point Tensors
are not affected), then executes custom op with autocast disabled.
lib (Optional[Library]) – If provided, the lifetime of this registration
Examples::
>>> importtorch>>> fromtorchimportTensor>>> fromtorch.libraryimportcustom_op>>>>>> # Create a custom op that works on cuda>>> @torch.library.custom_op("mylib::my_sin",mutates_args=())>>> defmy_sin(x:Tensor)->Tensor:>>> returntorch.sin(x)>>>>>> # Register autocast dispatch rule for the cuda device>>> torch.library.register_autocast("mylib::my_sin","cuda",torch.float16)>>>>>> x=torch.randn(3,dtype=torch.float32,device="cuda")>>> withtorch.autocast("cuda",dtype=torch.float16):>>> y=torch.ops.mylib.my_sin(x)>>> asserty.dtype==torch.float16
setup_context(ctx,inputs,output) runs during the forward pass.
Please save quantities needed for backward onto the ctx object via
either 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 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.
lib (Optional[Library]) – Library to register the fake tensor to.
allow_override (bool) – Flag controlling if we want to override an
existing registered fake impl. This is on by default;
pass False to error if the operator already has a
fake impl. This also only applies if the custom operator
was not created via torch.library.custom_op, as
overriding an existing fake impl is already allowed.
Examples
>>> importtorch>>> importnumpyasnp>>> fromtorchimportTensor>>>>>> # Example 1: an operator without data-dependent output shape>>> @torch.library.custom_op("mylib::custom_linear",mutates_args=())>>> defcustom_linear(x:Tensor,weight:Tensor,bias:Tensor)->Tensor:>>> raiseNotImplementedError("Implementation goes here")>>>>>> @torch.library.register_fake("mylib::custom_linear")>>> def_(x,weight,bias):>>> assertx.dim()==2>>> assertweight.dim()==2>>> assertbias.dim()==1>>> assertx.shape[1]==weight.shape[1]>>> assertweight.shape[0]==bias.shape[0]>>> assertx.device==weight.device>>>>>> return(x@weight.t())+bias>>>>>> withtorch._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)>>>>>> asserty.shape==(2,3)>>>>>> # Example 2: an operator with data-dependent output shape>>> @torch.library.custom_op("mylib::custom_nonzero",mutates_args=())>>> defcustom_nonzero(x:Tensor)->Tensor:>>> x_np=x.numpy(force=True)>>> res=np.stack(np.nonzero(x_np),axis=1)>>> returntorch.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)>>> returnresult>>>>>> fromtorch.fx.experimental.proxy_tensorimportmake_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()>>>>>> asserttorch.allclose(trace(x),torch.ops.mylib.custom_nonzero(x))
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 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.
it assumes that all inputs to the operator are being mutates.
Callers (e.g. the custom ops API) are responsible for checking these assumptions.
Parameters:
prototype_function (Callable) – The function from which to infer a schema for from its type annotations.
op_name (Optional[str]) – The name of the operator in the schema. If name is None, then the
name is not included in the inferred schema. Note that the input schema to
torch.library.Library.define requires an operator name.
mutates_args ("unknown" | Iterable[str]) – The arguments that are mutated in the function.
tags (Tag | Sequence[Tag] | None) – one or more tags to apply to the
inferred schema. Use torch.Tag.inplace or torch.Tag.out to
infer the conventional aliasing for those operator kinds.
>>> # Get the CPU kernel for torch.add>>> kernel = torch.library.get_kernel("aten::add.Tensor","CPU")>>>>>> # You can also use DispatchKey enum>>> kernel = torch.library.get_kernel("aten::add.Tensor", torch.DispatchKey.CPU)>>>>>> # Or use an OpOverload directly>>> kernel = torch.library.get_kernel(torch.ops.aten.add.Tensor,"CPU")>>>>>> # Example: Using get_kernel in a custom op with conditional dispatch>>> # Get the original kernel for torch.sin>>> original_sin_kernel = torch.library.get_kernel("aten::sin","CPU")>>>>>> # If input has negative values, use original sin, otherwise return zeros>>> defconditional_sin_impl(dispatch_keys, x):>>> if(x <0).any():>>> return original_sin_kernel.call_boxed(dispatch_keys, x)>>> else:>>> return torch.zeros_like(x)>>>>>> lib = torch.library.Library("aten","IMPL")>>> # with_keyset=True so the first argument to the impl is the current DispatchKeySet>>> which needs to be the first argument to ``kernel.call_boxed``
>>> lib.impl("sin", conditional_sin_impl,"CPU", with_keyset=True)>>>>>> # Test the conditional behavior>>> x_positive = torch.tensor([1.0,2.0])>>> x_mixed = torch.tensor([-1.0,2.0])>>> torch.sin(x_positive)tensor([0., 0.])>>> torch.sin(x_mixed)tensor([-0.8415, 0.9093])
=
()
)
Defines a new operator and its semantics in the ns namespace.
Parameters:
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.
Registers the function implementation as the fallback for the given key.
This function only works for a library with global namespace (“_”).
Parameters:
fn – function used as fallback for the given dispatch key or 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 fn when calling. This should be used to create the appropriate keyset for redispatch calls.
Registers the function implementation for an operator defined in the library.
Parameters:
op_name – operator name (along with the overload) or OpOverload object.
fn – function that’s the operator implementation for the input dispatch key or 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 fn when calling. This should be used to create the appropriate keyset for redispatch calls.
allow_override – Flag controlling if we want to override an
existing registered kernel implementation. This is on
by default; pass False to error if a kernel is
already registered for this dispatch key.
Registers which arguments require symmetric memory allocation for an operator.
This method allows operators to declaratively specify which arguments need
symmetric memory treatment. When used with torch.compile, Inductor
automatically allocates these arguments in P2P-accessible NVLink memory
(empty_strided_p2p), enabling zero-copy inter-GPU communication.
The operator’s schema should include a group_name (str) argument.
Inductor’s FallbackKernel._maybe_realize_symm_mem_args extracts
group_name at compile time to allocate P2P buffers for the correct
process group. Without group_name, the automatic realization is skipped.
Parameters:
op_name – operator name (along with the overload) or OpOverload object.
arg_names – list of argument names that require symmetric memory allocation.
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::
>>> importtorch>>> importnumpyasnp>>>>>> # Define the operator>>> torch.library.define("mylib::sin","(Tensor x) -> Tensor")>>>>>> # Add implementations for the operator>>> @torch.library.impl("mylib::sin","cpu")>>> deff(x):>>> returntorch.from_numpy(np.sin(x.numpy()))>>>>>> # Call the new operator from torch.ops.>>> x=torch.randn(3)>>> y=torch.ops.mylib.sin(x)>>> asserttorch.allclose(y,x.sin())
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.
This API may be used as a decorator. You can use nested decorators
with this API provided they return a function and are placed inside
this API (see Example 2).
Some valid types are: “cpu”, “cuda”, “xla”, “mps”, “ipu”, “xpu”.
Parameters:
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
>>> importtorch>>> importnumpyasnp>>> # Example 1: Register function.>>> # Define the operator>>> torch.library.define("mylib::mysin","(Tensor x) -> Tensor")>>>>>> # Add implementations for the cpu device>>> @torch.