Extending PyTorch: custom ops, tensor subclasses, kernels

Reading: 34 min, plus 13 in closed details. How to add what PyTorch does not ship without breaking autograd, torch.compile or export: custom operators, C++ extensions, Metal, Triton and Helion kernels, tensor subclasses and dispatch modes, on the topic's running example. Every graph count, opcheck result, trace and error was recorded with torch 2.14.1 on an Apple M1 Pro (CPU and MPS); source quoted at pinned tags. Data as of October 2026.

The idea in one screen

Every way of extending PyTorch plugs your code into one slot on the path a call already takes, and autograd, torch.compile and torch.export keep working only if you also hand PyTorch the three facts it cannot read from opaque code: the output's shape (a fake), the gradient, and what the code writes.

Fig. 1, step by step: one call path, six slots to plug into; the three facts highlighted

  1. One call, a stack of keys. ext::gelu2(x), the page's operator with a C++ kernel for the CPU and a Metal one for the Apple GPU (section 1.6), enters at the top. The dispatcher walks its keys in order; a key with a kernel registered for this operator runs it, a key without one passes the call down.
  2. Python API: __torch_function__. Before anything else, a tensor subclass or a TorchFunctionMode sees the Python function you called (F.linear, Tensor.add), above autograd (section 5.1).
  3. Autograd: fact 2, the gradient. register_autograd fills this slot (Autograd[alias] in the operator's recorded table): it records the backward node, so loss.backward() knows the op's gradient.
  4. ADInplaceOrView: fact 3, what the op writes. Version counters and views. The schema's mutates_args decides whether the op has a kernel here; ext::gelu2 writes nothing, so the slot is empty and the call passes through.
  5. Python key: __torch_dispatch__. Tensor subclasses and dispatch modes receive the ATen operator here, below autograd (sections 5 and 6). Plain tensors skip it.
  6. The kernel for the device. A CPU tensor runs the C++ kernel at CPU, an MPS tensor the Metal kernel at MPS: one operator, one kernel per device (register_kernel, TORCH_LIBRARY_IMPL; Triton and Helion kernels plug in the same way, section 4).
  7. Under compile: fact 1, the output's shape. torch.compile and torch.export trace with fake tensors, so the call goes to Meta, where register_fake returns an empty (8, 64, 1024) output: a shape, no data.

The dispatcher's keys in their real order, simplified (Tensors, the dispatcher and autograd walks all of them, Reading 2.2). The kernels drawn at the bottom are the ones in ext::gelu2's table as recorded with torch._C._dispatch_dump (CPU, MPS, Meta and Autograd; closed block in 1.6).

You need: the dispatcher's keys and the autograd graph from Tensors, the dispatcher and autograd (Reading 2 and 3), and what a graph break is from torch.compile from the user's side.

The running example. The parent topic's 3,186,944-parameter character-level GPT (Topic: pytorch-ecosystem, defined once in the root's src/model/), changed in two ways: the GELU in every block's MLP becomes your own kernel (C++, then Metal, then Helion), and the block weights become an int8 tensor subclass.

New terms

  • Operator: a named function the dispatcher knows (aten::addmm, or yours, ext::gelu), with a schema, a one-line signature such as ext::gelu(Tensor x) -> Tensor.
  • Fake (meta) implementation: computes the output's shape, dtype and strides without data; what the compiler traces with.
  • Graph break: where torch.compile stops a graph, runs Python, and starts a new one.
  • opcheck: torch.library.opcheck, four tests that the three facts are true.
  • Wrapper subclass: a tensor with a shape but no storage, whose data lives in inner tensors.
  • Dispatch mode: a context manager that sees every ATen call in a region.

Which hook for which need, with what was measured

You needUseAutogradtorch.compileMeasured here
A different gradient for code PyTorch can tracetorch.autograd.FunctionYoursTraced if forward and backward are traceableOwned by the sibling page (Reading 3.4): no schema or fake to maintain
To call a kernel or library PyTorch cannot seetorch.library.custom_op with a fake and register_autograd; not a direct callregister_autogradOne node, no break, once it has a fakeDirect call: graphs, breaks, export fails, of 52 parameters trained. Op: 1 graph, exports, all 52; µs per call against for F.gelu
The same, defined in C++A C++ op with TORCH_LIBRARYIn C++ or from PythonSame as custom_opCold build to s; µs per call
A Triton kernel the compiler should optimise aroundtriton_op + wrap_triton, or a raw @triton.jit call; not custom_opregister_autogradVisible: Inductor optimises around the kernelNot run: Triton has no macOS build
A tiled kernel written as PyTorch-like codeHelion (compiles to Triton, or Metal, Pallas, CuTe)Wrap it in an opTraced as a kernel call, no breakRan on MPS: 1 graph, 0 breaks
Weights or activations in a new formatA wrapper subclass (__torch_dispatch__) with __tensor_flatten__; not rewriting every layerAbove it: works unchangedCompiled throughint8 weights: MB to MB, 1 graph
A tensor spread over devicesDTensor (already built); not your own subclassUnchangedCompiled throughC++ fast path; FSDP2 and tensor parallelism are built on it
To intercept Python-level calls on your type__torch_function__Not seen in backwardPartly traced calls in forward, in backward
To observe or rewrite every op in a regionTorchDispatchMode; not a subclassSees backward tooEager toolFLOP count of one step:
A new devicePrivateUse1; not a forkThrough the usual keysThrough the vendor's backendNot run (needs a C++ device runtime)

The rows run from lightest to heaviest. The rule the page earns: use the lightest hook that does the job, and when you reach for an operator, give the compiler its three facts and test them with opcheck. The Which extension point? tab asks the same questions one at a time.

Each registration fills one slot of the operator's table and unlocks one more thing

1. Custom operators with torch.library

The problem. You have a kernel PyTorch cannot see inside: compiled C++, a Metal or CUDA kernel, a call into another library. Called as a plain Python function it works in eager mode, but autograd does not know its gradient, torch.compile cannot trace through it, and torch.export cannot put it in a graph. A custom operator fixes all three by making your function a first-class entry in the dispatcher, like aten::addmm, and by telling PyTorch the three facts it cannot work out by itself.

1.1 Defining one: a kernel, three facts, one test

The operator the running example uses, exactly as run (src/exp/custom_ops.py). EXT.raw_gelu is the C++ function of section 3; any opaque function would do.

import torch from torch import Tensor # 1. the operator: namespace::name, the kernel, and what it mutates @torch.library.custom_op("ext::gelu", mutates_args=()) def gelu(x: Tensor) -> Tensor: return EXT.raw_gelu(x) # opaque: C++ through pybind11 # 2. the fake: output metadata without running the kernel @gelu.register_fake def _(x): return torch.empty_like(x) # 3. the gradient: its own operator (with its own fake), so compile can trace backward too @torch.library.custom_op("ext::gelu_bwd", mutates_args=()) def gelu_bwd(grad: Tensor, x: Tensor) -> Tensor: return EXT.raw_gelu_backward(grad, x) @gelu_bwd.register_fake def _(grad, x): return torch.empty_like(x) def setup_context(ctx, inputs, output): # runs after forward: save what backward needs (x,) = inputs ctx.save_for_backward(x) def backward(ctx, grad): # one gradient per input (x,) = ctx.saved_tensors return gelu_bwd(grad, x) gelu.register_autograd(backward, setup_context=setup_context) # 4. the test torch.library.opcheck(gelu, (torch.randn(4, 8, 32, requires_grad=True),))

Swapped into every block's MLP (self.proj(gelu(self.fc(x)))), the model's loss is , the same as with F.gelu (), the largest gradient difference is , and torch.compile(fullgraph=True) gives one graph whose gradients differ from eager by at most measured here, CPU. The stepper beside this section adds them one at a time:

The stepper, step by step: what each registration adds

  1. @custom_op("ext::gelu", mutates_args=()): a kernel alone. The decorator defines the operator and registers your function as its kernel for every device. It also registers a fake slot and an autograd slot that raise. Eager forward runs; eager backward and torch.compile both stop: a kernel alone trains in neither mode.
  2. + gelu.register_fake: compile can trace. The fake fills the Meta slot: given input shapes it returns an empty output of the right shape. Dynamo can now trace the op as one node, but AOTAutograd cannot build the backward graph.
  3. + gelu.register_autograd: everything works. The formula fills the Autograd slot. Eager and compiled training both work, every parameter gets a gradient, and opcheck passes all four tests.

Slots as the decorator registers them (source in the closed block below); results recorded for the three variants kernel only, + fake and + fake + autograd of src/exp/custom_ops.py: a fake gives one compiled graph but no compiled backward, and only all three pass opcheck's four tests and train under compile.

custom_op is a thin layer over the dispatcher: it parses the schema, defines the operator in a torch.library.Library and registers the slots above at once: your function as the kernel at CompositeExplicitAutograd (every device, unless you name devices), and a fake and an autograd kernel that raise until you register your own. The ADInplaceOrView kernel (which bumps version counters) exists only for operators that mutate.

Source: what custom_op registers at definition (PyTorch v2.14.1)

1.2 The schema, inferred from type hints

The dispatcher needs a schema string, not Python annotations; custom_op writes it with torch.library.infer_schema. Python int becomes SymInt, an integer that may be symbolic under torch.compile, so size arguments do not force a recompile. Tensor? is an optional tensor and SymInt[] a list. Tensor(a0!) is an alias annotation: a0 names the memory, ! says it is written to; it appears for arguments listed in mutates_args.

What infer_schema produced for six signatures, and the error for one it cannot handle

1.3 Mutation and aliasing: say what you write

The compiler removes in-place operations (functionalisation, sibling page Reading 2.5), reuses buffers and reorders calls, which is safe only if every schema tells the truth. Declare every input you modify in mutates_args. Never return an input, or a view of one, as an output (return x.clone() if the result equals the input); custom_op checks this at run time:

The undeclared write is the dangerous one, because nothing checks it at run time. The lab's undeclared mutation variant clamps its input in place (x.clamp_(-3, 3)) under mutates_args=(). In the running example nothing visible goes wrong: activations never exceed 3, the loss is , it compiles into one graph. opcheck's schema test, fed inputs wide enough to be clamped, catches it:

1.4 The fake: the output's shape without running the kernel

A fake tensor carries a shape, dtype, device and strides but no data (sibling page Reading 2.5). torch.compile and torch.export trace with fake tensors and ask every operator what comes out for inputs of these shapes; yours cannot answer until you register a fake implementation that builds an empty output of the right shape and never reads input data.

A wrong fake is worse than none. The lab's wrong fake variant returns x.new_empty(x.shape[:-1]), a copy-paste slip that drops the last dimension. Eager mode never calls the fake, so training runs and the loss is right (). torch.compile fails one operator later, at the next layer, where the error no longer mentions your op:

opcheck points at the real culprit:

When the output size depends on the data (the positive entries of a tensor, the tokens routed to one expert), the fake asks for a fresh symbol with torch.library.get_ctx().new_dynamic_size(), an unbacked symbolic integer: a size known only at run time, carried through the graph as u0 with a run-time check that it is not negative measured here: compiled result , eager .

The missing-fake message, and the graph Dynamo captured for a data-dependent size

The graph for v = positive_values(x); v.sum() / v.numel():

1.5 The gradient: register_autograd

register_autograd(backward, setup_context=...) works like torch.autograd.Function split in two (sibling page Reading 3.4): setup_context(ctx, inputs, output) runs after the forward and saves what backward needs; backward(ctx, *grads) returns one gradient per input (None for inputs that need none). Write backward out of operators (here a second custom op with its own fake) and torch.compile traces it into the backward graph. Leave it out and the first backward raises, which is the good outcome. An operator defined directly with TORCH_LIBRARY in C++ (section 3) and given no autograd formula falls through to PyTorch's autograd fallback, which only warns and lets backward continue as if the op had no inputs needing gradients. In the running example that silently stopped training of each block's first MLP layer and the norm before it: of 52 parameters received a gradient. The sibling page shows how a key with no kernel falls back (Reading 2.3); the warning, as recorded here:

Source: the error custom_op raises at backward without a formula

1.6 One operator, one kernel per device

register_kernel("mps") adds a kernel at the MPS key next to the CPU one. The operator ext::gelu2 has the C++ kernel for CPU and a Metal kernel for the Apple GPU (section 4). Metal's standard library has no erf (), so the Metal kernel used GELU's tanh approximation while the CPU kernel computes the exact erf form. Same operator, two devices, two answers: they differ by up to , and the Metal kernel matches F.gelu(approximate="tanh") to measured on Apple M1 Pro. Nothing flags this: opcheck tests one device at a time and never compares kernels. Test every device's kernel against one reference.

The dispatcher's table for the two-device operator (torch._C._dispatch_dump)

1.7 opcheck: four tests, and what each one proves

TestWhat it doesWhat it catches
test_schemaRuns the op under a mode that records which inputs changed and what the outputs aliasUndeclared mutation or aliasing (only if the values actually change)
test_autograd_registrationChecks that an autograd kernel is registered when inputs require gradThe weakest of the four here: it passed for every variant it ran on, the bare C++ op on the autograd fallback included (grid below). custom_op always registers a kernel, one that raises
test_faketensorRuns the fake and the real kernel and compares shapes, dtypes, stridesMissing or wrong fakes
test_aot_dispatch_dynamicTraces forward and backward through AOTAutograd with dynamic shapes and compares with eagerMissing formulas, backward that cannot be traced, wrong gradients under compile
Checked against the recorded grid (2026-10-23)
An earlier version of this table said test_autograd_registration catches a C++ op left on the autograd fallback. The recorded run says otherwise: the C++ TORCH_LIBRARY, nothing else row passes it, and only test_faketensor and test_aot_dispatch_dynamic fail. Rely on the last one for gradients.

Every variant of the lab, every test, as recorded (hover or tap a cell for the message):

Source: opcheck's default test list at 2.14.1
Predict: the kernel + fake variant has a fake but no autograd formula. What does torch.compile(model, fullgraph=True) do on a training step?
Go deeper: the Custom-op lab tab shows all ten variants side by side: code, eager result, Dynamo's graphs and breaks, the compiled run and the four tests.

2. Custom operators under torch.compile, and two traps

The parent page showed the lesson on a toy function (Reading section 8: 3 graphs and 2 breaks against 1 and 0). Here it is on the whole running example, then what the compiler does with the opaque node, then two ways a correct-looking op loses its gradients under compile.

2.1 Dynamo traces the forward: an opaque call against a custom op

Dynamo, the front of torch.compile, records tensor operations into an FX graph and breaks it at a call it cannot trace, here a C++ function exposed through pybind11. Fig. 2 replays what torch._dynamo.explain recorded on one forward (src/exp/graphs.py), the GELU called directly, then as the custom op of section 1.

Fig. 2, step by step: what Dynamo recorded on one forward

  1. Dynamo starts at GPT.forward. It inlines every call it can (block, attention, MLP) looking for one graph. In the recording the outer GPT.forward ended up uncompiled: its 4 embedding operations (the back row) run eagerly in Python.
  2. Block 0: graph 1. ln1, attention, the residual and ln2: operations traced into one small graph (the first tray).
  3. The GELU: a graph break. The MLP's fc becomes graph 2 on its own; then Dynamo meets the C++ call and stops. Python runs raw_gelu outside any graph (the red box, lifted out of the row).
  4. After the break: graphs 3 and 4. A new graph starts for proj, another for the residual add. Inductor sees neither the GELU nor anything it could fuse across it.
  5. Blocks 1 to 3 reuse the four graphs. Compiled once for block 0, they run again; every block makes a trip through Python at its GELU.
  6. Done: graphs, breaks, an uncompiled outer frame. Final norm, head and loss (the front row) run eagerly too, op by op.

Each small box is one operation of the forward recorded by torch._dynamo.explain (101 in all), one row per stretch of the model; a glass tray is a compiled graph, one colour per graph; a box with no tray ran eagerly in Python; the red box is the graph break.

So the direct call leaves small graphs covering only the inside of a block; the parent's Compile lab measured what that shape costs with a print inside a block: 7 to 9% on the step. The reason Dynamo gave: . The custom op holds the whole forward in one graph.

Export has no fallback. torch.compile can break a graph and run Python; torch.export, which must produce one graph to save and run elsewhere, cannot. With the custom op, torch.export.export captured operations including ext.gelu nodes, still after run_decompositions() lowered the rest to core ATen operations, and the exported module's logits matched eager. With the direct call it failed, because the C++ function was handed a fake tensor and tried to read its data:

2.2 What Inductor does with an opaque node

Inductor turns the graph into code. The call() function it generated for the MLP's forward (fc, GELU, proj, inference):

F.gelu: generated kernel
custom op: generated kernels

With F.gelu, Inductor wrote one loop, cpp_fused_gelu_view_0, that reads the matmul's output and writes the activation in place. With the custom op it can only call your kernel, check that the output has the metadata the fake promised (assert_tensor_metadata, assert_alignment), and move on: nothing fuses across an opaque operator. For a big kernel (an attention, a fused MoE dispatch) that costs little; for a small element-wise op between two others you lose the fusion the compiler would have done for free.

The cost, measured
Training step of the running example, CPU, 4 threads measured on Apple M1 Pro, bench lock, load average about 3, median of 3 × 20 steps: F.gelu eager ms, compiled ms; the custom op eager ms, compiled ms. Almost all of the difference is the C++ kernel itself, about 11 times slower than ATen's GELU (section 3): an operator is only as fast as its kernel, and compiling cannot make an opaque kernel faster.
Predict: you want Inductor to fuse your element-wise kernel into its neighbours. Which registration lets it?

2.3 Two traps that drop gradients without an error

Both were found while building this page, with the C++ operator of section 3 given its fake and formula from Python by name (torch.library.register_fake("extc::gelu")).

Trap 1: registering after the first trace. In one process, the op was first traced bare, then registered, then compiled. The compiled model trained with the right loss, but the MLP weights got no gradients: the compiled backward treated the op's output as not needing one. opcheck in the same process says so (). The cause is a per-operator cache: the Python object for each operator overload remembers, per dispatch key, which kernel to use during tracing, and registering through torch.library does not empty it. Emptying torch.ops.extc.gelu.default._dispatch_cache after the registration made all four tests pass in the same process; so did a fresh process with the registrations made at import. Register everything when the module is imported, before any call.

Trap 2: the warm cache keeps the wrong answer. Compiled artifacts are cached on disk across processes: Inductor's FX graph cache and the AOTAutograd cache, which stores the compiled forward and backward pair. Four fresh processes shared one cache directory (src/exp/cache_trap.py, the running example compiled once, one forward and backward each):

The cache key evidently does not cover the operator's Python registrations (graph and configuration were identical), and turning off only the AOTAutograd cache fixed it. When you change an operator's registrations, clear the compile cache (TORCHINDUCTOR_CACHE_DIR, by default torchinductor_<user> in the temporary directory, or set TORCHINDUCTOR_AUTOGRAD_CACHE=0 while developing), and keep one cheap CI test that compares compiled gradients against eager on one batch.

A correct process read the broken backward that the first one cached

Recorded: parameters with no gradient were 16 of 52 in process 1 (late registration) and process 2 (registered at import, shared cache), 0 of 52 with TORCHINDUCTOR_AUTOGRAD_CACHE=0 and 0 of 52 with TORCHINDUCTOR_FORCE_DISABLE_CACHES=1. Loss 3.801371 in all four.

Source: the per-overload dispatch cache and the AOTAutograd cache flag (PyTorch v2.14.1)
Go deeper: torch.compile from the user's side owns Dynamo, guards, AOTAutograd and the caches in general; The compiler stack owns code generation below Inductor.

3. C++ extensions: TORCH_LIBRARY

The problem. Some kernels have to be compiled code: a hand-written loop, a call into a C++ library, a CUDA kernel. torch.utils.cpp_extension compiles C++ against PyTorch's headers and loads the result into the running process, three ways: load_inline (C++ in a Python string, built on first use), load (the same from files) and setup.py with CppExtension or CUDAExtension (a wheel built ahead of time, what libraries ship). The first two need the ninja build tool; it was not in the shared environment and had to be installed.

3.1 The tiny operator, built here

The running example's C++ GELU, whole file in src/exp/gelu_ext.cpp: a plain loop over the tensor's memory, then two macros that register it with the dispatcher.

static at::Tensor gelu_fwd(const at::Tensor& x) { TORCH_CHECK(x.device().is_cpu() && x.scalar_type() == at::kFloat, "extc::gelu: CPU float32 only"); auto xc = x.contiguous(); auto y = at::empty_like(xc); const float* in = xc.data_ptr<float>(); float* out = y.data_ptr<float>(); at::parallel_for(0, xc.numel(), 4096, [&](int64_t b, int64_t e) { for (int64_t i = b; i < e; ++i) out[i] = 0.5f * in[i] * (1.0f + std::erf(in[i] * 0.70710678f)); }); return y; } // ... gelu_bwd the same way ... TORCH_LIBRARY(extc, m) { // define: namespace extc, two schemas m.def("gelu(Tensor x) -> Tensor"); m.def("gelu_backward(Tensor grad, Tensor x) -> Tensor"); } TORCH_LIBRARY_IMPL(extc, CPU, m) { // kernels at the CPU key m.impl("gelu", &gelu_fwd); m.impl("gelu_backward", &gelu_bwd); }
# Python: build, load, then add what C++ did not say from torch.utils.cpp_extension import load_inline mod = load_inline(name="ext_gelu", cpp_sources=[src], functions=["raw_gelu", "raw_gelu_backward"], extra_cflags=["-O3"]) # loading runs TORCH_LIBRARY: torch.ops.extc.gelu exists torch.library.register_fake("extc::gelu")(lambda x: torch.empty_like(x)) torch.library.register_fake("extc::gelu_backward")(lambda g, x: torch.empty_like(x)) torch.library.register_autograd("extc::gelu", backward, setup_context=setup_context) y = torch.ops.extc.gelu(x)

TORCH_LIBRARY creates a static registrar, so the definitions run when the shared library is loaded. Afterwards the dispatcher's table shows the CPU kernel from the C++ file and the fake (at Meta) and the autograd kernel from Python. The same .so also exposed the two functions through pybind11 (functions=[...]), which is how the "before" side of section 2 called them without the dispatcher.

The macro's source, and the dispatcher's table for extc::gelu

3.2 What it costs

Overhead: through pybind11 the C++ function costs what F.gelu costs; as a dispatcher operator with a Python autograd kernel it costs about five times as much, because every call enters Python at the Autograd key even when nothing needs a gradient (a C++ autograd registration would avoid that; not measured here). Kernel: our loop is about 11 times slower than ATen's GELU, which is vectorised (4 floats per NEON instruction) and multi-threaded; ours computes one erf at a time, and at::parallel_for runs serially because the extension was compiled without OpenMP flags. Measure a custom kernel against what it replaces, on your shapes.

Overhead dominates 64 floats; the kernel dominates a real activation measured on Apple M1 Pro, CPU, 4 threads, bench lock, median of 3

Build. A cold load_inline of this 50-line file took to s (three builds, each in a fresh directory and process); afterwards the build directory acts as a cache.

One namespace, one TORCH_LIBRARY, per process
Loading a second build of the same file under another module name (to time a cold build) killed the Python process with SIGABRT (return code ) and no Python traceback: a namespace may be defined by one TORCH_LIBRARY block only. Use TORCH_LIBRARY_FRAGMENT to add definitions from several files, and never import two copies of an extension.
Beyond this example: autograd in C++, CUDA, one wheel for several PyTorch versions
  • Autograd in C++: subclass torch::autograd::Function and register it at the Autograd key with TORCH_LIBRARY_IMPL(extc, Autograd, m). Use it when you need C++-speed calls; the Python route above is simpler and enough for big kernels.
  • CUDA: CUDAExtension or load_inline(cuda_sources=...) compile .cu files with nvcc; register the kernel at the CUDA key exactly as above. Not run here (no NVIDIA GPU).
  • One wheel for several PyTorch versions: the C++ ABI changes between releases, so an extension built against 2.14 may not load into 2.15. PyTorch ships a smaller stable ABI for extensions, with its own registration macro (STABLE_TORCH_LIBRARY in torch/csrc/stable/library.h, line 355 of the 2.14.1 wheel's headers); not used here.
Go deeper: the custom C++ and CUDA operators tutorial; Writing kernels for writing the CUDA kernel itself.

4. Kernels that plug in: Metal, Triton, Helion

PyTorch does not need to understand a GPU kernel; it needs the same three facts as for any operator. The pattern is always: write the kernel, wrap it in an operator, register a fake and a gradient. What differs is whether the compiler can look inside. Writing fast kernels is its own subject (Triton and Gluon, Writing kernels); this section is about plugging them in.

The same GELU kernel plugged in three ways: what torch.compile sees in each

Opaque: a custom op wrapping a Metal, C++ or CUDA kernel (ran here). Visible: a triton_op, decomposed into its kernel launches under AOTAutograd so Inductor can schedule around them (read in the 2.14.1 source; not run). Traced call: a Helion kernel, registered with Dynamo as a higher-order operator (ran here on MPS: 1 graph, 0 breaks).

4.1 A Metal kernel on the Apple GPU, run here

torch.mps.compile_shader(source) compiles Metal Shading Language at run time and returns an object whose kernels you call with tensors; each thread computes one element:

lib = torch.mps.compile_shader(SHADER) @gelu2.register_kernel("mps") # gelu2: the custom op of section 1.6, CPU kernel in C++ def _(x): xc = x.contiguous() y = torch.empty_like(xc) lib.gelu_fwd(y, xc) # one thread per element return y

On an (8, 64, 1024) activation it took µs against µs for F.gelu(approximate="tanh") measured on Apple M1 Pro, MPS, median of 3, including a synchronize: an element-wise kernel is limited by memory traffic, and both read and write the same 2 MiB.

4.2 Triton: triton_op and wrap_triton (read, not run)

Triton is a Python-embedded language for GPU kernels that work on blocks of data; it is what Inductor generates for NVIDIA and AMD GPUs. Triton 3.8.0 on PyPI ships Linux wheels only (checked 2026-10-13), so nothing here ran. In the 2.14.1 source, triton_op is a custom_op whose fake is your own Python function (it only allocates outputs and launches kernels, so it can run on fake tensors), and which, under AOTAutograd, is decomposed into its kernel launches so Inductor sees the Triton kernels themselves. wrap_triton(kernel)[grid](...) is how a launch is written inside such an op so that dispatcher-level tracing (make_fx, non-strict export) can record it.

# a triton_op, condensed from the 2.14.1 docstring in torch/_library/triton.py (not run here) @triton.jit def add_kernel(x_ptr, y_ptr, out_ptr, n, BLOCK: tl.constexpr): offs = tl.program_id(0) * BLOCK + tl.arange(0, BLOCK) mask = offs < n tl.store(out_ptr + offs, tl.load(x_ptr + offs, mask=mask) + tl.load(y_ptr + offs, mask=mask), mask=mask) @torch.library.triton_op("mylib::add", mutates_args={}) def add(x: Tensor, y: Tensor) -> Tensor: out = torch.empty_like(x) n = out.numel() wrap_triton(add_kernel)[(triton.cdiv(n, 16),)](x, y, out, n, 16) return out

Two consequences. Under torch.export a triton_op stays one custom-op node rather than being decomposed (an exported program should not carry GPU-specific Triton source, the source explains). And the docstring recommends calling @triton.jit kernels directly when you need no operator at all: Dynamo can trace a raw Triton launch; the torch.library wrapper is needed only for operator behaviour (subclasses, dispatch modes, export).

Source: triton_op and wrap_triton at 2.14.1

4.3 Helion: kernels from tiled PyTorch, run here on the Apple GPU

Helion (PyTorch Foundation; 1.0 released 2026-04-03, 1.4.0 used here) lets you write a kernel as a loop over tiles with ordinary PyTorch operations inside; its compiler chooses block sizes, memory access and launch shape, and its autotuner can search them. Its settings name four code generators: Triton, CuTeDSL, Pallas and an experimental Metal one, which meant Helion could run on this Mac without Triton.

import helion, helion.language as hl # HELION_BACKEND=metal @helion.kernel(autotune_effort="none", static_shapes=True) def gelu(x: torch.Tensor) -> torch.Tensor: out = torch.empty_like(x) for tile in hl.tile(x.size()): # Helion splits the 3-D index space into tiles v = x[tile] out[tile] = 0.5 * v * (1.0 + torch.tanh(0.7978845608028654 * (v + 0.044715 * v * v * v))) return out

The element-wise kernel compiled and matched F.gelu(approximate="tanh") measured on Apple M1 Pro; exact GELU did not lower (Metal has no erf, the wall of section 1.6) and a row softmax stopped at the reduction. Without autotuning it took µs against µs for PyTorch's own: on its main backend (Triton on NVIDIA) the autotuner's search is the point, and none was run here. Two things worked fully. Ref mode (HELION_INTERPRET=1) ran both kernels, erf and softmax included, as plain PyTorch on the CPU with errors and : how you debug a kernel's logic without a GPU. Composition: inside torch.compile the Helion kernel gave graph and breaks, and registered as the MPS kernel of a custom op it passed opcheck's schema and fake tests.

Helion's backends, the status table, the generated kernel, and the Kernels Hub claim

Default configuration used: . Helion registers its kernels with Dynamo as a higher-order operator: . The generated kernel (Helion's Triton-like intermediate, before Metal translation), lines:

The old root page said prebuilt Helion kernels ship on the Hugging Face Kernels Hub. Checked: the kernels library 0.17.2 lists helion among the Python dependencies a Hub kernel may declare (kernels/python_depends.json); whether Helion kernels are published there is unconfirmed.

Go deeper: helionlang.com; the triton_op tutorial; Triton and Gluon for the language.

__torch_function__ sees what you called and no backward; __torch_dispatch__ sees ATen operators in both directions

Where this call was caught
The call
The last calls

5. Tensor subclasses: changing what a tensor is

The problem. Some extensions are not a new computation but a new kind of tensor: weights stored as int8 with a scale, a tensor split across eight GPUs, a float8 tensor that remembers its scaling factor. You want the model code unchanged (F.linear(x, w) stays F.linear(x, w)) while every operation on w does the right thing for its representation. A tensor subclass is a Python subclass of torch.Tensor that gets a say in every operation on its instances.

5.1 Two places to intercept: __torch_function__ and __torch_dispatch__

A call such as F.linear(x, w) passes two points where a subclass can step in. __torch_function__ is called first, at the Python API, with the function you called (linear, Tensor.add, Tensor.backward), before autograd. __torch_dispatch__ is called much later: the dispatcher reaches the Python key after autocast, autograd and view tracking have run, and hands over the ATen operator about to execute: aten::t and aten::addmm rather than linear, because linear decomposed on the way (sibling page Reading 2.3). In the tracer beside this section, step through one recorded training step of the running example with block 0's fc.weight replaced by a logging subclass of each kind (src/exp/subclasses.py; every row is a call the subclass actually received):

SubclassCalls seen in forwardin backwardLoss typeGradient type

In backward the __torch_function__ subclass saw only Tensor.backward itself, because autograd's engine runs backward in C++. Whether later operations reach a subclass depends on what it returns: rewrapped results spread it downstream (as DTensor does), plain results keep it to the weight (as an int8 weight's matmul does).

Every operation each subclass received, by phase

5.2 Wrapper subclasses: a tensor with no storage of its own

A wrapper subclass is created with torch.Tensor._make_wrapper_subclass(cls, shape, dtype=..., device=...): the outer object has a shape, a dtype and a device, so the rest of PyTorch treats it as a tensor of that shape, but it has no data. The real data lives in ordinary tensors stored as attributes (self.qdata, self.scale), and __torch_dispatch__ decides, per ATen operator, what to compute from them. Its key set gains Python and PythonTLSSnapshot ( for the DTensor below), which is what routes every call to your Python code.

Two decisions shape every such subclass. Contagious or not: does an operation on the subclass return the subclass (DTensor: a sharded result) or a plain tensor (an int8 weight: the matmul's output is ordinary float32)? And which operators to implement: the rest fall back to "dequantize and run the normal kernel" or to an error. One rule is not optional: nn.Parameter refuses a subclass whose detach() does not return the subclass, so handle aten.detach (and usually aten.t, aten._to_copy, aten.clone) by returning the subclass:

5.3 Build one: int8 weights for the running example

The subclass below stores each block weight as int8 qdata (same shape) and one float32 scale per output row (symmetric, per-channel: scale = max|w_row| / 127). It implements four ATen operators: the transpose and detach that nn.Linear and nn.Parameter need, addmm for the forward and mm for the backward's input gradient. The scale factors out of the matrix multiply, so the int8 values are multiplied first and the scale applied per output column afterwards. Full file: src/exp/subclasses_int8.py.

class Int8Weight(torch.Tensor): @staticmethod def __new__(cls, qdata, scale, transposed=False): shape = qdata.shape[::-1] if transposed else qdata.shape return torch.Tensor._make_wrapper_subclass(cls, shape, dtype=scale.dtype, device=qdata.device, requires_grad=False) def __init__(self, qdata, scale, transposed=False): self.qdata, self.scale, self.transposed = qdata, scale, transposed def __tensor_flatten__(self): # for torch.compile (5.4) return ["qdata", "scale"], (self.transposed,) @staticmethod def __tensor_unflatten__(inner, meta, outer_size, outer_stride): return Int8Weight(inner["qdata"], inner["scale"], meta[0]) __torch_function__ = torch._C._disabled_torch_function_impl @classmethod def __torch_dispatch__(cls, func, types, args=(), kwargs=None): if func is aten.t.default: # W.t(): flip a flag, move no data return Int8Weight(args[0].qdata, args[0].scale, not args[0].transposed) if func is aten.addmm.default and isinstance(args[2], Int8Weight): bias, x, w = args[:3] # x @ W^T + b, W = q * s[:, None] return torch.mm(x, w.qdata.to(x.dtype).t()) * w.scale + bias # ... aten.detach, aten.mm (backward), and a dequantizing fallback ...

Fig. 3, step by step: one int8 weight through one training step, as recorded

  1. A float32 weight. Block 0's fc.weight, 1024 × 256 numbers at 4 bytes each: 1,048,576 bytes. Height is bytes per number, so volume is memory.
  2. Int8Weight: a wrapper with no storage. The outer shell has the shape (1024, 256) and dtype float32 and holds no data; inside sit qdata, int8, 262,144 bytes, and scale, 1,024 float32 scales, 4,096 bytes: a quarter of the memory (the scale column is drawn thicker than to scale). For the 16 block weights: MB to MB.
  3. aten.t: flip a flag. F.linear asks for W.t(); the call comes down to __torch_dispatch__, which returns a new wrapper around the same qdata with transposed=True. No data moves.
  4. aten.addmm: unwrap. The multiply arrives with the activation x (512 tokens × 256). __torch_dispatch__ takes qdata out of the wrapper and converts it to float32 for the matmul: a temporary as large as the float weight exists during the multiply.
  5. Multiply, scale, bias: a plain result. mm(x, qT), times the scale per output column, plus the bias: an ordinary float32 output (512 × 1024), not rewrapped, so the subclass stops at the weight. In the recorded forward 16 t and 16 addmm calls reached it.
  6. Backward: aten.mm for the input's gradient. The gradient flows back through the same wrapper (16 t and 16 mm calls); the int8 weight itself is frozen, and the other parameters all received gradients.
  7. Under torch.compile: flattened away. __tensor_flatten__ names qdata and scale, so each int8 weight becomes two graph inputs ( to ) and the traced graph is plain ATen: the subclass is gone (5.4).

Bytes are derived from the shapes (1024 × 256 elements; 4 bytes in float32, 1 in int8, 1,024 float32 scales); the call sequence is the one recorded on the eager step and in AOTAutograd's forward graph (5.4). Activations: 512 tokens × 256 in, × 1024 out, float32.

The loss moved from to and the logits by at most : int8 per-channel rounding of a freshly initialised model. The quantized weights are frozen (requires_grad=False); the other parameters (embeddings, norms, biases) all received gradients, the setup that weight-quantized fine-tuning methods such as QLoRA start from (PEFT). The ATen operators that reached the subclass, recorded: forward ; backward . No call took the fallback.

5.4 Under torch.compile: flatten, trace, desugar

The compiler cannot keep a Python object inside a graph; it must know which tensors the subclass is made of, to pass them in as graph inputs and rebuild the subclass while tracing. That is the traceable-subclass protocol: __tensor_flatten__ returns the names of the inner tensors plus any non-tensor metadata, and __tensor_unflatten__ rebuilds the object from them. With it, Dynamo traced the int8 model into graph with breaks, and AOTAutograd ran __torch_dispatch__ on fake tensors and recorded what it did in plain ATen: the subclass disappears from the compiled graph (desugaring). Dynamo's graph took inputs; AOTAutograd's forward graph , because each of the 16 int8 weights became two (qdata and scale). The first block's attention projection in that graph:

The int8 weight is converted to float32 (_to_copy) right before the multiply. That is the honest cost of weight-only int8 on this CPU path: memory is saved at rest (a quarter of the bytes), not during the computation. torchao's own Int8WeightOnlyConfig weight, recorded on a nn.Linear of the same shape, issued the same kind of sequence: . A GPU kernel that reads int8 directly and dequantizes in registers is what turns the saving into speed (Quantization and Precision).

Forward of the running example, CPU, 4 threads measured on Apple M1 Pro, bench lock, median of 3
Eager, the subclass costs the Python round trip on 32 calls per forward plus the conversion; compiled, the Python is gone and int8 and float32 take about the same time.

5.5 The real ones are built the same way

DTensor (PyTorch's distributed tensor, the base of FSDP2 and tensor parallelism), torchao's NF4Tensor (the 4-bit format of QLoRA), Float8TrainingTensor and Int8Tensor all use this protocol; each was built here on block 0's fc.weight and taken apart in the closed block. Two facts matter on first read: at 2.14.1 DTensor's constructor and operator dispatch run in C++, with Python only for sharding rules not yet cached; and a subclass can tell FSDP2 what to send over the network (fsdp_pre_all_gather and fsdp_post_all_gather), which is how a sharded QLoRA or float8 run moves 4-bit or 8-bit bytes rather than float32.

DTensor, NF4, Float8 and Int8 taken apart, and the FSDP2 hooks (sources at pinned tags)

Each built on block 0's fc.weight (1024 × 256 float32, 1,048,576 bytes) and taken apart with __tensor_flatten__:

  • DTensor keeps the local shard and the device mesh as its inner parts and the placements as metadata. At 2.14.1 it is built in C++, sharing the wrapper-subclass helper, and its operators take a C++ fast path that only falls back to Python for sharding rules it has not cached; the Python __torch_dispatch__ only serves subclasses of DTensor:
    It refuses to mix with plain tensors rather than guess a placement: The Distributed PyTorch sibling owns how its placements propagate.
  • NF4Tensor (torchao) packs two 4-bit codes per byte plus double-quantized scales: 135,300 bytes for the 1 MiB weight. Its __torch_dispatch__ handles a table of ATen operators, and its docstring says the linear itself goes through an autograd.Function instead; its __torch_function__ looks F.linear up in a second table:
  • Float8TrainingTensor (torchao float8 training) holds float8 e4m3 data and one float32 scale; its operators come from a table (FLOAT8_OPS_TABLE). A matrix multiply of two of them ran on this CPU (); the speed-up is a GPU matter (H100-class float8 tensor cores), not measured here.
  • Int8Tensor (torchao 0.18.0) declares its inner tensors as class attributes and inherits flatten, unflatten and much of the boilerplate from TorchAOBaseTensor:

Subclasses and FSDP2. When FSDP2 shards a parameter whose inner tensor defines fsdp_pre_all_gather and fsdp_post_all_gather, it all-gathers whatever the first returns (the compact data) and rebuilds the full weight with the second. NF4 defines both, and so do torchao's float8 training tensor and its prototype int8 training tensors:

Go deeper: the Extending PyTorch notes (subclasses and modes); What (and why) is __torch_dispatch__; the subclass zoo; Libraries on top of PyTorch for where these appear in training stacks.

6. Dispatch modes: watch or change every operation in a region

A dispatch mode is the subclass idea without a subclass: a context manager whose __torch_dispatch__ is called for every ATen operation run inside the with block, whatever tensors it touches (the sibling page records one call key by key this way, Reading 2.2). PyTorch ships several; three on the running example.

FakeTensorMode: run the model with no data. Inside the mode, new tensors and parameters are fake, so the whole model ran and produced logits of shape without computing a number (how you check a 70-billion-parameter model's shapes on a laptop), but it cannot answer a question about values: loss.item() raised .

FlopCounterMode: count the arithmetic from a formula per operator. One forward and backward of the running example: FLOPs, exactly 6 × 3,156,736 × 512: six FLOPs per weight per token for every matrix-multiply weight (the 3,145,728 in the blocks plus the 11,008 of the head; the embeddings are lookups), over 512 tokens. The textbook "6 × parameters × tokens" with all 3,186,944 parameters gives . Your own operators count zero until you register a formula with register_flop_formula, and so did the CPU attention kernel (closed block). How FLOPs turn into utilisation (MFU) is on Performance math.

Two gaps in the FLOP count: CPU attention and your own operators

The CPU attention kernel (_scaled_dot_product_flash_attention_for_cpu) has no formula, so attention counted zero; written out by hand (attn="manual") its batched multiplies add .

from torch.utils.flop_counter import register_flop_formula @register_flop_formula(torch.ops.ext.gelu) # register before creating FlopCounterMode def _(x_shape, *, out_shape=None): return 8 * math.prod(x_shape) # your estimate per element

(Building the model inside FakeTensorMode needs care with tied weights: the root's make_model fails there because .to() cannot swap the tied embedding, as the sibling page found; constructing GPT(cfg) directly works.)

Your own mode. Twelve lines record every call (the parent's Inside one step tab is built this way):

from torch.utils._python_dispatch import TorchDispatchMode class Recorder(TorchDispatchMode): def __init__(self): super().__init__(); self.calls = [] def __torch_dispatch__(self, func, types, args=(), kwargs=None): self.calls.append(str(func)) return func(*args, **(kwargs or {})) with Recorder() as r: loss = model(x, y)[1]; loss.backward()

A TorchFunctionMode does the same at the Python API level (above autograd), and CommDebugMode counts collectives on DTensors (the parent's Distributed lab uses it). Cost: every call goes through Python. The sibling page measured 4.818 µs for a one-element add inside a dispatch mode against 0.622 µs without; use modes for tools and tests, not in a timed loop.

Depth: new devices, NVIDIA GPUs and interview rehearsal

New devices: PrivateUse1, briefly

A hardware vendor whose chip is not in PyTorch adds it without forking PyTorch through a reserved dispatch key, PrivateUse1. They register kernels at that key from a C++ extension (as in section 3, with TORCH_LIBRARY_IMPL(aten, PrivateUse1, m) for ATen operators), give the device a name with torch.utils.rename_privateuse1_backend("npu") (), add tensor methods such as .npu() with generate_methods_for_privateuse1_backend(), and plug in an allocator, streams and a compiler backend. PyTorch keeps a complete reference device in its own tests, torch_openreg (test/cpp_extensions/open_registration_extension/ at the v2.14.1 tag). Not run here: a device needs a C++ runtime, and nothing on this page depends on it. This is how non-NVIDIA chips arrive as first-class devices: Google and Meta's TorchTPU (device tpu) and AWS's TorchNeuron (device neuron), both public since 20 October 2026, are PrivateUse1 backends, and both send the graphs torch.compile captures to StableHLO for the vendor's compiler instead of through Inductor (TPUs and other accelerators, section 10). Most readers meet it through such a plugin package, not by writing one.

What carries over to NVIDIA GPUs, and what does not
  • Carries over unchanged: everything about registration and composition. Schemas, fakes, autograd formulas, opcheck, graph counts and breaks, export behaviour, the late-registration and cache traps, the subclass protocol and what reaches __torch_dispatch__: these are device-independent dispatcher and compiler logic.
  • Changes: the kernels. On CUDA you register at the CUDA key, write the kernel in CUDA C++ (CUDAExtension) or Triton (triton_op), and Helion's default Triton backend with its autotuner applies; none ran here. Inductor around an opaque op on a GPU loses fusions that matter more than on a CPU (each unfused element-wise op is a full round trip through GPU memory).
  • Changes: every timing on this page. Per-call overheads (3 to 4 µs for a Python-registered op, measured here) are paid on the CPU before every GPU launch as well, so many small custom ops hurt there too (Profiling, benchmarking and correctness shows how to see it); but a weight-only int8 or float8 kernel that reads the compact format directly is a GPU speed-up that the CPU path here does not show.
Interview rehearsal: twelve questions with short answers

What does torch.library.custom_op give you that calling a C++ function does not? A dispatcher operator: a schema, kernels per device, a fake implementation for tracing, an autograd formula, version bumps for mutation. So autograd, torch.compile (one node, no break), torch.export and dispatch modes all work with it (and vmap, once you add register_vmap).

What is a fake (meta) implementation and why does the compiler need it? A function computing the output's metadata (shape, dtype, device, strides) from the inputs' metadata, without data. Dynamo and export trace with fake tensors, so they must know every operator's output without running it.

How do you handle an op whose output size depends on the data? In the fake, allocate with a size from torch.library.get_ctx().new_dynamic_size(): an unbacked symbolic integer, carried as u0 through the graph with run-time checks.

Why must a custom op's schema declare mutation, and what does Tensor(a!) mean? Functionalization and Inductor reorder and reuse buffers assuming the schema is honest. Tensor(a!) names an alias set a and marks it written.

custom_op or triton_op? custom_op for opaque kernels (C++, CUDA, other libraries); triton_op when the body is Triton launches, so Inductor can see and optimise the kernels. Under export, both stay one node.

What does opcheck test? Schema honesty (mutation and aliasing), that an autograd kernel is registered, that the fake matches the real kernel's metadata, and that forward and backward trace through AOTAutograd with dynamic shapes and match eager.

__torch_function__ vs __torch_dispatch__? The first intercepts Python API calls (above autograd; sees linear; no backward). The second intercepts ATen operators at the Python dispatch key (below autograd; sees t and addmm, including backward's operations). Representation subclasses (DTensor, torchao) use the second.

What is a wrapper subclass, and how does torch.compile handle one? A tensor with metadata and no storage, whose data lives in inner tensors. With __tensor_flatten__ and __tensor_unflatten__ the compiler passes the inner tensors as graph inputs and desugars __torch_dispatch__ into plain ATen operations.

Why might weight-only int8 not speed anything up? If the kernel converts the weight to float before the matmul (as on the CPU path here), only memory at rest shrinks. Speed needs a kernel that reads int8 and dequantizes on the fly, and pays off where the matmul is memory-bound.

How is DTensor implemented? A tensor subclass holding the local shard and the device mesh, with placements as metadata. At 2.14.1 its constructor and op dispatch run in C++ (a fast path with cached sharding propagation), falling back to Python sharding rules.

You added register_autograd but compiled gradients are still missing. What do you check? Whether the op was traced before the registration (register at import), whether a stale compile cache is serving an old artifact (clear it or disable the AOTAutograd cache), and opcheck's test_aot_dispatch_dynamic.

How would you add support for a new accelerator? Out of tree through the PrivateUse1 key: kernels via TORCH_LIBRARY_IMPL(aten, PrivateUse1, ...), a renamed device, an allocator, streams, and a compiler backend; torch_openreg in PyTorch's tests is the reference, and TorchTPU and TorchNeuron are the production examples (both lower compiled graphs to StableHLO rather than Inductor).