Custom kernels with Pallas¶
Prerequisites: Memory model, storage and views, The optimization playbook
Chapter 11 ends with one move left: an op that is still the top of a compiled trace after the playbook has removed host gaps, recompiles, copies and padding, and after the existing kernels have been tried. This chapter is about that move. You write the op as a Pallas kernel, which means deciding yourself how the arrays are cut into blocks, which block of each array sits in VMEM at each step, and in what order the steps run; then you register it as a PyTorch op with torch.tpu.pallas.jax_op and call it from eager code or from inside torch.compile. The worked example is the fused residual RMSNorm + SwiGLU kernel from TorchTPU Performance: Execution Modes, XProf and Pallas Kernels, extended with a second grid axis so that it fits real MLP sizes. The order of work is fixed: plan the tiles on paper, prove the kernel correct in the Pallas interpreter on a laptop, prove it correct again on the TPU, and only then ask whether it is faster.
What this chapter covers¶
- When an op deserves a custom kernel, and the choice among a built-in TorchTPU op, Tokamax, Pallas and Helion.
- The Pallas programming model (grid, BlockSpecs, index maps) and registering a kernel as a PyTorch op with
torch.tpu.pallas.jax_op, including the signature rules the bridge enforces. - A kernel's double-buffered VMEM footprint and HBM reads, computed from block shapes and grid order, as the basis for choosing block sizes.
- Correctness checks in the Pallas interpreter on a CPU and against a PyTorch reference on the TPU, before any timing.
- Designing a fused kernel for a new operation: grid, block shapes, index maps, outputs and a test plan.
When a custom kernel is worth it¶
TorchTPU's custom-kernel guide gives three reasons to leave the built-in operators: to accelerate a model-specific operation, to fuse operations so that intermediates stop costing HBM bandwidth, and to implement an architecture that standard PyTorch operators do not cover. The FLUX case study's kernel walkthrough adds the two shapes these usually take on a TPU: masking or sparsity patterns that standard ops cannot express efficiently, and fusion barriers, where torch.compile fuses the elementwise chain but a contraction in the middle benefits from tiling you control.
Neither reason is a reason by itself. Chapter 11's rule stands: the op must be the top of a compiled trace that has already been through the playbook. Then ask what a kernel could remove, in the units of chapter 2. A kernel cannot make the MXU faster than its peak, so for an op that is compute-bound and near its bound, the only gain left is doing fewer FLOPs (skipping masked blocks, as Splash attention does). For a memory-bound op, the gain is bytes that never reach HBM: intermediates that stay in VMEM, or operands read once instead of several times. Estimate that number before writing code. For this chapter's fused block at its default shape (1024 rows, hidden 512, intermediate 1024, bf16), the four intermediates h, y, g and u would cost 12 MiB of HBM traffic if each op ran separately and each intermediate were written once and read back once at bf16 width (the kernel itself keeps h, g and u in float32 in VMEM), against 4 MiB of inputs the kernel must read anyway. How much of that 12 MiB the compiled reference already avoids depends on what XLA fuses, which only the compiled trace shows (chapter 10).
Then pick the cheapest tool that does the job. The custom-kernel guide lists three, and TorchTPU ships some kernels as ordinary ops:
| Approach | Status | Use it when |
|---|---|---|
Built-in torch.tpu.ops.* |
shipped (splash_sdpa is marked experimental in its source) |
the op exists: splash_sdpa for attention, ragged_dot for MoE grouped matmul, index-free max_pool{1,2,3}d |
| Tokamax | "Production Ready" (guide) | a standard LLM or MoE block: grouped matmul, token gathers and scatters, paged attention, Gated DeltaNet, Kimi Delta Attention, MLA, TopK |
Pallas via torch.tpu.pallas.jax_op |
"Production Ready" (guide); the function is decorated experimental in 0.2.0's source | a bespoke kernel with explicit VMEM tiling |
| Helion | experimental | one kernel source for GPU and TPU, written in a PyTorch-native DSL with @helion.kernel and hl.tile |
Tokamax kernels are themselves written in JAX Pallas and reach PyTorch through jax_op, with tile-size autotuning, XProf benchmarking and regression tests across TPU generations behind them, so a Tokamax kernel is the Pallas path with the tuning already done. Two names you may meet in other material are not on this list. Mosaic is the compiler entry point a Pallas TPU kernel lowers to (TorchTPU's architecture page names StableHLO and Mosaic as the two ways into the TPU compiler stack), not something you program directly from PyTorch. Kiln is a C++ kernel language inside torch_tpu (csrc/internal/mosaic/kiln/) that its header describes as "Pallas-shaped" and that the library uses for its own kernels; it has no user-facing API in the documentation, and this book does not cover it.
Ask the cheaper questions first; a Tokamax kernel is the Pallas path with the tuning already done. Helion is experimental: for production, use Tokamax or Pallas. Whichever card you reach, capture a new trace and check that the op shrank.
The Pallas programming model¶
Pallas is JAX's kernel language, and on a TPU it lowers to Mosaic. A TPU Pallas kernel has four parts, all visible in a pl.pallas_call:
- The kernel body, a Python function whose arguments are refs:
x_ref[...]reads the block the ref points at ando_ref[...] = vwrites one. Inside the body you writejax.numpycode on whole blocks: elementwise math runs on the VPU andjnp.doton the MXU. - The grid, a tuple such as
(4, 4). The body runs once per grid point, andpl.program_id(axis)tells it which one. - One BlockSpec per input and output,
pl.BlockSpec(block_shape, index_map). The block shape is the slice of the array the body sees; the index map takes the grid indices and returns the block's index along each dimension (in blocks, not elements). Pallas copies the chosen block of each input from HBM into VMEM before the step, and copies each output block back afterwards. - Compiler parameters,
pltpu.CompilerParams(dimension_semantics=..., vmem_limit_bytes=...), which say which grid axes are independent and how much VMEM the kernel may use.
Follow one step: each index map turns (i, j) = (1, 2) into one block per array, and only those blocks are in VMEM while the body runs. The empty right-hand slots are where the next step's blocks are already arriving.
Three properties of this model matter more than the syntax.
The grid is a loop, not a launch of parallel blocks. A CUDA grid launches thread blocks that run concurrently. The JAX Pallas TPU guide is explicit that a TPU grid is "generally not processed in parallel, but sequentially, in lexicographic order": for a grid (i, j), j changes fastest. This follows from the hardware in chapter 1: a TensorCore is a single-threaded processor whose scalar unit issues the DMAs, and parallelism lives inside each step, in the VPU's (8, 128) lanes and the MXU's systolic array, not across steps.
Copies overlap compute, and repeated blocks are not copied again. Pallas pipelines each BlockSpec: while the body computes on step t, the DMA engines fetch step t + 1's blocks and write back step t - 1's output. Every BlockSpec is double-buffered, and the Pallas guide says HBM communication is "handled by the compiler and overlapped with compute". And when consecutive steps use the same block index for an input, the guide says the HBM transfer for the second step "is skipped, as the data is already available". The scaling book's TPU chapter describes the same pipelining for XLA's own matmuls, which stream chunks through VMEM to keep the MXU busy (How to Scale Your Model, "What is a TPU?"); a Pallas kernel is that pipeline with the chunking written by you.
Axes are declared parallel or arbitrary. dimension_semantics marks each grid axis. The guide's rule: the axes are a run of "parallel" axes followed by a run of "arbitrary" ones, an axis is parallel unless the output block does not change along it, and only parallel axes can be split across a chip's cores. An "arbitrary" axis is one that carries state between steps, such as the k axis of a tiled matmul that accumulates into a pltpu.VMEM scratch buffer declared in scratch_shapes; torch_tpu's own rowwise_scaled_grouped_mm kernel uses ("parallel", "arbitrary", "arbitrary") with such an accumulator. In this chapter's kernel every output block depends on one (i, j) only, so both axes are parallel.
Block shapes must be TPU tiles. The guide's rule for the last two dimensions of a block: divisible by 8 and 128 respectively, or equal to the array's dimensions. This is chapter 5's tile again, now as a constraint on your code. Chapter 5's model adds that 2-byte types pack 16 rows per tile, so a bf16 block whose row count is a multiple of 8 but not 16 is legal but half of its last tile row is padding. A norm weight is given shape (1, hidden) rather than (hidden,) so that its block is 2D, and its one row is legal because it equals the array's full first dimension; it still occupies a whole (16, 128)-tiled slab of VMEM, as chapter 5's tile model shows.
The scaling book's roofline chapter gives the reason block shape matters for speed, not just legality: a matmul computed in \(b_m \times b_n\) output tiles re-reads its operands for every tile they meet, and its intensity falls to about \(\frac{b_m b_n}{b_m + b_n}\) (How to Scale Your Model, "Rooflines", footnote on tiled matmuls; chapter 2 of this book). XLA picks tiles for its own fusions. In a Pallas kernel, you pick them, and the grid order decides which operand gets re-read.
Writing the kernel¶
The kernel from TorchTPU Performance: Execution Modes, XProf and Pallas Kernels fuses a pattern every LLM block has: add the residual, RMS-normalize, then compute silu(y @ Wg) * (y @ Wu). The companion module code/ch12_pallas/kernel.py uses the same kernel body with a second grid axis j over the intermediate dimension, so that only a (hidden, block_inter) slice of each weight matrix has to be in VMEM at once. Stripped of the deliberately broken variants the module also builds for testing:
import jax
import jax.numpy as jnp
from jax.experimental import pallas as pl
from jax.experimental.pallas import tpu as pltpu
def kernel(x_ref, res_ref, w_ref, wg_ref, wu_ref, o_ref):
# VPU, float32: residual add and RMSNorm of one (block_rows, hidden) tile
h = x_ref[...].astype(jnp.float32) + res_ref[...].astype(jnp.float32)
y = h * jax.lax.rsqrt(jnp.mean(h * h, axis=-1, keepdims=True) + eps)
y = (y * w_ref[...].astype(jnp.float32)).astype(wg_ref.dtype)
# MXU, float32 accumulation: one (hidden, block_inter) slice of each projection
g = jnp.dot(y, wg_ref[...], preferred_element_type=jnp.float32)
u = jnp.dot(y, wu_ref[...], preferred_element_type=jnp.float32)
o_ref[...] = (jax.nn.silu(g) * u).astype(o_ref.dtype)
def fused_rmsnorm_swiglu(x: jax.Array, residual: jax.Array, norm_weight: jax.Array,
w_gate: jax.Array, w_up: jax.Array) -> jax.Array:
rows, hidden = x.shape
inter = w_gate.shape[1]
br, bi = block_rows, block_inter
if rows % br or inter % bi:
raise ValueError("the grid would skip the remainder")
row_tile = pl.BlockSpec((br, hidden), lambda i, j: (i, 0))
return pl.pallas_call(
kernel,
out_shape=jax.ShapeDtypeStruct((rows, inter), x.dtype),
grid=(rows // br, inter // bi), # rows_outer: j fastest
in_specs=[row_tile, row_tile,
pl.BlockSpec((1, hidden), lambda i, j: (0, 0)),
pl.BlockSpec((hidden, bi), lambda i, j: (0, j)),
pl.BlockSpec((hidden, bi), lambda i, j: (0, j))],
out_specs=pl.BlockSpec((br, bi), lambda i, j: (i, j)),
compiler_params=pltpu.CompilerParams(dimension_semantics=("parallel", "parallel"),
vmem_limit_bytes=vmem_limit_bytes),
interpret=interpret,
)(x, residual, norm_weight, w_gate, w_up)
Read the BlockSpecs as a contract. x and residual change with i only, so each row tile is loaded once and stays while j runs (the copy is skipped). The norm weight never changes. The weight slices change with j only. The output block is unique to (i, j), which is why both axes can be parallel. The normalized activations y exist only as a VMEM value inside the body: that is the fusion. The price of the second axis is visible too: the residual add and the normalization are recomputed for every j, cheap VPU work traded for a VMEM footprint that fits.
The precision choices follow the reference implementation and chapter 6: the add and the normalization in float32, y rounded to the weights' dtype before the MXU, both matmuls accumulated in float32 (preferred_element_type), and one cast at the end. The divisibility check is not decoration. rows // br silently drops a remainder, and the dropped rows are never computed; section "Correctness first" shows what that looks like.
The grid order is a design decision. The module also accepts grid_order="inter_outer", which runs the grid as (j, i). Same blocks, same result (the tests check the two orders are bit-identical on a CPU), different copies: now the weight slices stay while i runs, and x is re-read for every j. The animation walks a (3, 3) grid and counts the copies.
Watch the counter, not the blue boxes. Every step reads one x block and one W block, but a copy only happens when the block index changes; the operand on the outer axis is the one copied once.
Calling it from PyTorch: torch.tpu.pallas.jax_op¶
The bridge is one function. Its signature in torch_tpu 0.2.0 (src/torch_tpu/_internal/pallas/pallas.py, listed in the public API):
torch.tpu.pallas.jax_op(name, fn=None, /, *, donate_argnums=None, mesh=None,
input_partition_specs=None, output_partition_specs=None)
With fn it returns the registered op (a torch.library CustomOpDef); without it, it returns a decorator. The custom-kernel guide's example uses the functional form, and so does the companion code:
import torch
from kernel import make_fused_rmsnorm_swiglu # code/ch12_pallas/kernel.py
fused = torch.tpu.pallas.jax_op(
"ch12::fused_rmsnorm_swiglu", # namespace::name, exactly one "::"
make_fused_rmsnorm_swiglu(block_rows=256, block_inter=1024,
grid_order="inter_outer", vmem_limit_bytes=64 * 2**20),
)
x, res, w, wg, wu = (t.to("tpu") for t in inputs) # bf16 torch tensors
out = fused(x, res, w, wg, wu) # eager
step = torch.compile(lambda *a: fused(*a), backend="tpu", dynamic=False, fullgraph=True)
out = step(x, res, w, wg, wu) # one op inside a compiled graph
API stability
name comes first and is positional, and the only keyword arguments are donate_argnums, mesh, input_partition_specs and output_partition_specs. Static arguments are not declared; they are inferred, as below. The older custom_jax_kernel, which took static_argnums explicitly, is deprecated in favour of jax_op. The custom-kernel guide calls the Pallas path "Production Ready" while the 0.2.0 source decorates jax_op as experimental and "subject to change"; pin your TorchTPU version.
The signature rules come from the type annotations. jax_op reads the function's signature with inspect.signature(fn, eval_str=True) and builds the PyTorch op schema from it:
- Every parameter must be annotated, or registration raises
ValueError: Missing argument type annotation. Tensors are annotatedjax.Array(or sequences of them); other allowed types are plain values:bool,int,float,str, dtypes, enums,Literals and some unions and sequences of these. - Every non-tensor parameter becomes a static argument: a compile-time constant that is part of the cache key. Calling the op with a new value traces and exports a new kernel.
- The return annotation must be
jax.Array, a tuple of them, or a plain value; a tuple return gives the op several outputs. - The name must contain a namespace and exactly one
::.
Because of the first rule, a module that defines kernels must not use from __future__ import annotations: the factory imports jax inside a function, and string annotations would not resolve. The companion module carries a comment saying so.
What happens at trace time and at run time. The FLUX case study and its kernel walkthrough insist on one point: JAX is not executed when the model runs. Pallas ships inside the jax package, so the kernel is written with JAX syntax, but jax_op uses JAX only to trace and export.
The upper lane runs once for each new combination of shapes, dtypes and static arguments; the lower lane runs on every call. No arrow crosses from a torch tensor into JAX.
In the source, the first call with a new signature converts each tensor's shape and dtype into a jax.ShapeDtypeStruct placeholder, traces the jax.jit-wrapped function on those placeholders, and exports it with jax.export for the tpu platform. The result is a serialized StableHLO module in which the Pallas kernel is carried as a Mosaic payload. jax_op strips the outer module's debug locations, hashes it (a BLAKE2 fingerprint) and registers the serialized module with TorchTPU's C++ runtime under that fingerprint, so that the same kernel traced from a different call site, or in another process, maps to the same compiled executable. At registration it also installs a fake (meta) kernel, built from the same export, so Dynamo and AOTAutograd can trace through the op under torch.compile without running it. After that, calls dispatch the compiled kernel directly on the torch.Tensor TPU buffers, in eager mode and in compiled graphs alike; no tensor is ever converted to a jax.Array.
Training needs a backward. A jax_op has no gradient of its own. Register one on the returned op, as the FLUX case study does for Splash attention: a second jax_op for the backward kernel, a setup_context that saves what backward needs, and op.register_autograd(backward, setup_context=setup_context). The case study's forward returns the softmax logsumexp as a second output so the backward kernel does not recompute the forward.
Caching ops under torch.compile. A kernel specialized on configuration (block sizes, masks) is registered once per configuration. The FLUX walkthrough's pattern: hash the configuration into a unique op name, cache the name, look the op up with getattr(torch.ops.<namespace>, name), and mark the lookup function torch._dynamo.assume_constant_result. It returns the name string, not the CustomOpDef, because Dynamo cannot install guards on the CustomOpDef object, and returning it breaks torch.compile.
Limits to design around. Bounded dynamic shapes (chapter 7) are not supported with custom kernels registered through jax_op, and the default fake kernel raises if it sees a symbolic dimension; keep kernel inputs static, bucketed if they must vary. donate_argnums lets the kernel reuse an input's buffer, after which that tensor is invalid and must not be read. And mesh, input_partition_specs and output_partition_specs, with torch.tpu.pallas.get_pallas_mesh, register kernels that run across chips; the distributed support guide uses them for kernels with inter-chip DMA, which belong to Part IV.
Correctness first: testing on a CPU¶
A kernel that is fast and wrong is a regression. The first gate runs on a laptop: Pallas can execute a kernel body in an interpreter on JAX's CPU backend, and a test can compare the result with a PyTorch reference. code/ch12_pallas/reference.py holds the reference (the fused block's math in plain PyTorch, with an unfused twin built from F.rms_norm and F.linear to check it), and run.py --cpu-smoke runs the comparison when jax is installed (pip install -r requirements-optional.txt; without it the kernel tests are skipped and the planner and reference tests still run).
There are two interpreters, and they are not equally strict. interpret=True is the generic one. The JAX Pallas TPU guide recommends checking TPU kernels against pltpu.InterpretParams(), which models the TPU more closely. In jax 0.12.1 it fills memory that the kernel never wrote with NaN and raises on an out-of-bounds block read; the companion code uses it by default (interpret="tpu"). Real output, abridged to the kernel sections:
$ python code/ch12_pallas/run.py --cpu-smoke
== 3. the Pallas kernel in the interpreter on the CPU, against the reference
shape rows=256 hidden=256 inter=512, block_rows=64
dtype interpreter grid order block_inter grid max |err| result
float32 TPU rows_outer 512 (4, 1) 4.77e-06 ok
float32 TPU rows_outer 128 (4, 4) 4.77e-06 ok
float32 TPU inter_outer 128 (4, 4) 4.77e-06 ok
float32 generic rows_outer 128 (4, 4) 4.77e-06 ok
bfloat16 TPU rows_outer 512 (4, 1) 7.81e-03 ok
bfloat16 TPU rows_outer 128 (4, 4) 7.81e-03 ok
bfloat16 TPU inter_outer 128 (4, 4) 7.81e-03 ok
bfloat16 generic rows_outer 128 (4, 4) 7.81e-03 ok
== 4. broken index maps and grids: what the interpreters report
x_map_ignores_i
TPU interpreter: wrong values in 192 of 256 rows (max |err| 9.55)
interpret=True : wrong values in 192 of 256 rows (max |err| 9.55)
out_map_ignores_j
TPU interpreter: NaN in 98304 never-written elements (256 rows)
interpret=True : NaN in 98304 never-written elements (256 rows)
x_map_off_by_one
TPU interpreter: raised: Out-of-bounds block index (4, 0) for input "x_ref" in iteration (3, 3) on de...
interpret=True : wrong values in 192 of 256 rows (max |err| 9.63)
floor_grid
TPU interpreter: NaN in 16384 never-written elements (32 rows)
interpret=True : NaN in 16384 never-written elements (32 rows)
block_rows=36 (rows=216, float32)
TPU interpreter: matches the reference (max |err| 2.86e-06); planner: block_rows=36 is not a multiple of 8 sublanes (nor all 216 rows)
[ok] only the planner flags the misaligned block; the interpreter runs it
not checked by either interpreter: (8, 128) block alignment and VMEM capacity; use tiles.plan_tiles, then the verifier's TPU lowering on a machine with TorchTPU
cpu-smoke: OK
The correct kernel. In float32 the kernel differs from the reference by \(4.8 \times 10^{-6}\), accumulation order. In bf16 it differs by \(7.8 \times 10^{-3}\), one bf16 rounding step at the output's magnitude (bf16 keeps 8 significant bits; chapter 6). The tolerances in reference.py follow from that: \(10^{-4}\) for float32, \(2 \times 10^{-2}\) for bf16. Different grid orders and inter tilings give the same numbers, as they should: they change which copies happen, not the arithmetic.
The broken kernels. Each is one wrong lambda or one missing check, and each teaches what kind of evidence finds it.
x_map_ignores_ireturns(0, 0)for the input blocks, so every row tile reads row tile 0. Nothing fails and no NaN appears; the first 64 rows are even right. Only the comparison with a reference finds it. This is the bug class that ships.out_map_ignores_jwrites every column tile's result into column tile 0, so three quarters of the output is never written. The interpreter's NaN fill makes that visible. On a TPU the unwritten memory holds whatever the buffer held before, so the same bug returns plausible garbage.x_map_off_by_onereads blocki + 1. The TPU interpreter raises at the first out-of-bounds read and names the iteration;interpret=Trueclamps the read and returns wrong values without an error. Use the strict one.floor_griddrops the guard, and with 288 rows and 64-row blocks the grid covers 256: the last 32 rows are never computed.
What neither interpreter checks. A 36-row block breaks the TPU tile rule, and both interpreters run it and match the reference. Neither models VMEM capacity either. Those are the planner's job (next section) and, on a machine with TorchTPU, the verifier's.
The verifier. torch.tpu.pallas.verifier.verify(target, args, kwargs=None, *, mode=..., options=None) is experimental and runs on a CPU. Handed a jax_op, it runs op-contract, TPU-lowering, model-checking, autograd-parity and CPU-interpret checks; handed a raw JAX function, model-checking and interpret checks; handed any other callable, such as an nn.Module, it traces it to FX, checks buffer donation and aliasing, and verifies every jax_op the graph calls at the shapes it uses. Only Severity.ERROR findings fail a report; report.raise_for_errors() raises VerificationError. The mode matters. VerificationMode.FULL, the default, executes kernels in interpret mode, and creating JAX's CPU devices initializes JAX's other backends too, including the TPU, so in a process that already owns the TPU through TorchTPU use VerificationMode.STATIC, which never executes kernels and needs no JAX devices, and run FULL in its own process with JAX_PLATFORMS=cpu. In 0.2.0 the public Phase enum defines no members, so read what a report covered from report.checked_phases. verify is also forbidden inside a compiled region.
Choosing block sizes¶
Block sizes are bounded from above by VMEM and from below by efficiency, and the grid order decides what they cost in HBM traffic. Do the arithmetic before the first TPU run; code/ch12_pallas/tiles.py does it for this kernel.
VMEM per step. Every BlockSpec is double-buffered, so each block counts twice, padded to whole tiles. For this kernel:
where \(B(r, c)\) is the padded size of an \(r \times c\) block in the input dtype and \(B_{32}\) the same in float32 for the temporaries h, g and u (counted once). For the default shape this is 8.53 MiB, of which 0.03 MiB is the norm weight's padding to a 16-row bf16 tile; an estimate that ignores that padding gives 8.50 MiB. The term that dominates is the weights: in the single-axis kernel both full weight matrices sit in VMEM, double-buffered. That is fine at hidden 512 and impossible at real sizes.
The budget. What a kernel may use is a scoped limit, below the physical capacity. The TorchTitan TPU optimization guide says Pallas tile sizes are bounded by the per-core scoped VMEM limit, that the default is conservative, and that on v6e its recipes set LIBTPU_INIT_ARGS="--xla_tpu_scoped_vmem_limit_kib=65536" (64 MiB); the value is generation-specific, so check that it is accepted at start-up. A single kernel can also set its own limit with pltpu.CompilerParams(vmem_limit_bytes=...): torch_tpu's grouped-matmul kernel uses 48 MiB, and TorchTitan's fused cross-entropy kernel computes 90% of pltpu.get_tpu_info().vmem_capacity_bytes and picks its vocabulary block as the largest that fits. For physical capacity, chapter 1 gives 64 MiB per TensorCore on v7x, and the JAX guide says only "16MB+". VMEM capacity differs by generation, so ask the hardware with get_tpu_info() instead of hard-coding a figure.
A real MLP. Take a 4096-row batch, hidden 4096 and intermediate 14336 in bf16 with 256-row blocks. Without tiling the intermediate dimension the kernel needs 502 MiB of VMEM. Tiling it, the largest block that fits 64 MiB is 1024 columns, at 47.25 MiB.
Read the two panels together. The left one says which blocks fit; the right one says which fitting blocks keep the kernel above the ridge. With rows_outer, no fitting block does.
HBM reads, by grid order. Use the copy-skipping rule from the model: an input is fetched again only when its block index changes between consecutive steps.
rows_outerkeeps each row tile ofxwhilejruns, soxandresidual(64 MiB) are read once, but both weight matrices (224 MiB) are read once per row tile: 16 times, 3,648 MiB. With the output write, that is 244 FLOPs per byte, below both ridges: the fused kernel would be memory-bound on weight re-reads, and the block size of the intermediate dimension does not change it.inter_outerkeeps each weight slice whileiruns: weights once,xandresidual14 times, 1,120 MiB and 745 FLOPs per byte, above both ridges.
The general rule: put the larger operand on the outer axis, so it is the one read once, and choose the inner block so that the operand that is re-read is re-read few times. With rows_outer the lever is block_rows: 1024-row blocks with 256-column weight slices fit in 59.25 MiB and read 960 MiB (856 FLOPs per byte), because the weights are now re-read 4 times instead of 16. Two cautions. These are model numbers: they ignore anything the compiler does beyond the documented copy skip, and the chart's intensity counts HBM traffic only, while VMEM bandwidth and the VPU work recomputed per j set their own limits. And the lower bound on blocks is real: the TorchTitan guide says small Splash blocks (256) "usually underperform", and the MXU wants the contracted and output dims in multiples of its 128 or 256 width (chapter 11, padding waste).
Then sweep on the TPU. The planner narrows the candidates; only a measurement picks one. The FLUX case study is the cautionary tale: Splash attention with its default 512-token blocks was about 10% slower than standard SDPA under compilation, float32 inputs slower still, and with 2048-token blocks in bf16 it took the compiled block from 153.60 to 122.51 ms (1.25x). The guide's summary of every tile default: "a starting point, not an optimum". Expect tuned blocks not to carry over between generations.
Kernels to reuse before writing one¶
Most of the kernels a transformer needs exist. Check these first, in this order.
torch.tpu.ops.splash_sdpa. TorchTPU's built-in Pallas Splash attention, a replacement for F.scaled_dot_product_attention on (B, H, S, D) tensors with a Pallas backward. Splash is a flash attention whose grid visits only the blocks of the mask that are not empty, so a causal or local mask saves FLOPs as well as bytes. Its keyword arguments include is_causal (default True, wrong for bidirectional attention such as FLUX's), local_window_size, segment_ids for packed sequences, and the block sizes block_q, block_kv, block_q_dkv, block_kv_dkv and their relatives. A block size left as None defaults to the largest multiple of 128, up to 512, that divides the sequence length. The FLUX case study's call:
attn = torch.tpu.ops.splash_sdpa(q, k, v, is_causal=False, block_q=2048, block_kv=2048,
block_q_dkv=2048, block_kv_dkv=2048)
Tokamax. The kernel families listed in the table above, exposed as PyTorch APIs through jax_op. The docstring of torch_tpu's deprecated custom_jax_kernel shows the underlying pattern on tokamax.ragged_dot, and the TorchTPU API reference lists torch.tpu.ops.ragged_dot for the same MoE grouped matmul.
TorchTitan's TPU kernels. The fused linear cross-entropy from chapter 11, which never materializes the logits, and Splash attention, both with block sizes exposed in the job config.
Kernels inside built-in ops. Some ATen ops are Pallas kernels already: torch_tpu exports its scaled-matmul kernels at build time and embeds them in the lowering of torch._scaled_mm and torch._scaled_grouped_mm (scaled_mm_generate.py and scaled_grouped_mm_generate.py; the generator's docstring reads "Generate blockwise scaled mm Pallas kernel MLIR module embedded C++ files").
Reading one of these kernels is also the best way to learn the parts of Pallas this chapter only names: scratch_shapes accumulators on an "arbitrary" axis, scalar prefetch of metadata into SMEM, and manual DMA.
Performance second: measuring on a TPU¶
With parity established on a CPU, the TPU run repeats it and then times the kernel. run.py without --cpu-smoke does this on a TPU VM with TorchTPU and jax installed. It plans the tiles and stops if they do not fit; registers the kernel with jax_op; runs verifier.verify(op, args, mode=VerificationMode.STATIC) and raises on errors; checks the kernel in eager mode and inside torch.compile, and the compiled reference, against the CPU reference at bf16 tolerance; and then times three variants with the FLUX case study's method (3 warm-up calls, 10 timed calls back to back, one synchronize, profiler off).
The comparison that matters is the kernel against the compiled reference, not against eager: eager pays HBM round trips that compile already removes, and a kernel that only beats eager is not an optimization. No speedup is claimed for this kernel; measure your own, and report the numbers with the shapes, block sizes, grid order, VMEM limit, dtype and TorchTPU version, and keep the kernel only if it wins.
--profile-dir captures one XProf trace of the compiled reference and one of the compiled kernel with chapter 10's TpuProfilerConfig. The kernel enters the program as a custom call carrying the Mosaic payload, so look in the XLA Ops row for the custom-call op where the reference had its fusions and dots; the companion kernel passes name="ch12_fused_rmsnorm_swiglu" to pallas_call to make it easier to find. The exact op name XProf shows is something to confirm on your own trace.
Failure modes¶
| Symptom | Cause | Fix |
|---|---|---|
| Rows or tiles of the output wrong, no error, no NaN | An index map that ignores a grid index ((0, 0) instead of (i, 0)) |
Compare with a reference over the whole output; test several grid sizes, not one |
| NaN in the interpreter's output; plausible garbage on the TPU | Output blocks never written: an output index map that collapses an axis, or rows // block_rows dropping a remainder |
Guard divisibility in the wrapper; use pltpu.InterpretParams() so unwritten memory is NaN |
Out-of-bounds block index in the TPU interpreter, wrong values with interpret=True |
An index map that runs past the array (i + 1) |
Fix the map; test with the strict interpreter |
| Lowering or verifier error on block shape | Block's last two dims not multiples of 8 and 128 and not the full dims | Align blocks; give 1D operands a (1, n) shape; plan with tiles.plan_tiles |
| Compile error about VMEM, or blocks that will not grow | Double-buffered blocks exceed the scoped VMEM limit | Tile another axis, shrink blocks, or raise the limit (vmem_limit_bytes, or --xla_tpu_scoped_vmem_limit_kib per generation) |
| The kernel fits but is slower than the compiled reference | A grid order that re-reads the large operand; blocks too small for the MXU | Put the large operand on the outer axis; raise the inner block; sweep on the TPU |
ValueError: Missing argument type annotation at registration |
A parameter without an annotation, or string annotations from from __future__ import annotations |
Annotate tensors jax.Array, plain values with their type; no future import in kernel modules |
ValueError about a namespace |
Op name without ::, or with two |
"namespace::name" |
| A new compile on every call | A static argument (any non-tensor parameter) that changes value, or changing shapes | Keep static arguments fixed; bucket shapes (chapter 7) |
torch.compile fails around a cached op |
The lookup returns the CustomOpDef object |
Return the op name, look it up on torch.ops, mark the lookup assume_constant_result |
Error with mark_dynamic inputs |
Bounded dynamic shapes are not supported with custom kernels | Static shapes or buckets |
| Reading a donated input gives garbage | donate_argnums left it invalid |
Do not reuse donated tensors; copy back if needed |
| Odd TPU behaviour after running the verifier in the training process | VerificationMode.FULL initialized JAX's backends, including the TPU |
STATIC in the TorchTPU process; FULL in a separate process with JAX_PLATFORMS=cpu |
| Gradients missing or wrong in training | No backward registered, or a backward never compared with autograd | register_autograd with a backward kernel; compare gradients with the reference's |
Verifying the result¶
A custom kernel worked when all four of these hold, and the companion code checks the first two on a CPU:
python code/ch12_pallas/run.py --cpu-smoke # ends "cpu-smoke: OK"
pytest tests/ch12 -q
- The plan is sound. The planner reports aligned blocks, a grid that covers every row and column, a double-buffered VMEM footprint under the limit you set, and an intensity you can compare with your chip's ridge.
- Parity in the interpreter. In
pltpu.InterpretParams()the kernel matches the PyTorch reference at the dtype's tolerance (here \(4.8 \times 10^{-6}\) in float32 and \(7.8 \times 10^{-3}\) in bf16) for every grid order and tiling you might use, with no NaN anywhere in the output. If you registered a backward, gradients match the reference's too. - Parity on the TPU.
verify(op, args, mode=STATIC)passes, and the kernel's output in eager mode and insidetorch.compile(backend="tpu", dynamic=False)matches the reference at bf16 tolerance. - The trace and the stopwatch agree. The compiled kernel's mean step time, measured the FLUX way, is lower than the compiled reference's; the XProf trace shows the custom-call op where the reference's fusions and matmuls were; and the step that contains the op got faster by roughly what the op lost. If the kernel is faster in isolation and the step is not, the op was not the bottleneck.
Worked problems¶
Problem 1. For the companion kernel with 2048 rows, hidden 2048, intermediate 8192 in bf16, block_rows=256 and block_inter=1024, compute the double-buffered VMEM footprint with this chapter's formula. Does it fit a 64 MiB scoped limit?
Answer
Blocks in bf16 (tile (16, 128), all dims already aligned except the norm weight): x and residual \(2 \times 256 \times 2048 \times 2 = 2\) MiB; norm weight padded to \(16 \times 2048 \times 2 = 64\) KiB; w_gate and w_up slices \(2 \times 2048 \times 1024 \times 2 = 8\) MiB; output \(256 \times 1024 \times 2 = 0.5\) MiB. Sum 10.5625 MiB, doubled for the pipeline: 21.125 MiB. Float32 temporaries: h \(256 \times 2048 \times 4 = 2\) MiB, g and u \(2 \times 256 \times 1024 \times 4 = 2\) MiB. Total 25.125 MiB, which fits. Check: tiles.plan_tiles(2048, 2048, 8192, block_rows=256, block_inter=1024).vmem_mib returns 25.125.
Problem 2. Rewrite the four index maps of the companion kernel for grid_order="inter_outer", where the grid is (inter // bi, rows // br) and the lambdas receive (j, i). Which dimension_semantics apply?
Answer
Only the argument order changes; each map still returns block indices in the array's own dimension order. x, residual: lambda j, i: (i, 0). Norm weight: lambda j, i: (0, 0). w_gate, w_up: lambda j, i: (0, j). Output: lambda j, i: (i, j). Both axes stay "parallel": every output block depends on one (i, j) and nothing accumulates across steps. Writing (j, 0) for x by mistake would read row tile j: wrong rows, an out-of-bounds read when there are more inter tiles than row tiles, and exactly the bug class the strict interpreter and a reference comparison catch.
Problem 3. A colleague's kernel test on a laptop reports, in pltpu.InterpretParams(): "NaN in 8192 elements (16 rows)". The shapes were 400 rows, hidden 512, intermediate 512, block_rows=32, no intermediate tiling. Name the bug and the fix, and say what the same kernel would have returned on a TPU.
Answer
\(400 / 32 = 12.5\): the grid rows // block_rows has 12 steps and covers 384 rows, so the last 16 rows (\(16 \times 512 = 8192\) elements) are never computed. The interpreter fills unwritten memory with NaN; on a TPU those rows hold whatever the output buffer held, values that may look plausible. Fix: a divisibility check in the wrapper that raises (as the companion code's does), and a block size that divides the row count (16 or 80 rows; 80 is a multiple of 16 and divides 400), or pad the rows to a multiple of 32 and slice the result.
Problem 4. For the 4096 x 4096 x 14336 bf16 MLP, compare three plans by HBM reads and intensity: (a) rows_outer, blocks (256, 1024); (b) inter_outer, blocks (256, 1024); (c) rows_outer, blocks (1024, 256). Which would you try first on a v7x, and what would you measure to decide?
Answer
x and residual together are \(2 \times 4096 \times 4096 \times 2\) B \(= 64\) MiB; the two weight matrices \(2 \times 4096 \times 14336 \times 2\) B \(= 224\) MiB; the output write 112 MiB; FLOPs \(4 \times 4096 \times 4096 \times 14336\). (a) weights re-read for each of 16 row tiles: \(64 + 16 \times 224 = 3{,}648\) MiB, 244 FLOPs per byte, below v7x's ridge of 313. (b) weights once, x 14 times: \(224 + 14 \times 64 = 1{,}120\) MiB, 745 FLOPs per byte. (c) weights re-read for 4 row tiles: \(64 + 4 \times 224 = 960\) MiB, 856 FLOPs per byte, at 59.25 MiB of VMEM. (b) and (c) are above the ridge; (c) reads the least but has the narrowest weight slices (256 columns) and the largest footprint, near the 64 MiB limit. Try (b) and (c), both after checking parity, and decide by the compiled step time measured the FLUX way and by the trace; the model ignores VMEM bandwidth and the per-j recomputation of the normalization, which grows with the number of inter tiles (14 in (b), 56 in (c)).
Problem 5. Each registration or call below fails or misbehaves. Say why, from the jax_op rules. (a) jax_op("fused_swiglu", fn). (b) def fn(x: jax.Array, block): ... registered with a namespaced name. (c) A kernel function with scale: float, called as op(x, step_lr) where step_lr changes every step. (d) The op is called inside a torch.compile region whose input was marked with torch._dynamo.mark_dynamic(x, 0, min=16, max=512).
Answer
(a) ValueError: the name has no namespace; it needs exactly one ::, such as "mylib::fused_swiglu". (b) ValueError: Missing argument type annotation: every parameter must be annotated; annotate block: int, which also makes it a static argument. (c) It works but recompiles: a float parameter is static, part of the cache key, so each new value traces, exports and compiles a new kernel, the chapter 7 recompile signature. Pass a value that changes as a tensor argument (annotated jax.Array), which is data rather than part of the cache key. (d) Bounded dynamic shapes are not supported with custom kernels, and the default fake kernel raises when it sees a symbolic dimension. Keep the kernel's inputs static, with buckets if the length varies.
Problem 6. Design and write a fused residual add + RMSNorm kernel with two outputs: the new residual stream h = x + residual and the normalized y = rmsnorm(h) * weight, both (rows, hidden). Give the grid, the BlockSpecs, the return annotation jax_op needs, and a test plan; then implement it and check it in the TPU interpreter.
Answer
Grid (rows // block_rows,); inputs x and residual with BlockSpec((br, hidden), lambda i: (i, 0)), weight as (1, hidden) with lambda i: (0, 0); two outputs, out_shape=(sds, sds) with sds = jax.ShapeDtypeStruct((rows, hidden), x.dtype) and out_specs=(row_tile, row_tile); dimension_semantics=("parallel",). The body computes h in float32, writes it to h_ref, normalizes and writes y_ref. Annotate the wrapper -> tuple[jax.Array, jax.Array] so the registered op has two tensor outputs. Each row tile reads x and residual once and writes h and y once; unfused, h would be written, read back to normalize, and y written. Test plan: a divisibility guard; the strict interpreter against a PyTorch reference in float32 and bf16 with no NaN in either output; a row count that is not a multiple of the block to see the guard fire; then on a TPU, verify(..., mode=STATIC) and eager and compiled parity. The solution is code/solutions/ch12/residual_rmsnorm.py; its smoke run reports max errors of 0 for h and \(4.8 \times 10^{-7}\) for y in float32, and tests/ch12 checks it in both dtypes.
Quick questions¶
- Name three conditions from chapters 11 and 12 that an op must meet before a custom kernel is justified, and the cheaper options to try first.
- In what order does Pallas run the steps of a grid
(i, j)on a TPU, and how does that differ from a CUDA grid? - What does an index map return, and in what units?
- What happens to an input block whose index is the same in two consecutive steps, and how does that make the grid order a performance decision?
- State the TPU rule for a block's last two dimensions, and why a norm weight is given shape
(1, hidden). - What does
jax_opdo at trace time, and what does it not do at run time? - How does
jax_opdecide which arguments are static, and what does a changing static argument cost? - Give two differences between
interpret=Trueandpltpu.InterpretParams(), and one class of bug neither catches. - Why must
verifyrun inSTATICmode inside a process that owns the TPU through TorchTPU? - Which comparison decides whether a kernel is kept: kernel against eager, or kernel against the compiled reference? Why?
Key takeaways¶
- A custom kernel is the last step of the playbook, for an op that still tops a compiled, copy-free trace. Try a built-in op (
splash_sdpa,ragged_dot), then Tokamax, and estimate the bytes or FLOPs a kernel would remove before writing one. - A Pallas TPU kernel is a body on refs, a grid that runs sequentially in lexicographic order, and one BlockSpec per operand whose index map picks the block in VMEM at each step. Blocks are double-buffered, repeated blocks are not re-copied, and block shapes must be (8, 128)-aligned or span the array.
torch.tpu.pallas.jax_op(name, fn)readsjax.Arrayannotations to build the op schema, treats every other annotated parameter as static, traces and exports the kernel once per signature, and runs it ontorch.TensorTPU buffers with no JAX at run time, in eager mode and undertorch.compile. Training needs a registered backward.- Plan before running: double-buffered VMEM under the scoped limit, a grid that covers the array, and HBM reads for the grid order. Put the large operand on the outer axis; for a 4096 x 14336 MLP that is the difference between 3,648 and 1,120 MiB of reads.
- Prove correctness on a laptop with
pltpu.InterpretParams()against a PyTorch reference: it exposes unwritten output as NaN and out-of-bounds reads as errors. A wrong index map that reads the wrong block raises nothing; only the reference comparison finds it. Alignment and VMEM need the planner and the verifier. - Keep a kernel only when it matches the reference on the TPU, beats the compiled reference measured the FLUX way, and the trace shows where the time went. Tune its blocks on the target generation.
- Part IV takes the profiled, optimized and, where needed, hand-tiled model from one chip to many.
References¶
- TorchTPU custom kernels: reasons for custom kernels, Tokamax, Pallas and Helion, the
jax_opintegration steps - TorchTPU API Reference and TorchTPU Public APIs:
torch.tpu.pallas.jax_op,torch.tpu.pallas.verifier,torch.tpu.ops.splash_sdpa,ragged_dot pallas.pyin the TorchTPU repository: thejax_opsignature, static argument inference, export and fingerprinting, the deprecatedcustom_jax_kernel- Pallas kernel verification:
verifytargets, checks and modes splash_attention.pyandrowwise_scaled_grouped_mm_kernel.py:splash_sdpadefaults; a kernel with an"arbitrary"axis and a VMEM accumulator- TorchTPU repository: the scaled-matmul kernel generators and Kiln (
csrc/internal/mosaic/kiln/) - FLUX optimization: Splash attention through
jax_op,register_autograd, block-size results - Authoring Custom Pallas Kernels for PyTorch on Google Cloud TPUs: masking and fusion barriers, trace-time export, caching ops under
torch.compile - Guide to optimizing LLMs on TorchTPU: scoped VMEM limit, Splash block defaults; the TorchTitan TPU kernels include the fused cross-entropy
- Dynamic shapes: bounded dynamic shapes not supported with
jax_opkernels - TorchTPU distributed support:
mesh, partition specs andget_pallas_mesh - How TorchTPU works and Introduction to TorchTPU: StableHLO and Mosaic, the custom-kernel routes
- TorchTPU Performance: Execution Modes, XProf and Pallas Kernels: the fused RMSNorm + SwiGLU kernel, the tile planner, the verifier modes
- Sample code: TorchTPU execution modes, XProf and Pallas (sample_01)
- How to Think About TPUs, All About Rooflines and How to Profile TPU Programs
- Pallas and Pallas TPU details: grid order, skipped transfers, block shape rules,
dimension_semantics,pltpu.InterpretParams() - Companion code for this chapter: tested with jax 0.12.1; the Problem 6 solution is in
code/solutions/ch12


![An animation in eleven frames. The first frame shows a 3 by 3 grid with x cut into three row tiles x[0] to x[2], w_gate, w_up cut into three column tiles W[0] to W[2], and an empty 3 by 3 out grid in a dashed HBM region, and a dashed VMEM region with empty slots. Frames 2 to 10 walk the grid in rows_outer order, (0, 0), (0, 1), (0, 2), (1, 0) and so on. In each frame the blocks the step reads are blue in HBM, the out tiles written so far are green, and the VMEM region shows three rows, x, W and out, each with an in-use slot and a slot for the copy running meanwhile: for example at step (0, 1) the x slot says x[0] in use and x[0] copy skipped, the W slot says W[1] in use and W[2] copying, and the out slot says computing (0, 1) and writing (0, 0) back. A counter at the bottom reports HBM to VMEM block copies so far, ending at x 3 and W 9. The last frame compares orders: rows_outer, grid (i, j), x 3 copies and W 9 copies, x[i] stays while j runs; inter_outer, grid (j, i), x 9 copies and W 3 copies, W[j] stays while i runs. For a 4096 x 4096 x 14336 bf16 MLP with blocks (256, 1024), 16 row tiles by 14 inter tiles: rows_outer reads 3,648 MiB from HBM at 244 FLOPs per byte; inter_outer reads 1,120 MiB at 745 FLOPs per byte. Ridge points v6e 560 and v7x 313 FLOPs per byte.](../../../assets/ch12/vmem-walk.gif)

