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
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.__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).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.mutates_args decides whether the op has a kernel here; ext::gelu2 writes nothing, so the slot is empty and the call passes through.__torch_dispatch__. Tensor subclasses and dispatch modes receive the ATen operator here, below autograd (sections 5 and 6). Plain tensors skip it.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).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
aten::addmm, or yours, ext::gelu), with a schema, a one-line signature such as ext::gelu(Tensor x) -> Tensor.torch.compile stops a graph, runs Python, and starts a new one.torch.library.opcheck, four tests that the three facts are true.| You need | Use | Autograd | torch.compile | Measured here |
|---|---|---|---|---|
| A different gradient for code PyTorch can trace | torch.autograd.Function | Yours | Traced if forward and backward are traceable | Owned by the sibling page (Reading 3.4): no schema or fake to maintain |
| To call a kernel or library PyTorch cannot see | torch.library.custom_op with a fake and register_autograd; not a direct call | register_autograd | One node, no break, once it has a fake | Direct 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_LIBRARY | In C++ or from Python | Same as custom_op | Cold build to s; µs per call |
| A Triton kernel the compiler should optimise around | triton_op + wrap_triton, or a raw @triton.jit call; not custom_op | register_autograd | Visible: Inductor optimises around the kernel | Not run: Triton has no macOS build |
| A tiled kernel written as PyTorch-like code | Helion (compiles to Triton, or Metal, Pallas, CuTe) | Wrap it in an op | Traced as a kernel call, no break | Ran on MPS: 1 graph, 0 breaks |
| Weights or activations in a new format | A wrapper subclass (__torch_dispatch__) with __tensor_flatten__; not rewriting every layer | Above it: works unchanged | Compiled through | int8 weights: MB to MB, 1 graph |
| A tensor spread over devices | DTensor (already built); not your own subclass | Unchanged | Compiled through | C++ fast path; FSDP2 and tensor parallelism are built on it |
| To intercept Python-level calls on your type | __torch_function__ | Not seen in backward | Partly traced | calls in forward, in backward |
| To observe or rewrite every op in a region | TorchDispatchMode; not a subclass | Sees backward too | Eager tool | FLOP count of one step: |
| A new device | PrivateUse1; not a fork | Through the usual keys | Through the vendor's backend | Not 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.
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.
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.
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
@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.+ 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.+ 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.
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.
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:
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 graph for v = positive_values(x); v.sum() / v.numel():
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:
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.
| Test | What it does | What it catches |
|---|---|---|
test_schema | Runs the op under a mode that records which inputs changed and what the outputs alias | Undeclared mutation or aliasing (only if the values actually change) |
test_autograd_registration | Checks that an autograd kernel is registered when inputs require grad | The 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_faketensor | Runs the fake and the real kernel and compares shapes, dtypes, strides | Missing or wrong fakes |
test_aot_dispatch_dynamic | Traces forward and backward through AOTAutograd with dynamic shapes and compares with eager | Missing formulas, backward that cannot be traced, wrong gradients under compile |
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):
torch.compile(model, fullgraph=True) do on a training step?dynamo.explain: graph, breaks) and then fails when AOTAutograd traces the backward: The fake is enough for the forward; training needs the formula as well.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.
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
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.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).proj, another for the residual add. Inductor sees neither the GELU nor anything it could fuse across it.GPT.forward and everything it calls into a single graph; the embeddings are its first 4 operations.fc join the same graph: one tray under every row.ext::gelu. It asks the fake for the output's shape, records ext.gelu.default (the dark box) and keeps tracing: no break.ext.gelu.default appears once per block, nodes in all.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:
Inductor turns the graph into code. The call() function it generated for the MLP's forward (fc, GELU, proj, inference):
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.
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.triton_op, whose source it can inspect (section 4). A custom op is the right tool for a kernel that is already the whole fused computation.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.
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.
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.
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.
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.
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.
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.
TORCH_LIBRARY block only. Use TORCH_LIBRARY_FRAGMENT to add definitions from several files, and never import two copies of an extension.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.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).STABLE_TORCH_LIBRARY in torch/csrc/stable/library.h, line 355 of the 2.14.1 wheel's headers); not used here.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.
torch.compile sees in eachOpaque: 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).
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:
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.
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.
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).
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.
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.
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.
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.
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):
| Subclass | Calls seen in forward | in backward | Loss type | Gradient 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).
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:
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.
Fig. 3, step by step: one int8 weight through one training step, as recorded
fc.weight, 1024 × 256 numbers at 4 bytes each: 1,048,576 bytes. Height is bytes per number, so volume is memory.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.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.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.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.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.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.
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).
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.
Each built on block 0's fc.weight (1024 × 256 float32, 1,048,576 bytes) and taken apart with __tensor_flatten__:
__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.__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:
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.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:
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.
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 .
(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):
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.
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.
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.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).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).
Answer a few questions about what you need; the answer is the lightest hook that does the job, with a code skeleton, what to register, how to test it, and the evidence from this page's runs. The questions follow the table at the top of the Reading tab.
Ten ways of putting the same C++ GELU into the running example's MLP, from a direct call to a fully registered operator, each run for real with torch 2.14.1 on the CPU (src/exp/custom_ops.py, src/exp/graphs.py). For each: what is registered, what happens in eager training, what Dynamo captures, whether torch.compile(fullgraph=True) trains correctly, and what opcheck's four tests say. Pick two variants to compare; the defaults are the first and last steps of section 1 of the Reading tab.
Gradient differences are the largest absolute difference from the F.gelu model's gradients over all parameters that received one. "Parameters with gradients" counts the 52 parameter tensors (the tied embedding counts once). The made late variant was measured in one process after the bare C++ op had been traced; the at import one in a fresh process. Messages are cut to their first lines, with file paths removed.
This page's tabs, the parent topic and its tabs, the sibling pages, the knowledge base pages next door, and the best outside resources, each with an approximate time. Links checked on 2026-10-13; times updated 2026-10-23.
Custom operators from zero (schema, fake, autograd, kernels per device, opcheck), what compile and export do with them and two traps that drop gradients, C++ extensions, Metal, Triton and Helion kernels, tensor subclasses with a call-by-call tracer, dispatch modes; closed blocks for sources, PrivateUse1, NVIDIA GPUs and interview rehearsal. 31 min, plus 13 in closed details
Two or three questions to the lightest hook that works, with a skeleton, what to register, how to test, and this page's evidence. 5 min per question you bring
Ten registrations of one C++ GELU in the running example, side by side: eager gradients, Dynamo graphs and breaks, compiled training, the four opcheck tests. 15 min
The root: section 8 is the intuition-level version of this page; the running example is defined there. Its tabs: Inside one step (a TorchDispatchMode recording of one step), Compile lab (graph breaks and their cost), Distributed lab (DTensor and CommDebugMode), Ecosystem map. 26 min, plus 15 in closed details for the Reading tab
The machine this page plugs into: dispatch keys, tables, fallthroughs, fallbacks (Reading 2.3), fake tensors, autograd.Function; its Reading 2.2 records one call key by key with a dispatch mode. 24 min, plus 29 in closed details
Dynamo, guards, graph breaks, AOTAutograd, Inductor, export, caches. 36 min, plus 14 in closed details
DTensor's placements and sharding propagation, FSDP2 and TP built on it. 35 min, plus 20 in closed details
Profiling, memory, attention backends and torchao in practice. 38 min, plus 20 in closed details
Where these extension points show up inside HF, torchtitan, Lightning and others. 27 min, plus 12 in closed details
The map of GPU programming: one PyTorch call followed down to the instructions, and the five ways to get a kernel compared. 28 min, plus 4 in closed details
Writing the Triton kernels you would register with triton_op. 37 min, plus 9 in closed details
CUDA kernels and FlashAttention, the kernels behind a CUDAExtension. 34 min, plus 15 in closed details
PTX, SASS, NVRTC, and code generation below Inductor. 37 min, plus 22 in closed details
The number formats that torchao's subclasses implement. 34 min, plus 11 in closed details
QLoRA and the frozen quantized base weights of section 5.3. 26 min, plus 2 in closed details
FLOPs and MFU, for reading FlopCounterMode's count. 24 min
Timing a custom kernel honestly. 28 min, plus 8 in closed details
The official map of the routes in sections 1 to 4. 10 min
custom_op, register_fake, register_autograd, opcheck, step by step. 30 min
TORCH_LIBRARY, setup.py builds, CUDA kernels, Python registrations. 40 min
Every function used here, with its exact signature. reference
Raw Triton launches, triton_op and wrap_triton. 25 min
autograd.Function, __torch_function__, subclasses and modes. 40 min
The design note behind section 5, from the PyTorch developers' forum. 15 min
Small, readable tensor subclasses and modes to copy from. 30 min
What a fake tensor is and how FakeTensorMode works. 15 min
Integrating a new backend out of tree (section 7). 20 min
quantize_, the tensor subclasses of section 5.5, float8 training. 30 min
The classic tour of tensors, the dispatcher and how to write a kernel; older, but the model still holds. 45 min