Skip to content

Write a Pallas kernel

Use this guide when a profile shows one memory-bound op dominating the step, no existing kernel covers it, and you want a custom TPU kernel callable from PyTorch. You write the kernel in JAX Pallas, register it as a PyTorch op with torch.tpu.pallas.jax_op, prove it matches a PyTorch reference in the interpreter on a CPU, plan its blocks, and only then measure it on a TPU. Chapter 12 explains the programming model, what jax_op does at trace and run time, and how block sizes and grid order set HBM traffic.

Prerequisites

  • An XProf trace that names the op (Capture and read an XProf trace), and the compiled reference's step time to beat.
  • A reference implementation of the op in plain PyTorch.
  • jax installed next to TorchTPU on the TPU VM. On a laptop, pip install -r requirements-optional.txt (in this book's repository) installs jax[cpu] for the interpreter.
  • Optional: this book's code/ch12_pallas/ (source), a fused residual RMSNorm and SwiGLU kernel with a reference, a tile planner and a runner.

Steps

1. Check for an existing kernel first

In this order: torch.tpu.ops.splash_sdpa for attention (a replacement for F.scaled_dot_product_attention on (B, H, S, D) tensors with a Pallas backward); Tokamax for MoE grouped matmuls, gathers and scatters, attention variants and TopK (TorchTPU's API reference lists torch.tpu.ops.ragged_dot); TorchTitan's TPU kernels (fused linear cross-entropy, Splash attention). For example, 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)

is_causal defaults to True, which is wrong for bidirectional attention.

Check: none of these covers your op. Otherwise use it and skip the rest of this guide.

2. Write the kernel and its JAX wrapper

A Pallas kernel takes refs (x_ref[...] reads a block, o_ref[...] = v writes one); pl.pallas_call wraps it in a JAX function with the output shape. TorchTPU's custom-kernel guide's minimal example:

import jax
from jax.experimental import pallas as pl
import torch

def add_vectors_pallas_kernel(x_ref, y_ref, o_ref):
  x, y = x_ref[...], y_ref[...]
  o_ref[...] = x + y

def add_vectors_jax(x: jax.Array, y: jax.Array) -> jax.Array:
  return pl.pallas_call(
      add_vectors_pallas_kernel,
      out_shape=jax.ShapeDtypeStruct(x.shape, x.dtype),
  )(x, y)

For a real op add a grid, one pl.BlockSpec(block_shape, index_map) per input and output, and pltpu.CompilerParams(dimension_semantics=..., vmem_limit_bytes=...), as chapter 12's fused kernel does. Two rules from the JAX Pallas TPU guide: the last two dimensions of every block are divisible by 8 and 128, or equal to the array's; an axis is "parallel" unless the output block does not change along it. Guard divisibility in the wrapper, because rows // block_rows silently drops a remainder.

Check: every parameter is annotated (jax.Array for tensors, plain types for the rest) and the return is annotated jax.Array or a tuple of them.

3. Register it as a PyTorch op

add_vectors_fn = torch.tpu.pallas.jax_op(
    "pallas::add_vectors",
    add_vectors_jax,
)

x = torch.tensor([1.0, 2.0, 3.0], device="tpu")
y = torch.tensor([4.0, 5.0, 6.0], device="tpu")
z = add_vectors_fn(x, y)

The 0.2.0 signature is jax_op(name, fn=None, /, *, donate_argnums=None, mesh=None, input_partition_specs=None, output_partition_specs=None). The name needs a namespace and exactly one ::. Every non-tensor parameter becomes a static argument: a new value traces and exports a new kernel. Do not put from __future__ import annotations in a kernel module; jax_op reads the annotations with inspect.signature(fn, eval_str=True). The op works in eager mode and inside torch.compile(..., backend="tpu", dynamic=False). For training, register a backward with op.register_autograd(backward, setup_context=setup_context).

Check: registration does not raise, and z holds [5., 7., 9.].

4. Prove correctness in the interpreter, on a CPU

Run the kernel body in Pallas's interpreter against the PyTorch reference. Prefer interpret=pltpu.InterpretParams() to the generic interpret=True: it fills never-written memory with NaN and raises on an out-of-bounds block read, where interpret=True clamps the read silently. Test several grid sizes and every grid order you might use.

For the companion kernel:

pip install -r requirements-optional.txt     # jax[cpu]
python code/ch12_pallas/run.py --cpu-smoke   # ends "cpu-smoke: OK"

Check: the kernel matches the reference at the dtype's tolerance with no NaN in the output. The companion's kernel differs by \(4.8 \times 10^{-6}\) in float32 and \(7.8 \times 10^{-3}\) in bf16 (one bf16 rounding step), against tolerances of \(10^{-4}\) and \(2 \times 10^{-2}\). Its broken variants show what each check catches: an index map that ignores the row index gives wrong rows with no error and no NaN, so only the reference comparison finds it.

5. Plan block sizes before the first TPU run

Every BlockSpec is double-buffered, so VMEM per grid step is twice the padded size of every block, plus the float32 temporaries. Keep it under the scoped VMEM limit: TorchTitan's recipes set LIBTPU_INIT_ARGS="--xla_tpu_scoped_vmem_limit_kib=65536" (64 MiB) on v6e, and a kernel can set its own with vmem_limit_bytes. Put the larger operand on the outer grid axis so it is read from HBM once. tiles.plan_tiles(rows, hidden, inter, block_rows=..., block_inter=..., grid_order=...) in the companion does this arithmetic for its kernel.

Check: the plan reports aligned blocks, a grid that covers every row and column, a VMEM footprint under the limit, and an arithmetic intensity above your chip's ridge (about 560 FLOPs per byte on v6e, 313 on v7x). For a 4096 x 4096 x 14336 bf16 MLP with 256-row and 1024-column blocks, inter_outer reads 1,120 MiB at 745 FLOPs per byte; rows_outer reads 3,648 MiB at 244.

6. Verify and measure on the TPU

python code/ch12_pallas/run.py
python code/ch12_pallas/run.py --profile-dir /tmp/ch12_traces
xprof --logdir=/tmp/ch12_traces --port=6006

The runner registers the kernel, runs torch.tpu.pallas.verifier.verify(op, args, mode=verifier.VerificationMode.STATIC) and raises on errors, checks eager and compiled outputs against the CPU reference at bf16 tolerance, then times the kernel against the compiled reference: 3 warm-up calls, 10 timed calls back to back, one synchronize, profiler off. Use STATIC in a process that owns the TPU; VerificationMode.FULL initializes JAX's backends, so run it in its own process with JAX_PLATFORMS=cpu.

Check: the compiled kernel beats the compiled reference (not eager), the trace shows the kernel's custom call where the reference's fusions were, and the step that contains the op got faster by about what the op lost. If not, do not keep the kernel. Sweep a few block sizes: the FLUX case study's Splash attention was about 10% slower than SDPA with its default 512-token blocks and won only with 2048-token blocks in bf16.

Troubleshooting

Symptom Cause Fix
Rows or tiles of the output wrong, no error, no NaN An index map that ignores a grid index Compare with a reference over the whole output; test several grid sizes
NaN in the interpreter; plausible garbage on the TPU Output blocks never written (an output map that collapses an axis, or a dropped remainder) Guard divisibility; test with pltpu.InterpretParams()
Out-of-bounds block index in the TPU interpreter An index map that runs past the array Fix the map
Lowering or verifier error on block shape Last two block dims not multiples of 8 and 128 and not the full dims Align blocks; give 1D operands a (1, n) shape
Compile error about VMEM Double-buffered blocks exceed the scoped limit Tile another axis, shrink blocks, or raise vmem_limit_bytes
Kernel fits but is slower than the compiled reference Grid order re-reads the large operand, or blocks too small for the MXU Large operand on the outer axis; larger inner block; sweep on the TPU
ValueError: Missing argument type annotation Unannotated parameter, or from __future__ import annotations Annotate every parameter; no future import
ValueError about a namespace Op name without ::, or with two "namespace::name"
A new compile on every call A static (non-tensor) argument changes value, or shapes change Keep static arguments fixed; bucket shapes
Error with mark_dynamic inputs Bounded dynamic shapes are not supported with jax_op kernels Static shapes or buckets
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
Odd TPU behaviour after running the verifier VerificationMode.FULL initialized JAX's backends STATIC in the TorchTPU process
Gradients missing in training No backward registered register_autograd; compare gradients with the reference's

References