Pallas kernels

JAX's kernel language for a PyTorch and CUDA reader: the grid and BlockSpecs, eleven kernels on the running example (row kernels, LayerNorm and flash attention with their backwards, hand-written pipelines, paged decode by scalar prefetch), testing without a TPU, production kernels and block sizes. Child of Topic: jax-and-tpu. Run on an Apple M1 Pro CPU in interpret mode and lowered for TPU and GPU without one; chip speeds are Google's published figures, labelled. Data as of October 2026. Reading: 37 min, plus 13 in closed details.

The idea in one screen

Pallas is JAX's kernel language: you write one Python function that works on tiles in VMEM, the TPU core's fast on-chip memory, and a grid (a loop) plus one BlockSpec per array decide which tile of each array is copied in at every step, with the copies overlapped behind the compute. You write one only when the win comes from doing less than the compiler (XLA) can derive: not storing an intermediate, choosing tiles from data, or skipping known-zero work.

Fig. 1 follows the bias + GELU kernel of section 3 on the running example's MLP pre-activation x [4,096 × 512]: grid=(8,), one 512-row band per step. Section 2 steps through this and nine other grids.

  1. The arrays stay in HBM. x and o are cut by their BlockSpec, pl.BlockSpec((512, 512), lambda i: (i, 0)), into 8 blocks of 512 rows; the bias b [1 × 512] is one block. HBM is the chip's large, slow memory; nothing is computed there.
  2. Step 0: the BlockSpecs copy block 0 of x, and the bias, into VMEM. Before each step Pallas evaluates every index map and issues a DMA for each block whose index changed. An index map returns block coordinates, so (i, 0) at step 0 means rows 0 to 511.
  3. The body runs on the tile. The kernel reads x_ref[...] and b_ref[...] from VMEM and writes o_ref[...] there; it never touches HBM. On a TPU core the 8 steps run one after another; on a GPU they would be 8 parallel programs.
  4. Double buffering: the next block is on its way while this one computes. At step 2, x block 2 is being computed, x block 3 is already being copied into the second slot, and o block 1 is written back to HBM. x and o move band by band, so the copies hide behind the compute when the compute is the longer of the two (section 6).
  5. The bias is copied once. The bias's index map always returns block (0, 0), so it is copied once and given a single buffer: Mosaic marks it #tpu.pipeline_mode<synchronous> (section 3).
  6. After 8 steps: x 8 copies in, b 1, o 8 write-backs, counted from the kernel's own index maps by src/runs/pk_grid.py. Each element of x and o crossed between HBM and VMEM exactly once.

You need: jax.jit and jax.custom_vjp (JAX core, section 6 for custom rules); what VMEM, HBM and the MXU are and how big they are per generation (TPU programming and performance); the five ideas of Pallas, its tiled matmul and the (8, 128) block rule, from the root's TPU and Pallas lab. The PyTorch counterpart is a Triton kernel (Triton and Gluon); CUDA kernel concepts are on Writing kernels.

Ref
a mutable view of one tile in fast memory; the kernel reads x_ref[...] and writes o_ref[...] = ....
Grid
the loop nest the kernel body runs in; sequential on one TPU core, parallel programs on a GPU.
BlockSpec
for one array: the tile shape and an index map from grid indices to the tile's block index.
VMEM, SMEM, HBM
the core's vector memory (tiles), its small scalar memory (indices), and the chip's large slow memory (whole arrays).
Mosaic
the compiler that turns a Pallas kernel into TPU code; on GPUs Pallas lowers to Triton or Mosaic GPU.
Dimension semantics
"parallel" or "arbitrary" per grid axis: whether the axis may be split between cores.
Scalar prefetch
small integer arrays copied to SMEM before the grid starts, so index maps can choose tiles from data.
Interpret mode
running the kernel as ordinary JAX on a CPU (interpret=True), or under the TPU interpreter, which simulates copies and cores.
The four things to take away
  • Write a kernel only for what XLA cannot derive: an algorithm that changes what is stored (flash attention never writes the T × T scores), data-dependent tiles (paged and ragged attention, mixture-of-experts), or block sparsity. For a matmul, Google's own guide shows the best Pallas kernel only matching XLA (section 1).
  • The grid is a sequential loop on a TPU, so a block that several steps share stays in VMEM and can accumulate (sections 4 and 8). On a GPU the same grid is parallel programs, which is why the GPU kernels split such reductions into a second kernel.
  • Gradients are yours to write: jax.grad of a pallas_call fails; wrap forward and backward kernels in jax.custom_vjp (sections 4 and 5).
  • Interpret mode proves correctness, not speed or legality: test with the TPU interpreter and lower for TPU on your laptop before paying for a chip (section 9).
The eleven kernels on this page and how each was checked (reference)
Kernel (this page)What it teachesChecked againstmax abs. error

Every error is measured here, on the running example (Apple M1 Pro CPU, Pallas interpret mode, jax 0.11.2), against a plain jax.numpy reference; float32 throughout unless the row says bf16. Ten of the eleven ran; the eleventh, the emit_pipeline matmul, was lowered for TPU only (section 6). The three production kernels at the bottom ship with jax.

1. When a kernel wins, and when it cannot

In PyTorch you reach for a Triton or CUDA kernel when the framework's kernels move too much memory. In JAX the compiler, XLA, already writes most kernels and fuses chains of elementwise work into one pass (XLA and compilation, section 4). What a compiler cannot do is change the algorithm. Four kinds of work need one:

  • Store less than the maths suggests. softmax(q kT) v materialises a T × T score matrix in HBM, the chip's large and slow memory; flash attention computes the same result tile by tile and never stores it. For the running example's layer 0 that matrix is 8.4 MB of float32 (32 sequences × 4 heads × 128 × 128), and the plain backward keeps probabilities of the same size; the flash backward keeps one number per row, 66 KB measured here. For a 7B-class model at 8,192 tokens with 32 heads, the scores are 32 × 8,1922 × 2 bytes = 4.3 GB per sequence per layer in bf16 derived.
  • Data-dependent tiles. Serving keeps the KV cache in pages scattered through memory; mixture-of-experts sends a different number of tokens to each expert. The tile a step needs depends on a table that exists only at run time (section 7).
  • Skip work known to be zero. Causal or block-sparse masks empty whole tiles; a kernel skips computing them and even copying them (sections 2 and 5).
  • Overlap communication with compute by hand, for example a matmul that pulls the next shard from a neighbouring chip while multiplying the current one (pltpu.make_async_remote_copy; not run here: it needs several chips).

When not to. Google's Pallas TPU matmul guide measured a plain Pallas matmul against jnp.matmul (XLA) on a TPU v5e: the best block size only reached the compiler, and small blocks were 15 times worse Google, published (the chart).

The same guide's sparse chapter is the counter-example: a block-sparse × dense matmul (16,384 square, blocks of 512) took 8.136 ms against 46.953 ms for the dense XLA reference Google, published, because the kernel never touches the zero blocks. A kernel wins by doing less, not by doing the same thing better than the compiler.

The best Pallas matmul only matches XLA; small blocks lose by 15 times

Share of v5e bf16 peak reached by a square bf16 matmul (N × N × N). Source: docs/pallas/tpu/matmul.ipynb cell outputs at jax-v0.11.2 (the guide states "This notebook was run on a TPU v5e chip"; run date not stated). Utilisation = 2N3 / time / 197 TFLOP/s, as the guide computes it. Blocks are (bm, bk, bn); at 8,192 the guide's best is 91.5% against XLA's 92.3%, and 128-cubed blocks reach 6.1%.
Predict: for which of these would you expect a hand-written Pallas kernel to beat XLA on a TPU by a wide margin?
SituationDo thisPyTorch counterpart
Matmuls, elementwise chains, reductions, normalisationLet XLA fuse it; check the fusion on XLA and compilationtorch.compile and Inductor
Flash, splash, paged or ragged attention; grouped matmuls for MoECall a ready-made kernel (section 10)FlashAttention, FlexAttention, vLLM kernels
A new attention variant, a fused quantised matmul, a collective overlapped by handWrite a Pallas kernelA Triton or CUDA kernel

2. The model: one call, a grid and BlockSpecs

Everything is one call, pl.pallas_call(kernel, out_shape, *, grid, in_specs, out_specs, scratch_shapes, input_output_aliases, compiler_params, interpret, ...) (pallas_call.py:1091 at jax-v0.11.2 read in source), which returns a function you call on arrays inside jax.jit. The bias + GELU kernel of the hero, in full:

pl.pallas_call(bias_gelu_kernel,
    out_shape=jax.ShapeDtypeStruct((4096, 512), x.dtype),
    grid=(8,),                                              # 8 steps of 512 rows
    in_specs=[pl.BlockSpec((512, 512), lambda i: (i, 0)),   # x: block (i, 0) at step i
              pl.BlockSpec((1, 512),   lambda i: (0, 0))],  # b: the same block every step
    out_specs=pl.BlockSpec((512, 512), lambda i: (i, 0)),
    compiler_params=pltpu.CompilerParams(dimension_semantics=("parallel",)))(x, b)
Condensed from src/runs/pk_kernels.py (the bias_gelu section, shown in full in section 3), with the running example's shapes filled in.

The one rule that explains every copy. Before each step Pallas evaluates every index map; it copies an input block only when its block index differs from the one the previous step used, and writes an output block back when its index changes (or at the end). An index map returns block coordinates, not element offsets. So x and o move 8 times and b once. Step any kernel on this page through its grid with the lab (a tool: it opens on the last step and moves only when you do).

Try: Bias + GELU to the last step (x 8 copies, b 1, o 8). Then Flash fwd with "Before: naive index map" against "After: clamped": the same 16 steps and the same 10 computed tiles, but K and V are copied 16 times against 9 (section 5). LayerNorm bwd: dscale and dbias are copied once and written back once, the reason its axis must be "arbitrary" (section 4). Paged decode: the page index jumps around the pool (section 7).
input block in use, copied this stepinput block in use, already in VMEMoutput block in useused earliergrid point donecurrent grid point
How the lab is drawn and where its numbers come from

The index maps are the kernels' own, evaluated in src/runs/pk_grid.py; the body conditions are their pl.when tests. Each operand is drawn to its own scale (the arrays range from 8 × 32 to 16,384 × 128), with its block grid; an operand that is a single tall column of more than 8 blocks is drawn wrapped, its blocks numbered in order; three-dimensional operands are drawn as the two dimensions a block covers (flash: one head; paged: the pool as 40 pages of 16 tokens). Bytes count bf16 for activations and weights and float32 for statistics and fp32 outputs, the dtypes a TPU kernel would use. "Minimum" is every element read or written once. The recorded orders come from pltpu.InterpretParams(grid_point_recorder=...) on the real kernels; with "parallel" axes the interpreter shuffles them on purpose, even on one core, and a copy count in that order is computed here from the recorded order, per core.

The pieces, each against what a PyTorch, Triton or CUDA programmer already knows:

PieceWhat it isTriton or CUDA counterpart
kernel(*refs)Called once per grid step with one ref per input, then per output, then the scratch refs. Reads x_ref[...], writes o_ref[...] = ..., may slice o_ref[pl.ds(start, size), :]; ordinary jnp runs on the tile.The body of a @triton.jit or __global__ function
grid=(n0, n1, ...)The loop nest; pl.program_id(axis) says where you are, pl.num_programs(axis) how far it goes. On a TPU the steps run one after another (lexicographic order); on a GPU they are parallel programs.blockIdx and the launch grid
pl.BlockSpec(block_shape, index_map)Tile shape and block index per step. A None in block_shape squeezes that dimension away inside the kernel. Optional memory_space and pipeline_mode=pl.Buffered(n) (core.py:549).Pointer arithmetic and tl.load; shared-memory indexing by hand
out_shapeA jax.ShapeDtypeStruct (or a tuple) per output. Outputs start uninitialised.torch.empty passed in
scratch_shapesBuffers that live for the whole kernel: pltpu.VMEM(shape, dtype), pltpu.SMEM(...), pltpu.SemaphoreType.DMA((n,)); they carry state across steps (flash attention's running max).__shared__ arrays; registers carried across a loop
Memory spacesVMEM: 16 to 128 MiB per core by generation (jax/_src/tpu_info.py, as the root's TPU lab reads it). SMEM: scalars for indices and lengths. pl.ANY: "Unrestricted memory space (usually HBM)" (core.py:277): nothing is copied for you.Shared memory and registers; global memory
pltpu.CompilerParams(...)dimension_semantics per axis (section 8), vmem_limit_bytes (which "must be used in conjunction with the --xla_tpu_scoped_vmem_limit_kib=N flag", mosaic/core.py:97), and more.num_warps, num_stages
interpret=True: "runs the pallas_call as a jax.jit of a scan over the grid whose body is the kernel lowered as a JAX function ... the only way to run Pallas kernels on CPU" (pallas_call.py:1143). pltpu.InterpretParams(...): the TPU interpreter (section 9).TRITON_INTERPRET=1

Transformations. A pallas_call sits inside jax.jit like any primitive. jax.vmap of it adds a leading grid axis (docs/pallas/design/design.md:542): the softmax kernel vmapped over 4 score matrices of 1,024 rows became one call with grid (4, 2) and matched to 1.5e-8 measured here (jax's own GPU LayerNorm is written this way, one row per program, then vmapped). jax.grad needs a custom_vjp (section 4). Inside shard_map a kernel sees each device's shard; Sharding and scale owns that.

3. Row kernels: elementwise, softmax, cross-entropy

The simplest useful kernels cut an array into bands of rows and process each band alone: a one-dimensional grid, one BlockSpec per operand, the axis "parallel". Three of them, each on a real tensor of the running example, code exactly as it ran (src/runs/pk_kernels.py):


Bias + GELU on layer 0's MLP pre-activation (layer 0 MLP pre-activation x W1 [4,096 x 512] and bias b1 [512]) matches jax.nn.gelu(x + b, approximate=False) to 7.5e-8 and the model's own hidden activations to the same measured here. The bias is the trivial window of the hero: the TPU lowering marks it #tpu.pipeline_mode<synchronous>, single-buffered ("Force single-buffering pipelining for trivial windowing in VMEM", mosaic/lowering.py:1220), a trivial window being a block equal to the whole array with an index map of zeros. jax.lax.erf lowers to Mosaic's math.erf, so the exact GELU the model uses costs nothing extra; the tanh approximation (JAX's default) would differ by 1.9e-4 here, a porting trap.

Fused softmax on the scaled, causally masked attention scores of all 128 heads (layer 0 attention scores, scaled and causally masked, all 128 heads [16,384 x 128]): whole rows fit in a 512 × 128 block, so the max, the exponentials and the sum stay in VMEM and each element is read once and written once. Error 6.0e-8, row sums within 2.4e-7 of 1. 49.6% of the entries are -inf and come out as exact zeros, which works only because every row keeps its diagonal: a row with every entry masked computes -inf - (-inf) and returns NaN (tried here: that row came out all NaN, yes, the other 511 rows untouched; decoding at length 0 is the usual way to hit it). That is why the flash and paged kernels skip empty tiles with pl.when.

Fused cross-entropy on the whole model's logits at initialisation (logits of the whole model at initialisation, batch 0 [4,096 x 65], with the targets): each row's loss is its logsumexp minus the target's logit, picked with broadcasted_iota and a compare instead of a gather; the softmax is never stored. Mean 4.21168, identical to the model's loss_fn (difference 0), close to ln 65 = 4.174 as an untrained model should be. The 512 × 65 block is legal only because 65 is the whole row (the root lab showed the (8, 128) rule rejecting a 100-row block). Legal is not free: VMEM is laid out in rows of 128 lanes, so each 65-wide row occupies 128 lanes and 49% of the vector work and memory is padding derived. The production flash attention kernel pays the same on purpose: it stores its running max and sum 128 lanes wide, one value repeated (flash_attention.py:675; why, in the depth block at the end).

Precision: bf16 inputs, and an output dtype that rounds the accumulator

With bf16 inputs the softmax kernel (which upcasts to float32 inside) is off the float32 answer by 2.0e-3; XLA's jax.nn.softmax on the same bf16 input by 3.6e-3 measured here: inside a kernel the precision of the arithmetic is yours to choose.

The old version of this page showed a matmul kernel with out_shape in the input dtype and x_ref[...] @ y_ref[...]. It is correct, but with bf16 inputs the result is stored in bf16: off the float32 answer by 9.0e-4 against 7.1e-4 with a float32 output (preferred_element_type=jnp.float32), measured here. Accumulate and, where the next op allows, store in float32.

4. LayerNorm, forward and backward, joined by custom_vjp

The problem. A pallas_call is opaque to reverse-mode autodiff. Measured here: jax.grad through the softmax kernel fails with ValueError: Linearization failed to produce known values for all output primals. This is typically caused by attempting to differentiate a function uses an operation that does not support reverse-mode autodiff., and through the flash kernel (scratch buffers, pl.when) with a bare AssertionError; forward mode (jax.jvp) of the softmax kernel works. The Pallas design note explains why: transposing a kernel turns parallel reads into overlapping writes ("slow when done atomically"), and it names jax.custom_vjp "a viable escape hatch" (docs/pallas/design/design.md:553). So every training kernel is a pair, forward and backward, joined by jax.custom_vjp (JAX core, section 6); PyTorch's counterpart is a torch.autograd.Function.

The code: forward kernel, backward kernel and the custom_vjp that joins them, as they ran

src/runs/pk_kernels.py, the layer_norm section, as it ran.

How it works. The forward normalises a band of 256 rows and also writes two numbers per row, the mean and 1/√(var + ε). The backward recomputes x̂ = (x − μ) · rstd from them instead of storing x̂, so the saved state is x plus 2,130,432 bytes in all for this input, of which only 32 KB are statistics. The backward has two kinds of output: dx is per row, like the forward; dscale and dbias are sums over all 4,096 rows. Fig. 2 shows what the second kind does to the grid (step "LayerNorm bwd" in section 2's lab replays it block by block):

  1. 16 steps, one band of 256 rows each. x and dy (with the forward's mean and rstd) are copied in band by band, and each step writes its dx band back: 16 copies of each, like any row kernel.
  2. dscale and dbias: one block for the whole grid. Their BlockSpec maps every step to the same (1, 128) block, which stays in VMEM: the kernel zeroes it at step 0 (pl.when(pl.program_id(0) == 0)) and adds each band's contribution at every step.
  3. Written back once, at the end. Pallas writes an output block back when its index changes or the grid ends, so dscale and dbias are written back 1 time each, against 16 for dx. The steps must run in order on one core: the axis is "arbitrary".
  4. Mark the backward's row axis "parallel". A megacore chip (v4, v5p: two TensorCores as one device, sharing HBM, each with its own VMEM) may then split the rows between its two cores, each accumulating into its own copy of the shared block. Only the core that runs step 0 zeroes its copy, and both copies are written back to the same block (which band goes to which core is drawn illustratively).
  5. The accumulation forces "arbitrary", and the plain interpreter will not tell you. The plain interpreter ignores dimension semantics and returns the right answer (error 3.1e-5 on values up to 176, rounding). The TPU interpreter with two simulated cores, three seeds: measured here. With "arbitrary" the same two-core run is right again (3.1e-5).

Evidence. On layer 0's input with the trained LayerNorm (scale between 0.935 and 1.037 after the 500-step run), the forward matches the model's layer_norm to 2.4e-7, and the gradients agree with jax.vjp of it to a relative 1.1e-7 (dx), 1.7e-7 (dscale) and 1.0e-7 (dbias) measured here: float32 rounding.

On a GPU the decomposition changes. GPU programs run at the same time, so they cannot accumulate into one block. The Triton-style LayerNorm that ships with jax (deprecated in favour of tokamax, section 10) computes dscale and dbias in a second kernel, layer_norm_backward_kernel_dw_db (ops/gpu/layer_norm.py:192), one program per block of columns looping over all rows with masked loads. Same maths, a different decomposition, forced by the grid semantics.

The running max climbs block by block, and α shrinks what was accumulated before

high score (darker is higher)masked (key after query)not reached yet

The kernel itself, run with the same 32 × 16 blocks, agrees with this float32 replay to 1.2e-7 and with plain attention to 3.0e-7 measured here.

Where the replay's data comes from

src/runs/pk_tiles.py: sequence 0, head 0, layer 1 of the running example, training batch 0, with the weights after the root's 500-step training run (at initialisation attention is nearly uniform and the rescaling barely matters; trained, it does). The replay is float32 NumPy following the kernel line by line. The scores are q kT / √32.

5. Flash attention: the worked kernel, forward with its residual and backward

The root's lab ran the causal flash attention forward. A training kernel needs three more things: the forward must save something for the backward, the backward must exist, and the two must be joined by custom_vjp. All three are below, checked against plain attention and against the two production kernels that ship with jax, on the same tensors (layer 0 q, k, v of all 32 sequences x 4 heads [128 x 128 x 32]; upstream gradient N(0, 1), key 1).

The forward loop walks the key blocks for one query block, keeping three running quantities per row in VMEM scratch and rescaling them whenever a row's maximum grows:

mnew = max(m, rowmax Sj), α = em − mnew, l ← α l + rowsum eSj − mnew, acc ← α acc + eSj − mnew Vj
Sj
the scores of one query block against key block j, q kT / √dh, causally masked
m, l, acc
running row max, running softmax denominator, running numerator: VMEM scratch, kept across the key loop
α
rescales everything accumulated so far when the row max grows; the output is acc / l after the last block, and the saved residual is the logsumexp L = m + log l

The same loop on real numbers: one block of 32 queries (positions 96 to 127) of a trained attention head against the keys in 8 blocks of 16, exactly the arithmetic of flash_fwd_kernel. Predict before you step: if α is left out, will row 100's output be slightly off or badly off?

  1. Key block 0 (keys 0 to 15). Row 100's first tile: its largest score becomes the running max, m = -22.09. Nothing has been accumulated yet, so there is nothing to rescale.
  2. Key blocks 1 to 5: the max climbs at every block. m rises to 14.59. Each time, α = emold − mnew is at most 0.0046, so what was accumulated before shrinks almost to nothing: earlier keys hardly count once a much larger score arrives.
  3. Key block 6: the rescale that keeps both. The max moves only to 15.55, α = 0.38: the old sum is kept at that weight and the new block added. The block straddles the diagonal, so its keys after the query are masked.
  4. Key block 7: masked for row 100. Keys 112 to 127 come after position 100, so nothing changes (α = 1). The output acc / l matches plain attention to 2.4e-7 over the whole block, with 1,600 floats held on chip.

The algorithm's IO argument, with HBM and on-chip memory animated on random input, is on the FlashAttention paper page; the GPU schedules (FlashAttention-2's split across warps, atomics in its backward, Flash-Decoding) are on Writing kernels.

The forward here is the root's kernel plus one output, lse; the output matches the root kernel exactly (difference 0) and the logsumexp matches jax.nn.logsumexp of the scores to 9.5e-7.

Skipping, and not even copying. With causal masking the tiles above the diagonal are all -inf. The kernels skip their arithmetic with pl.when, but a BlockSpec would still copy K and V for them. The forward's K and V index map therefore re-uses the last block the query block needs, min(j, last); an unchanged block index means no copy. The production kernel does exactly this with lax.select (flash_attention.py:626). Fig. 3 plays both maps on the recorded grid (section 2's lab steps them block by block):

  1. One head, a 4 × 4 grid. q, k and v [128 × 32] in blocks of 32; the grid runs query block i (rows) by key block j (columns), the key axis "arbitrary". The 6 tiles above the diagonal are fully masked.
  2. Query block 0. Only tile (0, 0) is on the diagonal: the body runs once and pl.when skips three. The naive map still asks for K and V blocks 1, 2 and 3, so they are copied for nothing (dark grey marks); the clamped map keeps returning block 0, so nothing is copied.
  3. Query block 1. Two tiles run. Clamped, step (1, 0) needs block 0, which is still in VMEM from the row before: no copy at all.
  4. Query block 2. Three tiles run; one wasted copy under the naive map.
  5. Query block 3. All four tiles touch keys at or before their queries, so every step runs and copies.
  6. Same arithmetic, fewer copies. K copies: 16 naive, 9 clamped (and the same for V); the body runs on 10 of 16 tiles either way.

The backward, from the softmax derivative. With P = eS − L recomputed tile by tile from the saved L, and D = rowsum(dO ∘ O) computed once outside the kernels:

dV = PT dO, dP = dO VT, dS = P ∘ (dP − D), dK = dST Q / √dh, dQ = dS K / √dh
D
rowsum(dO ∘ O): the term the softmax Jacobian subtracts; the production kernel calls it di
∘
elementwise product

dK and dV sum over query blocks; dQ sums over key blocks. A grid step may only accumulate into an output block it owns, so the backward is two kernels: the first walks one key block past every query block (grid: head, key block, query block), the second one query block past every key block. The production TPU kernel splits it the same way, _flash_attention_dkv_kernel then _flash_attention_dq_kernel (flash_attention.py:796 and :1146). Both recompute P, the price of not storing it: about one extra QKT matmul per kernel.

The code: the forward kernel, the two backward kernels and the custom_vjp, as they ran

src/runs/pk_kernels.py, as it ran; the custom_vjp that joins them is at the end of the backward.
Kernel, same tensorsoutputdQdKdV

Max abs. error against plain attention (jax.vjp of the model's attention core) in float32: every kernel within 2.4e-6; the largest reference values are 0.93 (output) and 5.29 (dV). The production TPU kernel ran under pltpu.force_tpu_interpret_mode(); the GPU one with interpret=True. measured here

The production TPU kernel does not scale the scores unless you ask

flash_attention(q, k, v, causal=True) has sm_scale: float = 1.0 (flash_attention.py:148), not 1/√dh. Called without it on the running example's tensors, its output differs from the model's attention by 0.198 on values below 1 measured here, and no error is raised: the model just trains differently. The GPU mha has the same default. Pass sm_scale=1/math.sqrt(head_dim), or scale q first.

Block sizes and bf16 inputs for the flash forward

Every block shape tried computes the same answer and lowers for TPU v5e; they differ in how many steps run and how much is skipped:

bqbkgrid steps per headtiles computedmax abs. errorlowers for TPU

With bf16 inputs, as a TPU kernel would get them, the output is off the float32 answer by 2.6e-3, and by 1.8e-3 from float32 attention on the same bf16-rounded inputs: most of that is the bf16 rounding of the output itself.

6. Pipelining: what a BlockSpec does for you, written by hand

The problem. A TensorCore computes only on data in VMEM; the arrays live in HBM. Copy a tile in, compute, copy the result out, one after the other, and the matrix unit idles during every copy. Every BlockSpec kernel on this page is pipelined automatically: while step s computes, Pallas's generated code is already copying the blocks step s+1 needs into a second buffer (double buffering, step 4 of Fig. 1), and writes each output block back once it is final. "The default buffer count is 2 for all inputs and outputs" (the Pallas TPU pipelining guide, docs/pallas/tpu/pipelining.md:140).

The running example's matmul moves more bytes than it computes, so even perfectly overlapped it takes as long as its copies (9.05 µs against 8.96 µs of copies); the 7B-class matmul with 512 × 1,024 × 1,024 blocks computes longer than it copies, and overlap hides almost every copy (73.7 µs against 119.2 serial for the first 12 steps). Overlap can only bring the time down to the longer of the two lanes; block sizes decide which lane that is (section 11).

Overlap hides the copies only when the compute lane is the longer one

Calculated, not measured: every copy at v5e's published 819 GB/s and every block matmul at its 197 TFLOP/s bf16 peak (the figures the Pallas TPU matmul guide uses), bf16 inputs, float32 outputs, a copy issued only for blocks whose index changed. No DMA latency, issue cost or pipeline overhead is modelled, so real times are longer; the shape of the timeline is the point. derived

Written by hand. Put an operand in pl.ANY and Pallas copies nothing; you allocate VMEM slots and DMA semaphores as scratch and issue the copies with pltpu.make_async_copy(src, dst, sem) (mosaic/primitives.py:703), a descriptor with .start() and .wait(). This is the root lab's matmul with A's copies written out, the code a BlockSpec generates for you (code below). It matches jnp.dot exactly in both interpreters (error 0) and lowers to a Mosaic loop with two tpu.enqueue_dma (the prologue and the prefetch) and the waits.

The code with copies by hand, and the Mosaic loop it lowers to
The bug the TPU interpreter exists for

Move the .wait() to after the matmul that uses the slot. In the plain interpreter a DMA completes the moment it starts, so the result is still exact (error 0). On a TPU the matmul would read a half-copied buffer. The TPU interpreter executes DMAs only when the kernel waits on their semaphore (dma_execution_mode="on_wait", the default, interpret/params.py:178) and fills fresh buffers with NaN, so 1,024 of the 4,096 output rows came out NaN measured here. Always test hand-written DMAs under pltpu.InterpretParams().

How many buffers. pipeline_mode=pl.Buffered(n) on a BlockSpec sets the count. The pallas_call lowering accepts one or two only: pl.Buffered(3) runs in interpret mode and fails at TPU lowering with "Only single (1) and double (2) buffering are supported. Got 3." (mosaic/lowering.py:1277). One buffer saves VMEM and gives up the overlap: use it for blocks that never change.

BufferingInterpret modeLowered for TPU v5eVMEM for A and B blocks plus the output

The root lab's matmul with pl.Buffered(n) on both inputs (src/runs/pk_pipeline.py). VMEM is calculated: buffers × block bytes.

Inside a kernel: emit_pipeline. pltpu.emit_pipeline(body, grid, in_specs, out_specs) (mosaic/pipeline.py:2039) builds the same machinery anywhere inside a kernel: for nested pipelines (an outer loop over chips, an inner one over HBM tiles), deeper buffering and lookahead. The page's matmul_emit lowers for TPU v5e (234 lines of Mosaic, against 56 for the hand-written one), but it does not run in either interpreter on a CPU at jax 0.11.2: it asks for the TPU generation to choose a memory tiling and stops with ValueError: Unsupported TPU device kind: cpu. measured here. It is the one kernel on this page that was lowered but not run.

7. Scalar prefetch: tiles chosen by data

The problem. An index map is a traced function of the grid indices, run before each step to decide which block to copy. Serving needs more: each sequence's KV cache lives in fixed-size pages scattered through a shared pool, and which physical page holds tokens 32 to 47 of sequence 3 is in a page table known only at run time (why pages: the PagedAttention paper page). Scalar prefetch solves it: pltpu.PrefetchScalarGridSpec(num_scalar_prefetch=n, ...) (mosaic/core.py:390) copies the first n arguments, small integer arrays, into SMEM before the grid starts and passes them to every index map and to the kernel (as SMEM refs, :407). The BlockSpec still does the copy, so section 6's pipelining still applies. In vLLM's CUDA paged attention the block table is just a kernel argument each thread block reads; in Triton you load the entry and compute the pointer.

The whole trick is the index map, which now also receives the prefetched arrays (from the kernel's code, below):

def page_map(page):
    def f(s, p, table_ref, lens_ref):                            # index maps also receive the prefetched scalars
        last = (lens_ref[s] - 1) // page                         # last page that holds a token
        return (table_ref[s, jnp.minimum(p, last)], 0, 0)        # physical page; clamped, so no copy past the end
    return f
The code: paged decode attention with scalar prefetch, as it ran
src/runs/pk_kernels.py, the paged_decode section: grid (sequence, logical page); the K and V index maps return the table entry for min(page, last page); the kernel masks the tail of the last page and runs the online softmax across pages.

The test. Eight (sequence, head) pairs of the running example decode one token each: query = the q row at position n − 1, keys and values 0 to n − 1, with lengths 37, 128, 64, 90, 1, 17, 113, 70. Their K and V are cut into pages of 16 tokens and scattered over a pool of 40 pages (3 unused) in a shuffled order. Causal attention's row n − 1 sees exactly keys 0 to n − 1, so the kernel's output must equal the model's own attention output at that row: it does, to 3.7e-8, in both interpreters measured here.

The index map also clamps the page index to the sequence's last page, so the steps past the end, which do no work, copy nothing new: 43 K-page copies without the clamp, 37 with it, exactly the 37 pages that hold tokens (step "Paged decode" in section 2's lab).

The page table sends each logical page to a scattered physical page

Rows: the 8 sequences (n = length); columns: logical pages 0 to 7; each cell is the physical page in the pool (a dash: unused slot). Hover or tap a cell to see its page in the pool. Lengths and the shuffle are those of src/runs/pk_run.py (NumPy seed 0).
Stale table entries

Unused table slots must still hold a valid page index. With 9,999 in them and no clamp, the plain interpreter silently clamps the out-of-range block (error 3.7e-8: the step's arithmetic is skipped anyway); the TPU interpreter refuses: Out-of-bounds block index (9999, 0, 0) for input "k_ref" in iteration (0, 3) on device 0 (core 0): reading [(9999, slice(0, 16, 1), slice(0, 32, 1))] but input has shape (40, 16, 32). On a chip that copy would read outside the pool. With −1 in the slots neither interpreter raised measured here, so do not rely on the interpreter for negative indices: fill unused slots with a valid index and clamp in the index map.

What the lowering looks like, and who uses scalar prefetch in production

Lowered for TPU, the table and lengths become memref<8x8xi32, #tpu.memory_space<smem>> and memref<8xi32, ...smem> arguments and the function is tagged scalar_prefetch = 2 : i64; the index maps become transform_ functions that read SMEM with memref.load.

In production (all at jax-v0.11.2, section 10): paged attention passes lengths and page indices this way (paged_attention_kernel.py:640). The megablox grouped matmul for mixture-of-experts prefetches group metadata, which group and which row tile each step works on (gmm.py:530, built by make_group_metadata:79); run here on the running example's MLP rows split into four "experts" of 1000, 0, 2600, 496 rows, one of them empty, it matched per-group matmuls to 2.7e-7. Splash attention precomputes, for every (head, query block, key block), the next key block worth fetching, data_next, and keeps it "in TPU scalar-memory", a "scarse resource" its comment says, shrinking the dtype to int8 or int16 where it can (splash_attention_mask_info.py:32).

8. Dimension semantics, megacore and the order of the grid

Each grid axis is "parallel" (any order is fine, so the axis may be split between cores) or "arbitrary" (must run in order, as an accumulation must). With no dimension_semantics, every axis is arbitrary (mosaic/lowering.py:778). The split matters on megacore chips, v4 and v5p, where two TensorCores appear as one JAX device and share HBM but each has its own VMEM; "Only parallel dimensions can be partitioned over cores" (the Pallas TPU design notes, docs/pallas/tpu/details.rst:180). On TPU7x each core is its own device (the root's TPU lab, from tpu_info.py), and splitting work between them is sharding's job, not the grid's.

The rule: an axis may be "parallel" only if no output block is visited by two different indices along it ("parallel, unless the output window does not vary"). The matmul's K axis, the flash kernels' inner key or query loop, and the LayerNorm backward's row axis (because of dscale) all revisit an output block, so they are "arbitrary"; everything else on this page is "parallel". The root's lab showed a matmul whose K axis was marked parallel going wrong by 0.17 under two simulated cores; section 4 showed the same for an accumulation across rows. Both are invisible to interpret=True.

Predict: the TPU interpreter runs the flash forward (one head, 4 query blocks × 4 key blocks, semantics ("parallel", "parallel", "arbitrary")) on one simulated core. In what order does it visit the query blocks?

9. Testing a kernel without a TPU, and what it cannot tell you

Five rungs, each catching a different class of bug. Every kernel on this page climbed the first four on a laptop:

Tolerances. Compare with numpy.testing.assert_allclose against the jnp reference, with tolerances set by dtype, not by hope. On this page float32 kernels land at a relative 1e-7 (rounding), a long float32 sum such as dscale over 4,096 rows at a few e-5 absolute on values near 176, and bf16 inputs at a few e-3. A kernel 1e-4 off in float32 has a bug.

What interpret mode cannot tell you. It runs the kernel body as ordinary XLA:CPU code inside a loop over the grid, so it knows nothing about the MXU, VMEM capacity, DMA bandwidth or how Mosaic will schedule the code. What transfers to a TPU is correctness, legality of the block shapes, VMEM arithmetic and copy counts; speed has to be measured on the chip, with the profiler, against the XLA version you are trying to beat. The flash kernel took 150 ms in interpret mode against 2.0 ms for XLA's attention on this CPU, a ratio that says nothing about a TPU.

1. jnp referencethe function you want, in plain jax.numpy: the oracle for every test
2. interpret=Trueruns the kernel body as ordinary JAX on CPU: values, shapes, gradients10 of 11 kernels run
3. TPU interpreterinterpret=pltpu.InterpretParams(...): simulated DMAs, cores, races, out-of-bounds blockscaught 3 of 4 planted bugs
4. Lower for TPUjax.export(..., platforms=["tpu"]) on a laptop: Mosaic accepts the tiling or says why not11 of 11 lower
5. On a chipspeed, VMEM limits, the real compiler. Not run here (no TPU)published numbers only

Each rung catches what the one before misses: eight planted bugs

Planted buginterpret=TrueTPU interpreterLowering for TPU

Four bugs planted here (sections 4, 6 and 7), four in the root's lab. interpret=True caught 1 of 8 (the accumulator never zeroed); the TPU interpreter 6 of 8; lowering for TPU caught the one illegal block shape that both interpreters accept. measured here

Interpret-mode timings, to be ignored
KernelXLA, msinterpret mode, msratio

Measured on Apple M1 Pro (CPU), shared machine, 4 threads, low priority, 1-minute load about 53 at the start of the run; median of 3 wall-clock runs after a warm-up (CPU time recorded in out/kernels.json). On a TPU the kernel is compiled by Mosaic and the reference by XLA's TPU backend, and neither runs a loop like this.

10. Reading production kernels

Before writing a kernel, look for one. Two places ship them: jax.experimental.pallas.ops inside jax (TPU: flash, splash, paged and ragged paged attention, the megablox grouped matmul; GPU: Triton-backed ops being deprecated, and Mosaic GPU matmuls), and tokamax, OpenXLA's separate kernel library with one API per op and several implementations chosen per device (0.0.16 on PyPI, uploaded 2026-10-09; its README says it "is still heavily under development"). Three were run here on this page's tensors: jax's TPU flash attention (output 6.0e-8, gradients within 4.8e-7), megablox gmm and the GPU mha (output 8.9e-8).

What to copy into your own kernels, from reading them: keep every block size in one frozen dataclass, forward and backward, so they can be swept; save the logsumexp, not the probabilities; clamp index maps for skipped tiles; precompute masks and metadata on the host and pass them by scalar prefetch; write the reference implementation beside the kernel (both flash kernels ship one: mha_reference); and pass every scale explicitly.

The production kernels one by one: what each is for and what to learn from it
KernelWhat it is forWhat to learn from itHere
ops/tpu/flash_attention.pyFlash attention with causal masking, segment ids and a bias, forward and backwardA BlockSizes dataclass with three forward and seven backward block sizes, all defaulting to 128 with a TODO to choose them by heuristic (:114); custom_vjp (:204); the dK dV and dQ split; clamped K/V index maps; statistics 128 lanes wide; sm_scale=1.0 by defaultran here (section 5)
ops/tpu/splash_attention/Block-sparse attention for structured masks (causal, chunked causal, local, any NumPy mask, and their combinations); what MaxText imports (the root's TPU lab: layers/attention_op.py:29)Masks compiled on the host into MaskInfo: which blocks are empty, full or partial, and the next block to fetch, all by scalar prefetchread
ops/tpu/paged_attention/, ragged_paged_attention/Decode, and mixed prefill and decode batches, over a paged KV cache (serving)Page tables and lengths by scalar prefetch (section 7); a checked-in table of autotuned block sizes per TPU generation (section 11)read
ops/tpu/megablox/Grouped matmul for mixture-of-experts: tokens sorted by expert, one weight matrix per expert (gmm, and tgmm for the weight gradient)Group metadata by scalar prefetch; row tiles that straddle two groups are visited twice and maskedran here (section 7)
ops/tpu/matmul.py, all_gather.py, random/A small blocked matmul; an all-gather written with remote DMAs over ICI; in-kernel PRNG (threefry, philox)Minimal, readable examples of each featureread
ops/gpu/attention.py and the other Triton-backed GPU opsFlash attention, layer and RMS norm, softmax, decode and paged attention for GPUs, through TritonThe same algorithms under GPU constraints: masked loads, parallel programs, a second kernel for reductions. Importing one warns "jax.experimental.pallas.ops.gpu.attention is deprecated. Please use tokamax.dot_product_attention instead. See https://github.com/openxla/tokamax for more details."; six of them are deprecated (ops/gpu/attention.py:32). The Mosaic GPU kernels beside them (*_mgpu.py: Hopper and Blackwell matmuls, ragged dot, collective matmul) are not.ran here mha (section 5)
tokamax 0.0.16One API per op with several implementations chosen per device: dot_product_attention, ragged_dot, layer_norm, gated_linear_unit, linear_softmax_cross_entropy_loss and moreimplementation=None lets it pick, falling back to XLA; tokamax.autotune times every configuration in an op's search space. Its README lists attention as a GPU kernel, but its code also registers a Mosaic TPU attention built on its own copy of splash attention (ops/attention/api.py:66)read (not installed: needs a GPU or TPU to choose a kernel)

11. Choosing block sizes

The cost model. For a matmul tiled (bm, bk, bn), the Pallas TPU guide counts HBM traffic as (m k n / bn + k n m / bm + m n) × bytes per element: A is re-read once per column of blocks, B once per row of blocks (docs/pallas/tpu/matmul.md:341). Its advice: "to be compute bound, make the blocks as big as possible", limited by VMEM and by pipeline bubbles (with few grid steps, the first copy and last write-back are not hidden); and in practice "sweep over a large set of candidate block sizes, profile the kernel, and pick the best one". The root's lab tabulates that traffic for the running example and a 7B-class matmul; the Kernel playground tab adds the VMEM each of this page's kernels needs at each block size, logical and padded to (8, 128) tiles, against each generation's VMEM (flash attention at 128 × 128 blocks needs about seven times its logical bytes once its 32-wide head dimension and its one-number-per-row statistics are padded to 128 lanes).

What production does. Three strategies, from the source:

  • One default for everything: the flash attention kernel's 128 everywhere, with its TODO.
  • A checked-in table: ragged paged attention looks its block sizes up in TUNED_BLOCK_SIZES (tuned_block_sizes.py:37), 668 entries for "TPU v5" and 668 for "TPU v6", keyed by dtypes, heads per block, head dimension, page size, batched tokens and maximum model length, each giving (KV pages per block, queries per block). The two generations share every key but disagree on 237 of them: tuned values do not transfer between chips.
  • Search at run time: tokamax's ops declare a search space and tokamax.autotune measures it, for example ragged_dot's row tiles from 128 to 1,024 ("we found that there is no need on current TPU generations to search for larger tiles for m", ops/ragged_dot/pallas_mosaic_tpu.py:453). Its README warns that "autotuning is fundamentally non-deterministic" and that different configs "can lead to different numerics": serialise the result and reuse it.

The same keys, tuned on v5 and on v6, often pick different blocks

Best (KV pages per block, queries per block), from ragged_paged_attention/tuned_block_sizes.py at jax-v0.11.2 Google, published in source; the slice is q heads per block 8, kv heads per block 2, head_dim 128, max_num_batched_tokens 512, bf16. Rows: page size; columns: maximum model length. How the table was measured is not stated in the file.

12. Pallas against Triton, and against writing nothing

The same Python kernel lowers per platform: on TPU to a tpu_custom_call holding a Mosaic module (an MLIR dialect that libtpu compiles); on cuda and rocm to Triton unless you pass Mosaic GPU's compiler parameters (pallas_call.py:922: with no compiler_params it constructs Triton's). Fig. 4 follows the fused softmax of section 3 down both paths; the code each produced, compiled on this CPU, is under the figure.

  1. One Python kernel, one array. softmax_kernel on the scores s [16,384 × 128] float32. Lowered with jax.export for platforms=["tpu"] it becomes Mosaic; for ["cuda"], Triton.
  2. TPU: 32 blocks of 512 rows, one after another. One core walks the grid in order; before each step the BlockSpec's DMA copies the next block from HBM into VMEM.
  3. The tile is already in VMEM when the body starts. In Mosaic the refs arrive as memref<512x128xf32, #tpu.memory_space<vmem>>: the copy from HBM already happened, decided by the BlockSpec, and the body is vector.load, two vector.multi_reductions and a tpu.vector_store.
  4. GPU: 1,024 programs of 16 rows, launched at once. 16,384 / 16 = 1,024 derived: the Triton block is 16 rows (Triton blocks must be powers of two and small enough for registers), and every program runs at the same time.
  5. Each program computes its own addresses. In Triton the refs arrive as raw pointers (!tt.ptr<f32>), and the lowering builds a 16 × 128 tensor of addresses (tt.make_range, tt.addptr) before tt.load, which is what a Triton programmer writes by hand.
  6. Same maths, two schedules. On the TPU the grid is a loop, so a block that several steps share can stay in VMEM and accumulate (section 4); on the GPU the programs run at once, so a sum across them needs atomics or a second kernel.

On a TPU the BlockSpec has already copied the tile; on a GPU it becomes pointer arithmetic


Both produced by src/runs/pk_run.py with jax.export(..., platforms=["tpu"]) and platforms=["cuda"] under an abstract device (the TPU lowering targets "TPU v5 lite"; the GPU one an "NVIDIA H100 80GB HBM3"). Not compiled: that needs libtpu or CUDA.
Pallas on TPU (Mosaic)Triton on GPU (or Pallas lowered to it)No kernel: XLA
GridA sequential loop; blocks shared by steps stay in VMEMParallel programs; shared results need atomics or a second kernelThe compiler chooses
Memory movementBlockSpecs generate double-buffered DMAs into VMEM; or by hand with async copies and semaphoresPointer arithmetic and tl.load with masks; the compiler pipelines loads (num_stages)Fusion keeps intermediates on chip where it can
Edges and shapesLast two block dims divisible by (8, 128) or equal to the array; narrow arrays padded to 128 lanesPower-of-two blocks; any edge handled by masksAny shape; padding inserted for you
Gradientsjax.custom_vjp around forward and backward kernelstorch.autograd.Function (or custom_vjp from JAX)Automatic
TuningYour sweep, a checked-in table, or tokamax@triton.autotune configsXLA's own heuristics and autotuner
Testing without hardwareTwo interpreters and lowering for TPU on a laptop (this page)TRITON_INTERPRET=1; Pallas's interpret=TrueRuns anywhere

The same Pallas source lowers to both backends only while it stays generic: anything using pltpu scratch, semaphores, DMAs or CompilerParams is TPU-only, and lowering it for cuda fails with "Compiler params for platform tpu cannot be used for gpu lowering." (the section 3 softmax with its TPU CompilerParams, measured here). The GPU side, Triton and its successors, is on Triton and Gluon and Topic: cuda-and-gpu-programming; what XLA fuses without help is on XLA and compilation.

Depth: three design questions

Optional rehearsal; each answer adds something the sections above do not say outright.

Design a fused grouped matmul for mixture-of-experts on a TPU: grid, BlockSpecs, semantics and test plan

Inputs: tokens sorted by expert (m × k), expert weights (E × k × n), group sizes. Precompute on the host or in jnp a metadata list mapping each grid index to (group, row tile), with tiles that straddle a group boundary listed once per group; pass it by scalar prefetch. Grid (tiles, n blocks, k blocks); lhs map (row tile, k), rhs map (group, k, n block), out map (row tile, n block); semantics ("parallel", "parallel", "arbitrary") with the k loop accumulating in a float32 scratch; mask rows outside the group on straddling tiles. Backward: a transposed variant for dW (per group) and the same kernel for dX, under custom_vjp. Tests: per-group jnp matmuls as the reference, uneven and empty groups, bf16 tolerances, the TPU interpreter with two cores, lowering for TPU; then tile sizes swept on the chip. This is megablox's design (ran here: error 2.7e-7).

How do you test a TPU kernel without a TPU, flag by flag?

A jnp reference; interpret=True for values and gradients (assert_allclose with dtype-based tolerances); interpret=pltpu.InterpretParams(detect_races=True, num_cores_or_threads=2) for ordering, DMA and out-of-bounds bugs; jax.export(..., platforms=["tpu"]) to catch illegal block shapes and unsupported ops. Then the chip, for speed and VMEM.

Why does the production flash kernel store its running max and sum 128 values wide?

VMEM and vector registers are laid out in 8 × 128 tiles; an array whose last dimension is 1 occupies a full 128-lane row anyway, and keeping the statistic replicated across lanes makes broadcasting it against a 128-wide score tile free. The same padding is why a 65-wide vocabulary wastes 49% of the lanes (section 3).