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.
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.(i, 0) at step 0 means rows 0 to 511.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.#tpu.pipeline_mode<synchronous> (section 3).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.
x_ref[...] and writes o_ref[...] = ....interpret=True), or under the TPU interpreter, which simulates copies and cores.jax.grad of a pallas_call fails; wrap forward and backward kernels in jax.custom_vjp (sections 4 and 5).| Kernel (this page) | What it teaches | Checked against | max 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.
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:
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.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.
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%.| Situation | Do this | PyTorch counterpart |
|---|---|---|
| Matmuls, elementwise chains, reductions, normalisation | Let XLA fuse it; check the fusion on XLA and compilation | torch.compile and Inductor |
| Flash, splash, paged or ragged attention; grouped matmuls for MoE | Call a ready-made kernel (section 10) | FlashAttention, FlexAttention, vLLM kernels |
| A new attention variant, a fused quantised matmul, a collective overlapped by hand | Write a Pallas kernel | A Triton or CUDA kernel |
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)
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).
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:
| Piece | What it is | Triton 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_shape | A jax.ShapeDtypeStruct (or a tuple) per output. Outputs start uninitialised. | torch.empty passed in |
scratch_shapes | Buffers 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 spaces | VMEM: 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.
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).
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.
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.
custom_vjp that joins them, as they ranHow 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):
dx band back: 16 copies of each, like any row kernel.pl.when(pl.program_id(0) == 0)) and adds each band's contribution at every step.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 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.
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.
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:
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?
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):
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.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:
didK 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.
custom_vjp, as they rancustom_vjp that joins them is at the end of the backward.| Kernel, same tensors | output | dQ | dK | dV |
|---|
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
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.
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:
| bq | bk | grid steps per head | tiles computed | max abs. error | lowers 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.
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).
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.
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.
| Buffering | Interpret mode | Lowered for TPU v5e | VMEM 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.
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 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).
src/runs/pk_run.py (NumPy seed 0).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.
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).
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.
grid_point_recorder, the query blocks came in the order 3, 1, 0, 2, each with its key blocks 0 to 3 in order. The interpreter randomises "parallel" axes on purpose (random_seed, interpret/params.py:144) so a kernel that silently depends on their order fails in testing; the "arbitrary" LayerNorm backward came out in order (yes). A real single-core TPU runs the grid lexicographically. Replay both recorded orders in section 2's lab (Flash fwd or Softmax, "Recorded").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.
interpret=pltpu.InterpretParams(...): simulated DMAs, cores, races, out-of-bounds blockscaught 3 of 4 planted bugsjax.export(..., platforms=["tpu"]) on a laptop: Mosaic accepts the tiling or says why not11 of 11 lower| Planted bug | interpret=True | TPU interpreter | Lowering 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
| Kernel | XLA, ms | interpret mode, ms | ratio |
|---|
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.
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.
| Kernel | What it is for | What to learn from it | Here |
|---|---|---|---|
ops/tpu/flash_attention.py | Flash attention with causal masking, segment ids and a bias, forward and backward | A 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 default | ran 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 prefetch | read |
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 masked | ran 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 feature | read |
ops/gpu/attention.py and the other Triton-backed GPU ops | Flash attention, layer and RMS norm, softmax, decode and paged attention for GPUs, through Triton | The 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.16 | One 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 more | implementation=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) |
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:
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.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.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.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.
softmax_kernel on the scores s [16,384 × 128] float32. Lowered with jax.export for platforms=["tpu"] it becomes Mosaic; for ["cuda"], Triton.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.!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.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 | |
|---|---|---|---|
| Grid | A sequential loop; blocks shared by steps stay in VMEM | Parallel programs; shared results need atomics or a second kernel | The compiler chooses |
| Memory movement | BlockSpecs generate double-buffered DMAs into VMEM; or by hand with async copies and semaphores | Pointer arithmetic and tl.load with masks; the compiler pipelines loads (num_stages) | Fusion keeps intermediates on chip where it can |
| Edges and shapes | Last two block dims divisible by (8, 128) or equal to the array; narrow arrays padded to 128 lanes | Power-of-two blocks; any edge handled by masks | Any shape; padding inserted for you |
| Gradients | jax.custom_vjp around forward and backward kernels | torch.autograd.Function (or custom_vjp from JAX) | Automatic |
| Tuning | Your sweep, a checked-in table, or tokamax | @triton.autotune configs | XLA's own heuristics and autotuner |
| Testing without hardware | Two interpreters and lowering for TPU on a laptop (this page) | TRITON_INTERPRET=1; Pallas's interpret=True | Runs 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.
Optional rehearsal; each answer adds something the sections above do not say outright.
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).
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.
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).
Every kernel on this page, with its code as it ran, what was measured about it here, what the TPU lowering produced, and a calculator for the one decision you would tune on a chip: the block size, and whether its buffers fit in VMEM.
Measured values: src/runs/out/kernels.json (interpret mode on Apple M1 Pro CPU, jax 0.11.2). Lowering: jax.export(..., platforms=["tpu"]) for a TPU v5e on this CPU, op counts read from the printed Mosaic module (not compiled). The calculator is arithmetic, not a measurement: buffers × block bytes, two buffers per pipelined operand, one for a block that never moves (the lowering's single-buffering rule), plus scratch; "padded" rounds every block's last two dimensions up to (8, 128) as VMEM tiles do. VMEM per TensorCore by generation is read from jax/_src/tpu_info.py at jax-v0.11.2 (as the root's TPU lab reads it). The compiler also applies a lower default limit per kernel, raised with vmem_limit_bytes and the --xla_tpu_scoped_vmem_limit_kib flag; its default value is not stated in the source read here, so it is not drawn.
This page's tabs, the parent topic and its lab, the sibling pages, the knowledge base pages on the GPU side, and the best outside sources, each with an approximate time. Outside sources are marked Google (written by the makers of JAX and Pallas) or third-party. Links checked on 2026-10-15.
When a kernel wins, the grid and BlockSpecs with a stepper for ten kernels, row kernels, LayerNorm and flash attention with their backwards (the online softmax replayed on a trained head), pipelining, scalar prefetch, semantics, testing, production kernels, block sizes, Triton. 33 min, plus 13 in closed details
Each kernel's code, its measured errors, its Mosaic lowering, and a VMEM calculator by block size and generation. 4 min
The overview this page goes deeper than. Its TPU and Pallas lab tab has the five ideas of Pallas, the tiled matmul and flash forward this page builds on, three planted bugs, the Mosaic module of a matmul, the (8, 128) block rule, and HBM traffic by block size; its section 6 places Pallas in the stack. Reading: 32 min, plus 13 in closed details; TPU and Pallas lab 25 min, plus 5
What XLA fuses on its own and why it stops (section 4), the softmax compiled three ways, layouts, and AOT export: the "write nothing" alternative to this page.
custom_jvp and custom_vjp from zero (section 6), the mechanism every training kernel here relies on; vmap and its batching rules.
The chip from the programmer's side: MXU, VPU, VMEM, HBM per generation, rooflines and MFU.
shard_map and collectives, the context a multi-chip kernel runs in.
Where MaxText and others call splash attention and the other kernels read here.
Triton's block-level model, autotuning and compiler stages: the GPU counterpart of this page.
Reductions, softmax, tiled matmul and FlashAttention 1 to 4 on GPUs, with causal skipping and Flash-Decoding measured.
The CUDA model that Pallas's TPU model is contrasted with throughout.
The algorithm, its IO argument, and a live HBM against on-chip animation.
Why serving stores the KV cache in pages, simulated.
The hardware: systolic arrays and TPU pods.
Google. The quickstart, grids and BlockSpecs, and the TPU and GPU sections. 45 min for the core pages
Google. The index map semantics precisely, including squeezed and element dimensions. 20 min
Google. Memory spaces, multiple buffering, emit_pipeline, lookahead, megacore. 25 min
Google. The cost model and the v5e block-size measurements quoted in sections 1 and 11. 30 min
Google. The basis of section 7, with block-sparse matmuls. 25 min
Google. What is supported on TPU, the sequential grid, the (8, 128) rule, dimension semantics. 20 min
Google. Remote DMAs over ICI, semaphores, collectives written as kernels: the topic this page does not run. 40 min
Google. Why refs, why the grid and BlockSpecs, how interpret mode and the transformations fit. 25 min
Google. The production TPU kernels read in section 10. 1 to 3 h to read the attention kernels
Google (OpenXLA). The kernel library replacing jax's GPU ops, with autotuning. 15 min for the README
Google. VMEM, HBM and the MXU, which every block-size decision rests on. 50 min
Third-party. The backward algorithm implemented in section 5. 40 min
Third-party. The rescaling trick behind section 5's replay. 15 min
Third-party. Section 3's softmax as a Triton programmer writes it, pointers and masks included. 15 min