Custom Operators, C++/CUDA Extensions & Triton
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
Sometimes an operation cannot be written with existing PyTorch operators: you call a vendor library, a hand-tuned CUDA kernel, a Triton kernel or an arbitrary Python or NumPy routine. PyTorch can call such code directly, but then torch.compile, torch.export, autograd, vmap and fake tensors cannot see inside it. The solution is to register it as a custom operator with a declared schema, so the rest of the stack treats it as a first-class operator. This page covers the Python route (torch.library), the C++ and CUDA route (torch.utils.cpp_extension) and Triton.
Examples were run on Python 3.13 with PyTorch 2.15 (CPU) on 2026-10-31, including the inline C++ extension (built with Apple Clang and the ninja package, which load_inline needs on PATH). The CUDA extension and Triton examples need a CUDA GPU and toolchain and were not executed.
When to write a custom operator
The custom operators landing page gives the decision rule. If the operation can be built from existing PyTorch operators, write a plain Python function; torch.compile will trace and fuse it. Register a custom operator when you call code PyTorch cannot see: custom kernels, extension bindings, or a Python function that must be treated as opaque. Passing raw data pointers to a pybind-ed kernel works, but it does not integrate with autograd, torch.compile or vmap.
| Situation | Route |
|---|---|
Python function or Python bindings to C++/CUDA code that must work with |
|
Custom C++ or CUDA code, or you plan to use the operator from AOTInductor without Python |
C++ |
The implementation is one or more Triton kernels that |
|
Intel GPUs |
Custom SYCL operators (see the landing page) |
Python custom operators
torch.library.custom_op(name, fn=None, /, *, mutates_args, device_types=None, schema=None, tags=None) turns a Python function into an operator named namespace::name. The schema is inferred from the type annotations, and the documentation discourages writing it by hand because it is error-prone. mutates_args lists the arguments the function modifies in place (or is the string "unknown"), and must be accurate, otherwise the behaviour is undefined. device_types restricts the implementation to given devices; leave it out for a default implementation.
import numpy as np
import torch
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)
x = torch.randn(3)
print(torch.allclose(numpy_sin(x), x.sin())) # True
Fake kernel for tracing
torch.compile and torch.export run operators on fake tensors that carry only metadata. A custom operator needs a fake (meta) kernel that returns tensors with the right shape, dtype and device, using only PyTorch operations. It was called impl_abstract before PyTorch 2.4 and is now register_fake. For outputs whose size depends on the data, use torch.library.get_ctx().new_dynamic_size().
@numpy_sin.register_fake
def _(x):
return torch.empty_like(x)
Autograd formula
A custom operator is not differentiable until you register a backward. torch.library.register_autograd(op, backward, /, *, setup_context=None, lib=None) takes a setup_context(ctx, inputs, output) that saves values and a backward(ctx, *grads) that returns one gradient per input. Both must be traceable: no data_ptr() and no reliance on global state. Strides of the incoming gradient are undefined, so call contiguous() if a raw kernel needs a particular layout.
def setup_context(ctx, inputs, output):
(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)
numpy_sin(x).sum().backward()
print(torch.allclose(x.grad, x.detach().cos())) # True
For the class-based alternative used outside operators, see Custom autograd Functions.
Per-device kernels
torch.library.register_kernel(op, device_types, func=None, /, *, lib=None) attaches a different implementation per device, so you can ship a fast CUDA kernel and keep a CPU fallback.
@torch.library.register_kernel("mylib::numpy_sin", "cuda")
def _(x):
# A real project would launch a CUDA kernel here.
return torch.from_numpy(np.sin(x.cpu().numpy())).to(device=x.device)
Testing with opcheck
torch.library.opcheck(op, args, kwargs=None, *, test_utils=..., raise_exception=True, atol=None, rtol=None) verifies that the registrations are consistent. The default utilities are test_schema, test_autograd_registration, test_faketensor and test_aot_dispatch_dynamic. Call it on several representative inputs, including tensors with requires_grad=True and every supported device. It checks that the library is used correctly, not that the gradient is mathematically right; for that, also run torch.autograd.gradcheck.
samples = [(torch.randn(4),), (torch.randn(2, 3, requires_grad=True),)]
for args in samples:
torch.library.opcheck(numpy_sin, args)
Limits
-
custom_opdoes not support arbitrary aliasing, only the in-place andout=patterns. -
Operators tagged
torch.Tag.outdo not support autograd when any argument requires grad. -
The lower-level
torch.library.Libraryclass and the dispatcher are documented as complicated; prefer the higher-level functions above.
C++ and CUDA extensions
When the kernel itself is C++ or CUDA, build it with torch.utils.cpp_extension and register it in C++ with TORCH_LIBRARY and TORCH_LIBRARY_IMPL, so the operator appears under torch.ops.<namespace>. The C++ route is also the one to use if the operator must run inside AOTInductor-compiled artifacts without a Python interpreter (see AOTInductor). The module offers three build styles.
| Mechanism | Use |
|---|---|
|
Just-in-time compile a C++ or CUDA string or files at import time; best for experiments. |
|
Ahead-of-time build in a |
CMake |
For larger projects with their own build system. |
import torch
from torch.utils.cpp_extension import load_inline
cpp_source = r"""
#include <torch/extension.h>
torch::Tensor scaled_add(torch::Tensor a, torch::Tensor b, double alpha) {
return a + alpha * b;
}
"""
ext = load_inline(
name="scaled_add_ext",
cpp_sources=cpp_source,
functions=["scaled_add"],
verbose=True,
)
a, b = torch.ones(3), torch.ones(3)
print(ext.scaled_add(a, b, 2.0)) # tensor([3., 3., 3.])
An ahead-of-time build for a CUDA kernel looks like this.
# setup.py
from setuptools import setup
from torch.utils.cpp_extension import BuildExtension, CUDAExtension
setup(
name="my_cuda_ops",
ext_modules=[
CUDAExtension(
name="my_cuda_ops",
sources=["ops.cpp", "ops_kernel.cu"],
)
],
cmdclass={"build_ext": BuildExtension},
)
pip install --no-build-isolation -e .
Practical points: the compiler and CUDA toolkit versions must match the PyTorch build you run; a mismatch is the most common source of build failures. An operator written only as a pybind function does not get autograd, torch.compile or vmap support, so register it through TORCH_LIBRARY and add the Python-side register_fake and register_autograd as described above. The step-by-step C++ and CUDA walkthrough is in the Custom C++ and CUDA Operators tutorial.
Triton kernels
Triton is a Python-embedded language for writing GPU kernels. A raw Triton kernel works in eager mode, but torch.export and make_fx cannot see it. torch.library.wrap_triton(triton_kernel) makes a kernel traceable, and torch.library.triton_op(name, fn=None, /, *, mutates_args, schema=None) declares an operator whose body is made of such kernels. The difference from custom_op is visibility: custom_op is opaque to torch.compile and torch.export, while triton_op exposes the implementation so they can optimize it. Triton and a supported GPU are required.
import torch
import triton
import triton.language as tl
from torch.library import triton_op, wrap_triton
@triton.jit
def add_kernel(x_ptr, y_ptr, out_ptr, n_elements, BLOCK_SIZE: tl.constexpr):
pid = tl.program_id(axis=0)
offsets = pid * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
mask = offsets < n_elements
x = tl.load(x_ptr + offsets, mask=mask)
y = tl.load(y_ptr + offsets, mask=mask)
tl.store(out_ptr + offsets, x + y, mask=mask)
@triton_op("mylib::add", mutates_args={})
def add(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
output = torch.empty_like(x)
n_elements = output.numel()
def grid(meta):
return (triton.cdiv(n_elements, meta["BLOCK_SIZE"]),)
wrap_triton(add_kernel)[grid](x, y, output, n_elements, 16)
return output
You still register autograd for a triton_op with register_autograd. For how Inductor itself generates Triton code and how to inspect it, see torch.compile and torch.compile Troubleshooting; for the general GPU-programming background see Hardware & Mixed Precision.
Checklist
-
Can the operation be expressed with existing operators? If yes, stop and write Python.
-
Declare the operator with correct type annotations and an accurate
mutates_args. -
Add a fake kernel so
torch.compileandtorch.exportcan trace it. -
Add an autograd formula if training needs gradients, and verify with
gradcheck. -
Add device-specific kernels as needed.
-
Run
opcheckon varied inputs, then test undertorch.compile(fullgraph=True).