Fig. 1 follows one call of the running example's jitted train step (below) down the stack, one station per layer. Each layer passes the next a program, and each has a child page; read down the list for the order this page takes.
nn.Module, torch.optim, DCP, DataLoader). JAX itself has none of them (section 4); together they hand down a pure function, so the running example's 826,368 parameters and their Adam state, 9.9 MB, go in as arguments and come back as results. Owner: The JAX training stack, whose Fig. 1 follows one training step through the four libraries; the port: PyTorch to JAX, whose Fig. 1 gives one step's state its two homes. Lab here: Training lab.jit, grad and vmap call the function once with tracers (a shape and a dtype, no values) and record a jaxpr: 3,411 equations for the whole step, forward, backward, clipping and AdamW measured. grad and vmap are interpreters that rewrite one jaxpr into another (in PyTorch: torch.compile, loss.backward(), torch.func.vmap). Owner: JAX core, whose Fig. 1 runs one sin through three interpreters, Fig. 2 traces once, compiles once and runs many times, Fig. 3 differentiates an MLP one plate per equation and Fig. 4 nests vmaps. Lab: Transforms lab. Section 2.Mesh and a PartitionSpec per array; the partitioner splits the work into one program per device and inserts the collectives. On 8 simulated devices, data parallel compiles to 1 all-reduce of 3.3 MB, and FSDP leaves 0.4 MB of weights on each device (section 5's table) measured. In PyTorch: DDP, FSDP2, DTensor, chosen as wrappers. Owner: Sharding and scale, whose Fig. 1 puts two annotations on 8 devices and finds one collective, and Fig. 5 writes the per-device program with shard_map. Lab: Sharding lab. Section 5.A map, not a mechanism: each step lights the layer one child page owns and links that child's own figure. Read it as the life of one train step: the highlighted labels are what one layer hands the next. Numbers are the running example's, measured by this page's labs on a CPU; the chip's are section 6's.
You need PyTorch as a user (the page maps every idea to it; its layers are on Topic: pytorch-ecosystem); rooflines and MFU help in section 6 (Performance math).
New terms, each used again below:
f32[8,128]), recording what is done to itdot_general, add, tanh)The running example. Every lab works on the same model, so their numbers compare. One tiny decoder-only transformer language model over characters: the 65 distinct characters of TinyShakespeare, 4 layers, width 128, 4 attention heads, MLP width 512, context 128 characters, 826,368 parameters. It is written three times, in PyTorch, in Flax NNX and in plain JAX with optax (src/data/), and all three read the same batches of 32 sequences. Started from the same weights, their logits agree to within 8.3e-07 and their training losses over 500 steps to within 2.9e-05 measured (setup's check_equiv.py), so any later difference between them is a finding, not noise. Everything ran on an Apple M1 Pro CPU; for sharding, one flag makes JAX treat the CPU as 8 separate devices, so meshes, shardings and collectives compile and run for real (the programs and memory figures are real; the speeds are not those of accelerators).
Labels: measured here in October 2026 on that CPU; vendor a maker's figure about its own product; third-party a figure from someone without a stake; derived computed with the formula shown; unconfirmed no primary source confirms it.
PyTorch runs your Python line by line (eager execution): each operation goes to the device when Python reaches it, and autograd records a tape for loss.backward(). That is wonderful for debugging and costs two things at scale: Python is on the critical path of every operation, and no one ever sees the whole program, so no one can optimise across it or decide, for the whole step, how to split it over thousands of chips. JAX takes the opposite bet: record the function first, then transform it and compile it as a whole with XLA (Accelerated Linear Algebra, Google's compiler for array programs, which started inside TensorFlow). In its own words, "a Python library for accelerator-oriented array computation and program transformation" (JAX README); an early version was described at SysML 2018 (Frostig, Johnson and Leary, "Compiling machine learning programs via high-level tracing"). The price is purity: parameters, optimiser state and random-number state stop hiding inside objects and become values you pass in and get back.
Who uses it. Google DeepMind trains Gemini with it: "We trained Gemini models using TPUv5e and TPUv4", where "the 'single controller' programming model of Jax and Pathways allows a single Python process to orchestrate the entire training run" (Gemini 1 report, section 3, vendor). Apple's foundation models "are pre-trained on v4 and v5p Cloud TPU clusters with the AXLearn framework", a JAX library: the server model on 8,192 TPUv4 chips and the on-device model on one slice of 2,048 TPUv5p chips (Apple AFM report, section 3.3). xAI released Grok-1 (314B parameters) with "JAX example code" (grok-1 repository). Outside the large labs PyTorch dominates: on the Hugging Face Hub, 255,916 models are tagged PyTorch and 12,404 JAX, about 21 to 1 measured 2026-10-15 from the Hub's library filter (a weak signal: the tag follows the weight files uploaded, and models trained in JAX are often uploaded as PyTorch weights).
Tracing. When a transformation meets your function, JAX calls it once with tracers: stand-ins that carry an abstract value (shape and dtype, no numbers) and record every array operation into a jaxpr, a small typed program of primitives. Python itself (loops, helper functions, arithmetic on shapes) runs to completion and leaves no trace. Every transformation is then an interpreter over that program, which explains the rest:
jax.jit(f) compiles the jaxpr with XLA and caches the executable under the call's signature: argument shapes and dtypes, plus any argument marked static, whose Python value is baked in. A new signature means a new trace and a new compile; shapes are always static, so variable lengths are padded and masked. PyTorch: torch.compile, but all or nothing.jax.grad(f), jax.value_and_grad(f) return a function computing the gradient of a scalar f, with exactly the structure of the parameters: no .grad attributes, no zero_grad(). PyTorch: loss.backward(), but as a function; jax.lax.stop_gradient is detach().jax.vmap(f) turns a function for one example into one for a batch by rewriting each primitive into its batched form. Per-example gradients are vmap(grad(loss), in_axes=(None, 0)). PyTorch: torch.func.vmap, which ports the idea.The discipline follows from tracing. Arrays are immutable (x = x.at[0].set(1.0) returns a new array; under jit it becomes an in-place write). A Python if on a traced value is an error and a Python loop is unrolled, so compiled code uses jax.lax.cond, jnp.where, jax.lax.scan and while_loop. Randomness is a value: a key (jax.random.key(0)) is split into a fresh subkey for every use, and the same key always gives the same numbers. And a pytree (nested lists, tuples, dicts and registered classes with arrays at the leaves) holds parameters, gradients and optimiser state alike: jax.tree.map(lambda p, g: p - lr * g, params, grads) is a complete SGD step, replacing model.parameters(), state_dict() and parameter groups.
Fig. 2, step by step
jit runs the Python function once with tracers (shapes and dtypes only) and records every primitive into a jaxpr. Nothing has been computed yet.print("step", x). You call it three times with arrays of the same shape. What appears?One line, showing a tracer. The body runs only while tracing; the second and third calls hit the cache and Python never runs. Use jax.debug.print for values at run time.
import jax, jax.numpy as jnp
@jax.jit
def f(x):
print("step", x)
return x * 2
for _ in range(3):
f(jnp.ones(4))step JitTracer(float32[4])
Ran with jax 0.11.2 on Apple M1 Pro (CPU), Python 3.12.11; output as printed.
import jax, jax.numpy as jnp
def mlp(w1, w2, x): # x: [tokens, d_model]
h = jax.nn.gelu(x @ w1) # [tokens, 4 * d_model]
return h @ w2
w1, w2 = jnp.ones((128, 512)), jnp.ones((512, 128))
x = jnp.ones((8, 128))
print(jax.make_jaxpr(mlp)(w1, w2, x)){ lambda ; a:f32[128,512] b:f32[512,128] c:f32[8,128]. let
d:f32[8,512] = dot_general[
dimension_numbers=(([1], [0]), ([], []))
preferred_element_type=float32
] c a
e:f32[8,512] = integer_pow[y=3] d
f:f32[8,512] = mul 0.044714998453855515:f32[] e
g:f32[8,512] = add d f
h:f32[8,512] = mul 0.7978845834732056:f32[] g
i:f32[8,512] = tanh h
j:f32[8,512] = add 1.0:f32[] i
k:f32[8,512] = mul 0.5:f32[] j
l:f32[8,512] = mul d k
m:f32[8,128] = dot_general[
dimension_numbers=(([1], [0]), ([], []))
preferred_element_type=float32
] l b
in (m,) }Ran with jax 0.11.2 on Apple M1 Pro (CPU), Python 3.12.11; output as printed.
Inputs with their abstract values, one primitive per line, no Python left. The GELU became tanh and a cube because jax.nn.gelu defaults to the tanh approximation (approximate=True) while PyTorch's nn.GELU defaults to the exact form (approximate='none'). Nested transformations: each primitive is handled by the current trace, held in a context (core.trace_ctx); tracing has been "stackless" since jax 0.4.36 (December 2024), so explanations of trace levels and MainTrace, including part 1 of Autodidax, describe machinery that no longer exists, and an inner jit prints as jit, where older posts show pjit. Loops: lax.scan is how layers, RNNs and decode loops are written, and much faster to compile than an unrolled loop; fori_loop and while_loop with a dynamic trip count are not reverse-differentiable. Flax's nnx.Rngs does the key splitting inside models.
A jitted function passes through four forms, each printable: the jaxpr (jax.make_jaxpr(f)(x)); StableHLO, a versioned, portable operation set in MLIR and the hand-off point between frameworks and compilers (PyTorch's TPU and Trainium backends emit it too; jax.jit(f).lower(x).as_text()); optimised HLO after XLA's passes (.compile().as_text()); and machine code (LLVM for CPUs, GPU kernels, some through Triton, or the TPU backend).
The passes that matter to you, each defined once:
compiled.memory_analysis() reports its result before anything runs.jax.jit(step, donate_argnums=0) promises the old parameters and optimiser state are dead, so the new ones reuse their buffers instead of a second copy existing. Flax's nnx.jit donates nothing unless asked.jax.checkpoint (alias jax.remat) recomputes activations in the backward pass instead of storing them; policies choose what to keep. PyTorch: activation checkpointing.Compile time is real time. A large step's first call can take seconds to minutes; the executable is cached in memory, and a persistent compilation cache (jax.config.update("jax_compilation_cache_dir", ...)) keeps it across runs. Long Python loops multiply compile time, which is why layers are stacked and run with lax.scan.
Against torch.compile. TorchDynamo reads Python bytecode, captures what it can, and at anything it cannot handle inserts a graph break that runs eagerly. JAX never reads your Python: Python control flow is resolved while tracing or is an error. One graph or none, no silent fallback (torch.compile from the user's side owns the PyTorch side).
compiled.cost_analysis() counts a loop body once: the step written with lax.scan reports 6.39 GFLOP against 23.71 for the unrolled step measured (Compiler lab), so multiply by the trip count yourself. Flax's donation spelling is @nnx.jit(donate_argnames=("model", "optimizer")) (flax 0.12.10, nnx/transforms/compilation.py:317-318).
JAX has no layers, optimisers or checkpoints. Four libraries supply them, together what Google calls the JAX AI stack (docs.jaxstack.ai); versions are the latest on PyPI on 2026-10-15.
| PyTorch | JAX stack | The difference that matters |
|---|---|---|
nn.Module | Flax NNX (flax 0.12.10): nnx.Module, nnx.Linear(d_in, d_out, rngs=rngs) | Feels like PyTorch: modules hold their parameters as attributes (nnx.Param) and are built eagerly. To enter a JAX transformation a module is split into a static graphdef (its structure) and a state pytree (its arrays) and merged back after; nnx.jit and nnx.value_and_grad do this for you. |
torch.optim.AdamW | optax (0.2.8): optax.adamw(...) | An optimiser is a pair of pure functions, init(params) and update(grads, state, params), returning updates you apply. Clipping, schedules, weight-decay masks, accumulation (MultiSteps) and EMA are links in optax.chain(...), not subclasses; a schedule is just a function of the step. |
torch.save, DCP | orbax (orbax-checkpoint 0.12.7) | Asynchronous and sharded by default: each host writes its own shards and restores straight into a target sharding; the counterpart of torch.distributed.checkpoint, but the default path. |
DataLoader | grain (0.2.18) | Deterministic shuffling and an iterator whose position is saved with the checkpoint, so a preempted run resumes mid-epoch on exactly the next batch. |
Which neural-network library. For new code, Flax NNX: "new users are encouraged to use Flax NNX", and Linen "is not going to be deprecated in the near future as most of Flax users still rely on this API" (Flax docs). Learn to read Linen (stateless modules: model.init(key, x) returns a parameter dict, model.apply(params, x) runs it), the style of most JAX code written before 2025. Equinox (0.13.8) makes a model itself a pytree, popular in research. Haiku is in maintenance mode: "As of July 2023 Google DeepMind recommends that new projects adopt Flax instead of Haiku", though still released (0.0.17, 2026-07-27) (Haiku README).
Mixed precision is the PyTorch recipe written out: float32 master parameters and optimiser state, bf16 for the matmuls, float32 for softmax and the loss. On TPUs bf16 is native and no loss scaling is needed.
import jax, optax
from flax import nnx
import common as C, model_nnx as M # the running example (src/data)
model = M.make_model(C.CFG) # built eagerly, like an nn.Module
optimizer = M.make_optimizer(model, C.CFG) # nnx.Optimizer(model, optax chain, wrt=nnx.Param)
@nnx.jit(donate_argnames=("model", "optimizer")) # one compiled program; reuse the old buffers
def train_step(model, optimizer, x, y):
def loss_fn(model):
logits = model(x) # [B, T, vocab]
return optax.softmax_cross_entropy_with_integer_labels(logits, y).mean()
loss, grads = nnx.value_and_grad(loss_fn)(model) # grads mirror the parameters
optimizer.update(model, grads) # zero_grad + backward + step, in one call
return loss
params = nnx.state(model, nnx.Param)
print("parameters:", sum(p.size for p in jax.tree.leaves(params)))
for step in range(3):
x, y = C.batch(step) # int32 [32, 128]: the batches PyTorch reads too
print(step, x.shape, float(train_step(model, optimizer, x, y)))parameters: 826368 0 (32, 128) 4.200614929199219 1 (32, 128) 4.168322563171387 2 (32, 128) 4.115612506866455
Ran with jax 0.11.2 and flax 0.12.10 on Apple M1 Pro (CPU); output as printed. The model and optimiser come from src/data/model_nnx.py (AdamW with warmup, global-norm clipping and weight decay on weight matrices only); nnx.jit donates nothing unless asked, hence donate_argnames; float(...) forces a host sync, fine for three steps and a mistake in a real loop.
In PyTorch you choose a parallelism implementation (DDP, FSDP2, tensor-parallel layers) and it owns the communication. In JAX you write the single-device step once, say how arrays are laid out over devices, and the compiler does the rest. Three objects carry the description: a Mesh (devices as a named grid, such as 8 devices as ('data', 'model') of 2 × 4), a PartitionSpec P(...) (for each array dimension, the mesh axis that splits it, or None), and a NamedSharding (the two together, attached with jax.device_put, to a jitted function's inputs and outputs, or to intermediates with with_sharding_constraint).
The compiler's partitioner then propagates shardings to every other array and, wherever an operation needs data laid out differently, inserts a collective: all-gather (everyone gets the whole array), reduce-scatter (sum, each keeps a slice), all-reduce (sum, everyone gets the result), all-to-all, or permute. The design is GSPMD (Xu et al. 2021); since JAX 0.7.0 (2025-07-22) the propagation is done by its successor Shardy, which "will be the only partitioner in JAX" (JAX Shardy migration guide). The strategies you know become different specs on the same function:
| Strategy | Batch spec | Weight spec | Collectives XLA inserts | PyTorch |
|---|---|---|---|---|
| Data parallel | P('data') | replicated, P() | all-reduce of gradients | DDP |
| FSDP (ZeRO-3 style) | P('data') | split on 'data' too | all-gather weights before use, reduce-scatter gradients | FSDP2 |
| Tensor parallel | P('data') | MLP in: P(None, 'model'); MLP out: P('model', None) | two all-reduces of activations per block in the forward pass (after attention and after the MLP), more in the backward | Megatron-style TP, DTensor |
| Layout | Mesh | Collectives in the compiled step | Bytes in them | Weights per device | Loss vs one device |
|---|---|---|---|---|---|
| One device | 1 | none | 0 | 3.3 MB | 0.0e+00 |
| Data parallel | 8 | 1 all-reduce | 3.3 MB | 3.3 MB | 4.8e-07 |
| FSDP, weights annotated only | 8 | 94 all-gather, 36 all-to-all, 80 all-reduce | 174.1 MB | 0.4 MB | 4.8e-07 |
| FSDP (ZeRO-3 style) | 8 | 78 all-gather, 70 all-reduce | 6.6 MB | 0.4 MB | 4.8e-07 |
| Data x tensor parallel | 2 × 4 | 18 all-reduce | 26.1 MB | 0.9 MB | 7.2e-07 |
| FSDP x tensor parallel | 2 × 4 | 4 collective-permute, 62 all-gather, 58 all-reduce | 28.1 MB | 0.5 MB | 7.2e-07 |
| Sequence sharded | 8 | 11 all-gather, 6 all-reduce | 37.0 MB | 3.3 MB | 9.5e-07 |
The second row is the lesson: sharding the weights and the batch but leaving the activations unannotated let the partitioner choose layouts that all-gather 32 times more bytes (105 MB against 3.3 MB); one with_sharding_constraint on the residual stream per block (the next row) fixed it. measured by the Sharding lab.
Collectives counted in compile().as_text() of the whole step (forward, backward, clipping, AdamW, donated state), 20 steps each, Auto mesh axes, jax 0.11.2 (src/shard/out/rd_collectives.json). Bytes are the sizes of the arrays the collectives carry, not link traffic. Data parallel compiles to a single all-reduce: XLA combined every gradient into one. FSDP shows all-reduces where a reduce-scatter is expected: XLA's CPU pipeline reduces then slices, while its GPU pipeline has the pass that turns that into a reduce-scatter (Sharding lab, XLA source). Tensor parallel's 18 all-reduces include 8 in the forward pass, two per block.
Why it is not optional. Replicated training state, 16 bytes per parameter, outgrows any chip; the widget sets data parallel against FSDP for four model sizes on up to 8,960 devices.
Who decides, and when you want control. On Auto mesh axes the compiler chooses everything you did not annotate. On Explicit axes a sharding is part of the array's type (jax.typeof(x)) and ambiguous cases are errors at trace time; in JAX 0.11.2 jax.make_mesh makes Explicit axes by default, while the Mesh constructor still defaults to Auto, so pass axis_types=(AxisType.Auto,) * 2 to get the behaviour older tutorials assume. jax.shard_map runs a function per device on its local shard with collectives you write (psum, all_gather, ppermute): the rank-view program a torch.distributed user knows. Old code you will meet: pmap (in maintenance mode since 0.8.0), pjit (merged into jit), xmap (deleted in 0.4.31) (JAX changelog). Across many hosts the same script runs on every host and one jitted program spans the slice (not run here: one host).
An x @ W whose contracted dimension is sharded raises a ShardingTypeError under Explicit axes until you say how the output is sharded; jax.set_mesh(mesh) sets the mesh it uses. MaxText still defaults to automatic mode (shard_mode: "auto"). shard_map left jax.experimental in JAX 0.8.0 (2025-10-15); pmap is now reimplemented over jit and shard_map. Many hosts: jax.distributed.initialize() connects them, jax.process_index() is the rank, and each host feeds its part of the batch with jax.make_array_from_process_local_data; collectives ride the ICI links.
Training state = 16 bytes per parameter (bf16 weights and gradients, fp32 master weights and two Adam moments; the accounting of the ZeRO paper), activations excluded. derived 16 × parameters ÷ devices for FSDP, 16 × parameters for data parallel; HBM capacities vendor (section 6), all in GB of 109 bytes (v5p's 95 GiB is 102 GB, Ironwood's 192 GiB is 206 GB).
A GPU is about a hundred small processors running thousands of threads. A TPU chip has one or two big TensorCores and no threads: think "one wide core with a matrix engine and explicitly managed memory", scheduled almost entirely by XLA. The parts a JAX programmer meets:
jax/_src/tpu_info.py at jax-v0.11.2).| Chip (Cloud name) | Track | bf16 peak per chip | HBM, bandwidth | Largest pod | Ridge point derived |
|---|---|---|---|---|---|
| v5e (2023) | efficiency | 197 TFLOP/s | 16 GB, 819 GB/s | 256 chips, 2D torus | 241 |
| v5p (Dec 2023) | performance | 459 TFLOP/s | 95 GiB, 2,765 GB/s | 8,960 chips, 3D torus | 166 |
| v6e Trillium (May 2024) | efficiency | 918 TFLOP/s | 32 GB, 1,638 GB/s | 256 chips, 2D torus | 560 |
| TPU7x Ironwood (announced Apr 2025) | both | 2,307 TFLOP/s (4,614 fp8) | 192 GiB, 7,380 GB/s | 9,216 chips, 3D torus | 313 |
Ridge point = peak FLOP/s ÷ HBM bytes/s, in FLOPs per byte: an operation doing fewer FLOPs per byte it moves is limited by memory, not by the matrix units. vendor specifications as verified on TPUs and other accelerators, which owns the full table, v1 to Ironwood.
Ironwood's ridge uses its bf16 peak. v5e's bandwidth is ambiguous: Cloud's page says "800 GiBps" (859 GB/s, ridge 229), the scaling book and JAX's own tpu_info.py 819 GB/s, used here. The specifications come from the Cloud TPU documentation and Google's posts; the hardware page also records where they disagree.
The roofline in one line. A matmul of B tokens against a D × F weight does 2BDF FLOPs and moves about 2DF bytes of bf16 weights, so when B is much smaller than D and F its arithmetic intensity is about B FLOPs per byte. Training with thousands of tokens per chip clears every ridge above; decoding one token at a time for 8 users does not.
Pallas. XLA writes almost every kernel, and for most training that is enough. When it is not (attention variants, mixture-of-experts routing, quantised or ragged matmuls), Pallas is JAX's kernel language, the counterpart of Triton: a Python function over refs (buffers in on-chip memory), launched on a grid, with a BlockSpec per input saying which tile each grid step loads. It lowers through Mosaic on TPU and through Triton or Mosaic GPU on GPU (Pallas docs); interpret=True runs a kernel on the CPU, checking indexing and correctness but not speed.
The TPU and Pallas lab wrote two kernels and ran them interpreted measured: a tiled matmul on the running example's MLP shape (4,096 × 512 times 512 × 128, blocks of 512 × 128 × 128 on an 8 × 1 × 4 grid) matches jnp to 2.5e-7, and a causal flash-attention kernel (64 × 64 blocks) matches to 8.9e-8 while skipping 128 of its 512 blocks above the diagonal. Interpreted, the matmul took about 49 ms against 4.7 ms for XLA's own, which says nothing about a TPU. A stricter interpreter that simulates the TPU's cores caught a bug the plain one hid: marking the reduction axis of the grid "parallel" gave an error of 0.17.
Production JAX for large language models lives in a few open repositories, where sections 2 to 6 meet: a model in Flax NNX, optax, orbax, grain, and above all the rules that map each weight's named dimensions onto a mesh. Activity is the last push to the default branch, from the GitHub API on 2026-10-15.
| Codebase | What it is | Read it for |
|---|---|---|
| MaxText | Google's "high performance, highly scalable, open-source LLM library and reference implementation" in pure JAX, for TPUs and GPUs: Gemma, Llama, Qwen, DeepSeek, Kimi, GPT-OSS, Mixtral; "migrated to Flax NNX from Linen" (README news, 2026-06-29); post-training through Tunix since 2025-10-10. Pushed 2026-10-15. | The decoder and the train step; logical_axis_rules, which map logical dimension names (embed, mlp, heads) to mesh axes in a config so sharding never appears in model code. |
| Tunix | Google's JAX post-training library ("Tune-in-JAX"): supervised fine-tuning (full and parameter-efficient), DPO and ORPO, RL with PPO, GRPO, GSPO-Token, DAPO and Dr.GRPO, multi-turn agentic RL, and a distillation package. "V2 Release", "under active development". Pushed 2026-10-15. | The GRPO trainer: how sampling and training share one set of devices. What GRPO and PPO are is taught on RL for LLMs. |
| levanter (now in Marin) | Stanford CRFM's trainer, built "with JAX, Equinox, and Haliax" (a named-tensor library); "bitwise deterministic ... even in the face of preemption and resumption" on TPU. "Levanter has been merged into Marin" (November 2025); development continues in Marin's lib/levanter/. | A non-Google design: named axes everywhere, and what it takes to make a run reproducible to the bit. |
| AXLearn | Apple's JAX library on which its foundation models were trained (section 1). Pushed 2026-07-08. | A second large-company stack, configuration-heavy. |
| big_vision | Google Research's vision codebase (ViT and its descendants) in Flax Linen. Last pushed 2025-05-19: not archived, but quiet. | The older functional Linen style in its cleanest form. |
Older Google stacks (T5X, Pax), EasyLM and serving (vLLM's TPU backend tpu-inference, which says it unifies "JAX and PyTorch under a single lowering path", and JetStream) are dated on the Tool map.
| Model | Chips | Configuration | MFU | Tokens/s per chip |
|---|---|---|---|---|
| Llama 2 70B | v6e | 256 chips, bf16, sequence 4,096 | 43.8% | 900 |
| Llama 3.1 8B | v6e | 256 chips, bf16, sequence 8,192 | 45.46% | 7,207 |
| Llama 3.1 70B | v6e | 256 chips, bf16, sequence 8,192 | 50.33% | 960 |
| Llama 2 70B | v5p | 512 chips, bf16, sequence 4,096 | 65.4% | 692 |
vendor figures from MaxText's docs/reference/models/tiering.md at commit 1a95d1e5 (2026-10-15; the page itself is undated), which also lists Silver models (Llama 3.1 405B 38.55% and Mixtral 8x22B 36.2% on v6e; Mixtral 8x7B 52.56% on v5p). These figures match the pre-July-2025 non-causal FLOP count. Recomputed with MaxText's own FLOP counter from the published tokens per second, 6 of these 8 MFUs (Gold and Silver) come out within 0.22 points only when attention is counted as non-causal, as MaxText did before pull request 1988; with the causal count its current code uses, all eight recompute 0.8 to 5.1 points below the published figure (Llama 3.1 405B on v6e and Llama 2 70B on v5p reproduce under neither count). derived on TPU programming and performance (section 9) and JAX LLM codebases (section 6). MaxText's own docs warn that comparing MFU across codebases needs identical FLOP counting. Nobody independent has measured these here.
Neither is faster in general: both end in compiled kernels on the same hardware, and speed comes from the program, the shapes and the sharding more than the framework. They differ in what they make easy. Each row says who wins and the evidence; where the evidence is an opinion, it says so.
| Axis | JAX | PyTorch | Edge |
|---|---|---|---|
| Debugging | Inside jit you see tracers, not numbers; errors appear at trace time, far from the data (section 2, Mistakes). | Eager: print, breakpoints and stack traces work on real values. | PyTorch |
| Compiling the step | jit captures the whole step or raises an error; no silent fallback, one XLA program including the backward pass and the optimiser. | torch.compile is optional; a graph break (code Dynamo cannot capture) silently splits the graph and falls back to eager for that part (torch.compile from the user's side). | trade-off: JAX is predictable once it compiles; PyTorch always runs. |
| Composable transforms | grad, vmap, jit, jvp nest freely: per-example gradients are vmap(grad(loss)). | torch.func ports the same idea; it works on functional code, not on stateful modules directly. | JAX, narrowly |
| Sharding | One program; annotate a few arrays with a mesh and partition specs and the compiler inserts the communication (section 5). Gemini's whole run is driven by one Python process (section 1). | FSDP2, DTensor, tensor and pipeline parallel APIs, composed by hand (Distributed PyTorch); one process per GPU. | JAX for simplicity of the model code; both reach thousands of chips |
| TPUs | Native: TPUs were designed around XLA. | Native too since 20 October 2026: TorchTPU, open source, makes the TPU an ordinary PyTorch device with eager mode and torch.compile lowered to StableHLO; vLLM and SGLang TPU engines are built on it, and Meta serves with SGLang-TorchTPU in production. Google's own comparison, a vendor figure: Qwen3 MoE 235B in TorchTitan on 64 TPU v7 chips at 1,828 tokens/s against 1,937 for MaxText (PyTorch blog). It replaces PyTorch/XLA; torchax still runs PyTorch code through JAX. | JAX, for maturity |
| NVIDIA GPUs and kernels | Supported (CUDA wheels; Pallas lowers to Triton or Mosaic GPU); fewer ready-made kernels. | The default: FlashAttention, Triton, cuDNN integrations, every new kernel lands here first. | PyTorch |
| Ecosystem and models | 12,404 models tagged JAX on the Hub measured. | 255,916 tagged PyTorch measured; Hugging Face, vLLM, SGLang and most open releases are PyTorch-first. | PyTorch |
| Reproducibility | Random numbers come from explicit keys: the same key gives the same numbers whether generated on one device or sharded (identical on meshes of 8 and 2 × 4 simulated devices measured, src/read/key_sharding_check.py). | A hidden global generator per device; reproducible with care (seeds, deterministic algorithms). | JAX |
| Same model, same data | The running example's twins, from the same weights on the same batches for 4,000 steps (Training lab): validation loss at the end 1.5760 in PyTorch, 1.5765 in plain JAX and 1.5765 in Flax NNX; training losses within 2.9e-05 of each other over the first 500 steps and 9.5e-04 over all 4,000 measured. The gap is summation order: different kernels add the same numbers in different orders, and training compounds the last-bit differences slowly (explained in src/data/README.md and the Training lab). Median CPU step 73 ms in PyTorch eager, 102 ms in plain JAX and 115 ms in Flax NNX over setup's 500-step run, the first JAX step 1.1 s (tracing and compiling), measured on Apple M1 Pro (CPU), shared machine, 4 threads, low priority (the 4,000-step run's medians, 164, 193 and 225 ms, were taken under heavier load). On a CPU this small model is dominated by fixed costs, so these speeds say nothing about accelerators; the Training lab overlays the curves. | tie on results; speed not comparable here | |
Hugging Face counts: the Hub's library filter on 2026-10-15; a tag follows the weight files uploaded, not the framework a model was trained in. Activity dates from the GitHub API on the same day.
vmap over stacked parameters;A practical path (the old page's, kept because it works): develop and test on CPU, where JAX traces identically; check sharding on simulated CPU devices as this page does; smoke-test on a free single TPU chip; train on a slice; profile before buying more. Free TPU options are described in Further reading.
Optional. Each mistake is a PyTorch habit meeting JAX, with the real message from running it here (src/read/run_examples.py); the owning child explains each mechanism.
if on a traced valueThe tracer has no value, so Python cannot decide the branch. Use jax.lax.cond or jnp.where, or mark the argument static if it really is a configuration value.
import jax, jax.numpy as jnp
@jax.jit
def relu_or_not(x):
if x.sum() > 0: # a Python bool of a traced value
return x
return -x
relu_or_not(jnp.ones(3))jax.errors.TracerBoolConversionError: Attempted boolean conversion of traced array with shape bool[]. The error occurred while tracing the function relu_or_not at <snippet>:3 for jit. This concrete value was not available in Python because it depends on the value of the argument x. See https://docs.jax.dev/en/latest/errors.html#jax.errors.TracerBoolConversionError
Ran with jax 0.11.2 on Apple M1 Pro (CPU), Python 3.12.11; output as printed (raised while tracing, before anything runs; shown up to its documentation link).
Every array shape must be known while tracing. Keep the shape fixed and mask: jnp.where(x > 0, x, 0), or jnp.nonzero(x, size=k) with a fixed maximum.
import jax, jax.numpy as jnp
@jax.jit
def positives(x):
return x[x > 0] # how many? depends on the data
positives(jnp.array([1.0, -2.0, 3.0]))jax.errors.NonConcreteBooleanIndexError: Array boolean indices must be concrete; got bool[3] See https://docs.jax.dev/en/latest/errors.html#jax.errors.NonConcreteBooleanIndexError
Ran with jax 0.11.2 on Apple M1 Pro (CPU), Python 3.12.11; output as printed (shown up to its documentation link).
JAX arrays are immutable. .at[i].set(v) (also .add, .multiply, .min, .max) returns a new array; under jit it becomes an in-place write when the old array is dead.
import jax.numpy as jnp
x = jnp.zeros(3)
try:
x[0] = 1.0
except TypeError as e:
print("TypeError:", e)
x = x.at[0].set(1.0) # a new array
print(x)TypeError: JAX arrays are immutable and do not support in-place item assignment. Instead of x[idx] = y, use x = x.at[idx].set(y) or another .at[] method: https://docs.jax.dev/en/latest/_autosummary/jax.numpy.ndarray.at.html [1. 0. 0.]
Ran with jax 0.11.2 on Apple M1 Pro (CPU), Python 3.12.11; output as printed.
The list grew once, during tracing, and holds a tracer. Return values instead of appending; for logging at run time use jax.debug.print or jax.debug.callback.
import jax, jax.numpy as jnp
seen = []
@jax.jit
def f(x):
seen.append(x) # runs while tracing only
return x + 1
for _ in range(3):
f(jnp.ones(2))
print(len(seen), seen[0])1 JitTracer(float32[2])
Ran with jax 0.11.2 on Apple M1 Pro (CPU), Python 3.12.11; output as printed.
The global was read while tracing and baked into the compiled program as a constant. Pass anything that changes as an argument.
import jax, jax.numpy as jnp
scale = 2.0
@jax.jit
def f(x):
return x * scale # read once, while tracing
print(f(jnp.ones(2)))
scale = 10.0
print(f(jnp.ones(2))) # same shape: cached, still 2.0[2. 2.] [2. 2.]
Ran with jax 0.11.2 on Apple M1 Pro (CPU), Python 3.12.11; output as printed.
Same key, same numbers: a reused key silently correlates your dropout masks or initialisations. Split a fresh subkey for every use.
import jax key = jax.random.key(0) a = jax.random.normal(key, (3,)) b = jax.random.normal(key, (3,)) # same key: same numbers key, sub = jax.random.split(key) c = jax.random.normal(sub, (3,)) # fresh subkey: new numbers print(a); print(b); print(c)
[ 1.6226422 2.0252647 -0.43359444] [ 1.6226422 2.0252647 -0.43359444] [-2.4424558 -2.0356805 0.20554423]
Ran with jax 0.11.2 on Apple M1 Pro (CPU), Python 3.12.11; output as printed.
Each new length is a new signature: trace and compile again. Pad batches to a few fixed lengths (buckets) and log compiles while developing.
import jax, jax.numpy as jnp
@jax.jit
def f(x):
return jnp.tanh(x).sum()
batches = [jnp.ones(n) for n in [100, 100, 101, 102]]
jax.config.update("jax_log_compiles", True)
for x in batches: # a new length is a new signature
f(x)
print("cache size:", f._cache_size())Compiling jit(f) with global shapes and types (ShapedArray(float32[100]),). Argument mapping: (UnspecifiedValue,). Compiling jit(f) with global shapes and types (ShapedArray(float32[101]),). Argument mapping: (UnspecifiedValue,). Compiling jit(f) with global shapes and types (ShapedArray(float32[102]),). Argument mapping: (UnspecifiedValue,). cache size: 3
Ran with jax 0.11.2 on Apple M1 Pro (CPU), Python 3.12.11; output as printed (JAX's compile log, its per-phase timing lines left out).
Under JAX, out-of-bounds reads are clamped and out-of-bounds writes are dropped, with no error, because accelerators cannot raise mid-kernel. Check indices yourself, or use jax.experimental.checkify.
import jax, jax.numpy as jnp x = jnp.arange(5.0) print(x[10]) # no error: clamped to the last element print(x.at[10].set(99.0)) # no error: the write is dropped
4.0 [0. 1. 2. 3. 4.]
Ran with jax 0.11.2 on Apple M1 Pro (CPU), Python 3.12.11; output as printed.
out.block_until_ready() and leave out the first call, which includes tracing and compiling. The reverse mistake is a host sync every step: float(loss), loss.item(), printing or converting to NumPy forces Python to wait for the device and stalls the queue; log every N steps.donate_argnums, the step's outputs need fresh buffers while the inputs are still alive: briefly two copies of parameters and optimiser state. nnx.jit does not donate by default (flax 0.12.10, nnx/transforms/compilation.py:317-318: "If neither donate_argnums nor donate_argnames is provided, no arguments are donated"); write @nnx.jit(donate_argnames=("model", "optimizer")). On the running example the Compiler lab measured, from memory_analysis: 385.8 MB in all without donation, 376.6 MB with it, the difference being the 9.9 MB of parameters and Adam state that the outputs now reuse ("alias") measured. Here activations (366 MB of temporaries) dwarf the state, so donation saves 2.4%; for a 70B model the state is about 1.1 TB (section 5) and the second copy is what runs out of memory.precision=jax.lax.Precision.HIGHEST or jax.default_matmul_precision("float32") when comparing against PyTorch (JAX docs, default_matmul_precision).Answer each yourself first; the design questions have no single right answer, so say the constraint that decides it.
jax.jit do on the first call, and on the second?grad traces the function into a jaxpr, builds its forward-mode linearisation (JVP), and transposes the linear part to get the reverse-mode (VJP) program; that new program is then compiled like any other. The backward pass is therefore code the compiler can fuse and shard, not a replay of a log.P('data'), weights replicated, so XLA all-reduces the gradients. FSDP (ZeRO-3 style): weights also sharded on the 'data' axis, so XLA all-gathers each weight before use and reduce-scatters its gradient (on CPU, XLA does the last as an all-reduce and a slice). Tensor parallel: the first weight of the attention and of the MLP split by columns and the second by rows on a 'model' axis, so two all-reduces per block in the forward pass (8 for the running example's 4 blocks, measured in section 5). The model code does not change; the compiled program and its collectives do.dcn_data_parallelism setting), and leave pipeline parallelism out unless that network becomes the bottleneck.block_until_ready(); JAX dispatches asynchronously.jax_log_compiles (or jax_explain_cache_misses); varying shapes or a Python value passed as static recompiles every step.float(loss), .item(), printing or NumPy conversion every step stalls the pipeline; log every N steps.jit(f).lower(...).compile().as_text()) for unexpected all-gathers or all-reduces; a missing sharding constraint can replicate a large array.jax.profiler (XProf trace viewer) rather than guessing.jit with shardings (GSPMD) by default; jax.shard_map when you need per-device code and explicit collectives; never new pmap: since JAX 0.8.0 (2025-10-15) it is implemented over jit and shard_map and "in maintenance mode", and 0.10.0 (2026-04-16) removed the old implementation. pjit is deprecated in favour of jit; xmap was deleted in 0.4.31 (JAX changelog).src/read/check_defaults.py): LayerNorm epsilon is 1e-6 in Flax NNX and 1e-5 in PyTorch, and NNX's LayerNorm also defaults to use_fast_variance=True (variance as E[x2] − E[x]2, harmless on this model, lossy when the mean is large against the spread; child page PyTorch to JAX); jax.nn.gelu uses the tanh approximation by default, nn.GELU the exact form; optax's adamw defaults to weight decay 0.0001, PyTorch's AdamW to 0.01; nnx.Linear initialises its kernel with LeCun normal (truncated, fan-in) and PyTorch's Linear with Kaiming uniform; and the kernel is stored [in, out], the transpose of PyTorch's weight, so copied weights must be transposed. Set every one explicitly and copy the weights, and the running example's twins stay within 3 × 10-5 in loss over 500 steps and 10-3 over 4,000 (sections 0 and 8); what remains is summation order, compounding slowly. Then: matmul precision (on TPU the default precision for fp32 matmuls uses bf16 passes), reduction order, and dropout keys.Each child owns its subject in depth with its own measured examples; times are each page's own header.
This lab teaches the functional core of JAX from zero, on the running example: a 4-layer, 826,368-parameter character transformer written in PyTorch and in plain JAX from the same weights (Reading, section 0). Reading section 2 gave the overview; here every idea is run, counted and compared with PyTorch. Each code block below ran with jax and torch 2.14.1 on an Apple M1 Pro CPU (Python 3.12.11), and its output is pasted from that run. Counts, jaxprs, error messages and numerical differences are deterministic and transfer to any machine; the few timings are labelled and are rough.
jit, grad, vmap) does not run your Python on numbers. It runs it once on tracers, stand-ins that carry only a shape and a dtype, records every elementary operation into a small typed program called a jaxpr, and then interprets that program: compile it (jit), differentiate it (grad), or batch it (vmap). Everything else in this lab, the purity rules, the recompiles, the errors, follows from that.Traced with jax.make_jaxpr on an activation f32[32,128,128] (batch 32, 128 characters, width 128) and block 0's weights. Each equation is linked to its Python line through the source information JAX stores on every equation (source_info_util.user_frames); script src/xf/run_trace.py.
The problem it solves. PyTorch in eager mode runs each operation the moment Python reaches it, so the framework never sees your program as a whole and cannot optimise across operations (torch.compile exists to recover that view). JAX takes the opposite route: before doing anything, it captures the whole function as data.
How it works. When jax.jit(f) (or jax.make_jaxpr(f)) is called, JAX replaces each array argument by a tracer whose abstract value is a ShapedArray: shape and dtype, no numbers (printed f32[32,128,128]). Your Python then runs normally, but every jnp or lax call on a tracer is intercepted and appended to the jaxpr as one primitive (an elementary operation such as dot_general, add, exp) with its output's abstract value. Python itself (the variables, the helper functions, the for over q, k and v, the arithmetic on shapes) runs to completion and leaves no trace: only the array operations remain.
What to notice. Ten Python lines became equations, and the three projections, written once in a generator expression, appear three times. Shapes are fully known at every line, so a shape bug fails while tracing, before any compute. Python constants are folded in: / math.sqrt(dh) became div ... 5.656854152679443. jnp.tril and jnp.where appear as nested jit equations, because many jnp functions are themselves jitted functions with their own jaxpr inside. And jax.nn.softmax subtracts the row maximum under stop_gradient for numerical safety, so the max does not get differentiated.
What a tracer is, by transformation. Each transformation has its own tracer type. Printing the argument inside a function under each one (real output):
Under grad alone the tracer still holds the real value (the primal), so Python can look at it; under jit it holds only the abstract value. That is why a Python if on an array works under grad but fails under jit (section 2). Python scalars get a weak type: jax.typeof(2.0) is , the tilde meaning "defer to the other operand's dtype", so bf16_array * 2.0 stays bfloat16.
PyTorch counterpart: torch.fx.symbolic_trace and TorchDynamo also capture graphs, but Dynamo reads Python bytecode and can fall back to eager at a graph break; JAX's tracer sees only array operations and has no fallback. Compiling the jaxpr is the Compiler lab's subject.
The rule. While tracing, a value is either static (known to Python now: shapes, dtypes, Python numbers, arguments marked static_argnums) or dynamic (a tracer: known only when the compiled program runs). Python may branch and loop on static values freely; the branch taken is simply baked into the program. It cannot branch on a dynamic value, because there is no value yet. The real errors, from this run:
@jax.jit
def f_if(x):
if x.sum() > 0: # needs a Python bool from a tracer
return x
return -x
@jax.jit
def f_int(x):
return jnp.zeros(int(x.sum())) # a shape that depends on data
The second error is the deeper rule: no array may have a shape that depends on data, because XLA compiles for fixed shapes. Variable-length work is padded to a fixed size and masked.
The structured replacements, all primitives in the jaxpr:
jnp.where(c, a, b): both sides computed, then selected elementwise (a select_n). Cheap for small branches.jax.lax.cond(pred, true_fn, false_fn, x): both branches traced and compiled into one cond primitive; one runs. On the inputs [-1, -2, 0.5] it returned .jax.lax.scan(f, carry, xs): a loop with a carried state, compiled once. jax.lax.fori_loop with bounds known at trace time becomes a scan (seen in the jaxpr below); with traced bounds it becomes a while, which reverse-mode grad cannot differentiate.def body(i, c): return c * 0.5 + i # python for: for i in range(10): c = body(i, c) # lax.fori_loop(0, 10, body, c); lax.scan(step, c, jnp.arange(10)); lax.while_loop(cond, step, (0, c))
"Equations" counts the top-level jaxpr; "inside" adds the equations of nested bodies. All four return the same value. Script src/xf/run_trace.py.
Why it matters at model scale. The running example's forward pass loops over its 4 layers in Python, so the trace contains every layer. Written with lax.scan over stacked layer weights (the setup's apply_scan, same logits to the last bit), the traced program holds one layer whatever the depth:
Compile time grows with program size, which is why large-model code (MaxText, levanter) scans over layers; the compile-time side is measured in the Compiler lab.
Moved to JAX core, section 3 ("jit and its cache"): the cache key drawn as a diagram whose parts light up from the drill table this lab recorded (14 calls, traces and XLA compiles counted, JAX's own cache-miss explanations), the static against traced rule and the rules that fall out (bucket shapes, jit once outside the loop).
Moved to JAX core, section 3: the jitted function called three times whose counter ran once, the tracer leak, NumPy randomness and the clock frozen at trace time, and the safe ways to look inside (jax.debug.print, jax.debug.callback, returning values). The Reading tab's predict question shows the core of it.
A JAX array never changes after it is created; operations return new arrays. This is what makes purity cheap to check, and the compiler gets the in-place update back where it is safe (inside jit, and across steps with buffer donation, measured in the Compiler lab). The indexed-update API is x.at[index].set / add / multiply / min / max / get.
Two behaviours that differ from PyTorch:
x.at[[0, 0, 0]].add(1.0) adds 3 to x[0] (scatter-add). PyTorch's t[[0, 0, 0]] += 1 adds only 1, because it gathers, adds, then writes back; index_put_(..., accumulate=True) is the accumulating form.x[10] returned (clamped to the last element), x[-10] returned (clamped to the first), and x.at[10].set(99.0) silently did nothing. An error would need a host check on device data, so XLA clamps gathers and drops out-of-range scatters. PyTorch raised . Use .at[i].get(mode="fill", fill_value=...) to make out-of-range reads visible: x.at[[1, 7]].get(mode="fill", fill_value=-1.0) gave .Moved to JAX core, section 10 ("Random keys"): a stateful against a counter-based generator, split and fold_in, typed keys against the old PRNGKey, and the key-reuse run (two dropout masks from one key agreed on 100% of 4,096 positions, masks from split keys on 81.8%). That the same key gives the same numbers on 8 devices or a 2 × 4 mesh is in the Reading tab, section 8.
The problem. Transformations take and return arrays, but a model has dozens of parameters. PyTorch keeps them as attributes of nn.Module objects and gives you model.parameters() and state_dict() to walk them. JAX instead accepts any nesting of containers, a pytree, and flattens it to a list of leaves (the arrays) plus a tree definition (the structure) whenever a transformation needs to. jit, grad, vmap, optax and orbax all speak pytrees, so parameters, gradients, optimiser states and checkpoints share one shape.
What counts as a leaf. Lists, tuples, dicts, None and classes registered with JAX are containers; everything else is a leaf, including Python floats and strings. An unregistered class is a single opaque leaf, so transformations cannot see the arrays inside it. Flattening this object (real output):
obj = {"tuple": (1.0, 2.0), "none": None, "str": "adam", "opaque": Opaque(), # plain class holding an array
"pair": Pair(jnp.ones(2), jnp.zeros(2)), # @jax.tree_util.register_dataclass
"list": [jnp.ones(3)], "empty": {}}
jax.tree_util.tree_flatten_with_path(obj)
None and the empty dict contribute no leaves, the dict keys come out sorted, and the opaque object is one leaf. Flax NNX modules are registered, which is how nnx.split(model) returns a state pytree: for the running example's NNX twin it has .
tree_map. jax.tree.map(f, *trees) applies f leaf by leaf across trees of the same structure; jax.tree.map(lambda p, g: p - lr * g, params, grads) is a complete SGD step. If the structures differ, it refuses:
The plain-JAX model's parameters: nested dicts and a list. Click a node; leaves show their path (jax.tree_util.keystr), shape, position in jax.tree.leaves order, and the PyTorch name the setup maps them to.
The difference in one line. PyTorch differentiates the computation that just ran: loss.backward() walks the graph autograd recorded during the forward pass and adds gradients into each parameter's .grad. JAX differentiates a function: jax.grad(loss_fn) returns a new function that, given parameters, returns a gradient pytree shaped like them. There is no .grad attribute, no zero_grad() and no requires_grad; you choose what to differentiate with argnums.
loss, grads = jax.jit(jax.value_and_grad(loss_fn))(params, x, y) # JAX: one pure call # PyTorch on the same weights and batch: loss_t = loss_fn_torch(model, x, y); loss_t.backward() # fills p.grad for every parameter
Why the key biases stand out. Their true gradient is exactly zero: adding the same vector to every key adds the same number to every score in a row, and softmax ignores a constant added to a whole row. Both frameworks compute float noise around zero (about 2e-11 here), so their relative difference is meaningless and is left out of the "worst relative" figure. The setup's equivalence check explains why that noise still moves those biases during AdamW training (Reading, section 0 and the Training lab).
has_aux returns metrics next to the loss without differentiating them: jax.value_and_grad(loss_aux, has_aux=True) where loss_aux returns (loss, {"accuracy": ..., "max_logit": ...}) gave , and the gradient matched the plain one to . Forgetting has_aux:
Transformations compose. grad returns an ordinary function, so jax.grad(jax.grad(jnp.tanh))(0.5) is the second derivative: , against the formula −2 tanh(x)(1 − tanh²(x)) = . jax.jit(jax.vmap(jax.grad(f))) is the per-example gradient of section 9. In PyTorch, higher derivatives need create_graph=True.
jax.make_jaxpr(mlp)(p, x_one) # x_one: f32[128], one token jax.make_jaxpr(jax.vmap(mlp, in_axes=(None, 0)))(p, x) # x: f32[4096,128], 32 x 128 tokens; p shared
The problem. Many computations are easiest to write for one example: one sequence's loss, one query against one key, one sample's gradient. Batching them by hand means adding a leading dimension everywhere and getting every transpose right; a Python loop over examples is slow. jax.vmap(f, in_axes=...) does the rewrite for you: it traces f with batch tracers that remember which dimension is the batch, and replaces each primitive with its batched form through that primitive's batching rule. No loop survives into the program. in_axes gives the batched dimension of each argument (None for an argument shared by the whole batch); out_axes places it in the output.
One rule, different programs. The batching rule of dot_general looks at which inputs carry a batch dimension. The same one-line function dot(q, k) = q @ k on two vectors of 32 (one query, one key) becomes three different programs (real jaxprs):
Ordinary training needs the batch-mean gradient, but some methods need one gradient per example: differentially private SGD clips each example's gradient norm before averaging, and data-attribution methods score examples by their gradients. In PyTorch the plain way is a loop of backward() calls; torch.func.vmap with torch.func.grad ports JAX's approach. Here all four ways computed the 32 per-example gradients of the running example's loss (32 sequences of 128 characters, 826,368 parameters each, so of gradients):
def per_ex_loss(params, xi, yi): # one sequence: int32[128]
return loss_fn(params, xi[None], yi[None])
per_ex_grads = jax.jit(jax.vmap(jax.grad(per_ex_loss), in_axes=(None, 0, 0)))(params, x, y)
Why vmap wins here. The loop runs 32 small programs, each with matrix products of one sequence; the vmapped program runs one program whose matrix products carry the batch, which keeps the hardware busy and pays dispatch overhead once. The traced per-example gradient program has equations for one example and after vmap: the same program with batched shapes, not 32 copies.
Each dot is one sequence's gradient norm (the quantity DP-SGD clips). Their mean gradient equals the batch gradient (row above), because the loss is a mean over equally long sequences.
JAX's core is small. Each transformation is a trace object (an interpreter) with one method that matters, process_primitive. Every jnp or lax call ends in Primitive.bind, which hands the operation to whichever trace is current. Transformations nest by stacking traces: under jit(vmap(grad(f))), grad's trace handles an operation first and calls the operation again on its parent (vmap's), which calls it on jit's, which records it. Section 1's tracer table showed exactly that nesting.
Read at the pinned version (tag jax-v0.11.2, commit 32544801), verbatim with real line numbers; open each:
The same design at toy scale: a tracer that records operations into a program, and one interpreter loop given three different rule tables (evaluate, forward-mode derivative, batch). Scalars only, three primitives; checked against JAX on the same function.
Script src/xf/toy_tracer.py. What the toy leaves out: abstract values and shapes (JAX checks every equation's output type), many arrays and dtypes, reverse mode (JAX linearizes, then transposes the linear part), nested transformations, and compilation. Child page JAX core goes further into these files.
Each one ran in this lab's scripts; open for the message and the fix.
Transforms lab: built 2026-10-15 with jax 0.11.2, jaxlib 0.11.2, flax 0.12.10, torch 2.14.1, Python 3.12.11 on an Apple M1 Pro (CPU only). Scripts and their outputs in src/xf/ of this page's repository folder; source excerpts from jax-ml/jax at jax-v0.11.2.
jitYou call jax.jit(train_step) and the first call takes a second; every later call is fast. This tab opens that second up, on the running example's real train step (the tiny character model of the Reading tab: 4 layers, width 128, 826,368 parameters, a batch of 32 x 128 characters). Every count, size and memory figure below was produced here by the scripts in src/xla/, with JAX on an Apple M1 Pro, CPU only. Counts and memory are deterministic; times are rough and labelled.
jax.jit instead runs your Python once with placeholder values to record the whole function as a program, hands that program to a compiler (XLA), and from then on runs the compiled program. The nearest PyTorch analogue is torch.compile; section 9 compares them on the same model.Between your Python and the processor there are five forms of the same program. Each has a name you will meet in error messages and docs, and each can be printed:
dot_general, add, reduce_sum) applied to typed variables. Produced by tracing: running your function with tracers, stand-in values that carry only a shape and dtype and record every operation applied to them.The text in the box is the real output for one MLP sub-block of the model (x + mlp(layer_norm(x)), block 0), small enough to read; the counters are for the whole train step (forward, backward and AdamW update), whose texts run to hundreds of kilobytes. Paths were stripped from the printed texts.
The train step is three programs in one: the forward pass, the backward pass that jax.grad derives from it, and the optimiser update. Counting each separately (forward only, then forward and backward, then the whole step) shows something PyTorch users rarely see:
The problem. Run the MLP sub-block eagerly and every equation is its own kernel: it reads its inputs from memory and writes its output back, even when the next equation immediately reads that output again. On accelerators, memory traffic, not arithmetic, is usually the bottleneck for this kind of elementwise work. Fusion merges a chain of operations into one kernel so intermediate values stay in registers or on-chip memory.
Real data: the 29 equations of the block's jaxpr, and the 4 kernels of its optimised HLO. Each equation is placed in the kernel that computes it, matched by the operation name and source line XLA keeps in its metadata (src/xla/fusion_demo.py). "Bytes moved" before fusion is derived: every equation reads its inputs and writes its output once (); after fusion it is XLA's own cost_analysis()["bytes accessed"] (). Hover a chip for the equation.
dot). Counted are the top-level instructions that do work; the small add or max bodies a reduction applies through to_apply= ( here) run inside their caller's kernel and are not counted (an earlier version of this lab counted them and said 1,057). Why not far fewer: the optimiser updates 69 separate arrays, each with its own small chain, and XLA:CPU does not merge the chains of different arrays into one kernel. That is the problem PyTorch's foreach and fused optimisers solve by hand.XLA optimises by running passes, each a rewrite of the whole HLO program: algebraic simplification, common-subexpression elimination (the largest single drop in this step: the gradient norm is computed twice, once inside clip_by_global_norm and once for logging), dead-code elimination, layout assignment, fusion (the cliff, section 2), then copy insertion and buffer assignment (section 4). XLA_FLAGS=--xla_dump_to=DIR --xla_dump_hlo_pass_re=.* writes the program after every pass that changed it.
Moved to XLA and compilation: the pass pipeline counted pass by pass (section 3, with its Pass diff viewer tab), how fusion decides (section 4) and buffer assignment (section 6).
After fusion, XLA's buffer assignment gives every value in the program a place in memory, letting values whose lifetimes do not overlap share the same bytes. compiled.memory_analysis() reports the result before anything runs: arguments (what you pass in), outputs, temp (everything in between, mostly the activations the backward pass needs) and alias (outputs written into input buffers). PyTorch has no ahead-of-time equivalent; you learn its peak from torch.cuda.max_memory_allocated() after running.
Donation. A train step takes the parameters and optimiser state and returns new ones of exactly the same shapes. Without help, XLA must keep the inputs intact (you might use them again), so the outputs need fresh buffers: two copies of the training state exist at once. jax.jit(step, donate_argnums=(0, 1)) is a promise that you will not touch arguments 0 and 1 again, so XLA may write the outputs into their buffers. The running example's make_train_step donates both.
On the running example, memory_analysis() gives 385.8 MB in all without donation and 376.6 MB with it, because the outputs now reuse ("alias") the 9.9 MB of parameters and Adam state, while the activations (366 MB of temporaries) dwarf the state. How buffer assignment plans every byte before the step runs is XLA and compilation, section 6.
Ran here (src/xla/debug_tools.py); output as printed. A donated array is deleted after the call; donation XLA cannot use is ignored with a warning.
donate_argnums = 0, train_utils.py:242 at the pinned commit). Flax's nnx.jit does not donate unless told: its docstring says "If neither donate_argnums nor donate_argnames is provided, no arguments are donated" and recommends @nnx.jit(donate_argnames=("model", "optimizer")) (flax/nnx/transforms/compilation.py:317, flax 0.12.10).The problem. The backward pass needs the forward pass's intermediate values (the attention scores, the GELU inputs, ...). Keeping them all is the "temp" bar above, and it grows with batch, sequence length and depth. Rematerialisation (jax.checkpoint, alias jax.remat; PyTorch's torch.utils.checkpoint) keeps less and recomputes the rest during the backward pass. A policy says what to keep:
nothing_saveable: keep only the wrapped function's inputs; recompute everything (the default for jax.checkpoint).dots_saveable: keep every matmul output, recompute the cheap elementwise work around them.dots_with_no_batch_dims_saveable: keep matmuls against weights, but not the batched ones (attention's q @ k and p @ v, whose outputs are the large B x H x T x T tensors).Production code names its policies by what they keep: MaxText's default is remat_policy: 'full' (recompute everything), with a ladder of options from 'minimal' to 'full' that its config describes as a "trade-off between speed (fastest to slowest) and HBM usage (highest to lowest)", including variants that offload saved tensors to host memory (configs/base.yml:489-492).
nothing_saveable, temp memory is with 3 blocks wrapped and with all 4: no saving, while the 4th block's recompute still costs FLOPs. The backward pass starts at the last block: its activations are needed the moment the forward pass ends, so whether they were kept or recomputed, they are all alive at the peak. Remat pays where activations wait a long time to be used, which is the early layers.The running example's apply loops over its 4 layers in Python. Tracing runs that loop, so the jaxpr holds 4 copies of the block, and XLA compiles 4 copies. apply_scan stacks the layers' weights into arrays with a leading layer axis and runs one traced block under jax.lax.scan, which XLA compiles once as a loop (a while in HLO). Same logits (difference 0.0, checked by setup). The cost of unrolling is compile time and program size, and it grows with depth:
cost_analysis() counts a loop body once. For the scan version of the train step it reports , against for the unrolled one: the same arithmetic, with the 4 layers counted as one. MFU calculations from cost_analysis on scanned models must multiply by the trip count.A jitted function keeps an in-memory cache of executables keyed on the signature: argument shapes, dtypes, shardings and the values of static arguments. A new signature means trace, lower and compile again (the Transforms lab counts recompiles). That cache dies with the process. The persistent compilation cache writes executables to disk so the next process can skip XLA:
jax.config.update("jax_compilation_cache_dir", "/path/to/cache")
jax.config.update("jax_persistent_cache_min_compile_time_secs", 0.0) # default 1.0: faster compiles are not saved
jax.config.update("jax_persistent_cache_min_entry_size_bytes", -1) # -1: no size threshold
jax_compilation_cache_dir (other options at their defaults) and rerun the script. Is the running example's train step loaded from the cache?jax_persistent_cache_min_compile_time_secs defaults to 1.0 (pinned source, section 10): programs that compiled faster are never written (its help text: "This threshold can be raised to decrease the number of entries written to the cache"). Large models compile for minutes on TPU, so the default is right there; small experiments need the threshold lowered.Inside jit, your Python ran once, during tracing; what runs later is XLA's program. So the PyTorch habits (a print, a breakpoint, checking a tensor for NaNs after each line) need JAX equivalents, each of which puts something into the compiled program:
print against jax.debug.printPython's print fired once, while tracing, and shows a tracer; jax.debug.print became part of the program and fires on every call with the real value.
checkify: errors from inside the programAccelerators cannot raise an exception mid-kernel, so a check becomes an error value returned next to the output, which you inspect on the host.
jax_debug_nans: find the operation that made the NaNsWhen a jitted function returns NaNs, JAX reruns it de-optimised, operation by operation, and raises at the first one that produced it. Slow; turn it on to hunt, off to train.
debug.print adds a call back into Python (a host round trip that also orders the program); checkify adds the checks and the error plumbing but stays on the device. All examples ran here with JAX ; outputs as printed (src/xla/debug_tools.py).
XLA_FLAGS=--xla_dump_to=DIR writes, per compiled module, the HLO before and after optimisation, the buffer assignment, a memory-usage report and, on CPU, object files; add --xla_dump_hlo_pass_re=.* for one file per pass (section 3). The dump of the MLP block alone: . Dumps contain absolute file paths in their metadata: strip them before sharing.jax.config.update("jax_log_compiles", True) logs every compilation; "jax_explain_cache_misses" logs why a cache missed (which argument's shape or static value changed). The first tool to reach for when a step is slow because it recompiles.with jax.profiler.trace(DIR): (or start_trace / stop_trace) records a timeline you open in XProf, the tool behind TensorBoard's profiler, or in Perfetto; jax.profiler.StepTraceAnnotation marks training steps. On GPU the trace has rows for the GPU streams, and XProf covers "activity on GPU and TPU" (JAX profiling docs, read 2026-10-15). On this CPU the timeline shows host threads running XLA:CPU's kernels, named after the fusions in the optimised HLO, so a slow kernel can be traced back to the operations it fused. The files are named after the machine: scrub the host name before sharing.torch.compile, on the PyTorch twinThe running example's PyTorch twin (same weights, same batches) under eager mode and under torch.compile (TorchDynamo captures graphs from Python bytecode, TorchInductor generates kernels: C++ on CPU, Triton on GPU). How Dynamo's guards, graph breaks and recompiles behave is taught on torch.compile from the user's side; here, only the comparison.
Dynamo splits the function at the branch (2 graphs, 1 graph break) and runs the branch in Python: it always works, sometimes slowly. JAX's tracer has no value to branch on, so it refuses; you rewrite the branch as data (jnp.where, lax.cond). One program or an error, never a silent fallback. Ran here (src/xla/torch_compile.py), torch .
Every stage above is a few functions in JAX's Python, at the pinned version jax-v0.11.2 (commit 32544801e261, 2026-09-17). XLA itself is C++ in openxla/xla; JAX only builds the module and asks for an executable. The full walk through these files is on the child page XLA and compilation.
jax.block_until_ready(out) before stopping the clock: JAX dispatches asynchronously, so without it you time the dispatch, not the work.jax.jit(step, donate_argnums=(0, 1)); with Flax NNX, nnx.jit(donate_argnames=("model", "optimizer")), since nnx.jit donates nothing by default.jax_persistent_cache_min_compile_time_secs when iterating on small models.jax.debug.print adds a host callback to every step; jax_debug_nans checks every output and reruns de-optimised on a hit. Both belong in a debugging run, not a training run.jax.jit(f)(x) and the result?f with abstract tracers into a jaxpr, lower each primitive to StableHLO, hand the module to XLA, which optimises (simplification, CSE, layout assignment, fusion, buffer assignment) and generates code; cache the executable. Then dispatch it asynchronously and return arrays whose values arrive later.memory_analysis() of the compiled step before running anything: are the state arguments donated (alias equal to the state size)? Is temp dominated by activations? Then remat (a policy, and which layers), smaller micro-batches with gradient accumulation, sharding the state (FSDP), and offloading saved activations or optimiser state to host memory.jit differ from torch.compile?jit traces with abstract values and produces one whole program or an error; torch.compile reads bytecode, captures what it can and falls back to Python at graph breaks, guarded by runtime checks that trigger recompiles. JAX demands purity up front and gets whole-program compilation; PyTorch keeps eager semantics and compiles opportunistically.Scripts and outputs: src/xla/ (see its README). Every figure on this tab is regenerated by those scripts and embedded by make_data.py; check_data.py confirms the page holds exactly that data.
JAX gives you arrays and transformations; the libraries around it give you layers (Flax), optimisers (optax), checkpoints (orbax) and data loading (grain). This lab takes each one from zero for someone who knows PyTorch, runs it on the page's running example, and checks the JAX version against the PyTorch twin number by number.
The running example is the tiny character-level transformer of the Reading tab: 826,368 parameters, 4 layers, width 128, trained on TinyShakespeare, written in PyTorch, in Flax NNX and in plain JAX with optax, all three starting from the same weights and reading the same batches (setup in src/data/README.md). Everything below ran on an Apple M1 Pro CPU with jax 0.11.2, flax 0.12.10, optax 0.2.8, orbax-checkpoint 0.12.7, grain 0.2.18, equinox 0.13.8, dm-haiku 0.0.17 and torch 2.14.1. Losses, differences and file sizes are deterministic; times are rough (shared machine, 4 threads, low priority) and say nothing about accelerators.
The problem. In PyTorch a layer is an object that owns its weights and changes them in place, and loss.backward() finds them through the object. JAX's transformations (jit, grad, vmap) work on pure functions of arrays: they only see what is passed in as arguments, as a pytree (any nesting of lists, tuples and dicts whose leaves are arrays; the Transforms lab builds them from zero). So every JAX neural-network library has to answer one question: how does a model's state get in and out of a pure function? There are four answers.
| Library | Where the weights live | How you run it | Linear weight layout | Same block, same weights: max difference from PyTorch |
|---|
The running example's transformer block (pre-LayerNorm attention and MLP, 198,272 parameters) written in each library, loaded with block 0 of the PyTorch model after 500 training steps, run on the embeddings of training batch 0 ([32, 128, 128]); the largest output is about 2.1, so a difference of 8e-7 is float32 rounding measured (src/train/frameworks.py).
nnx.splitThe MLP of the code below; each array is a square whose area is proportional to its number of elements (the 128 x 512 kernel is 65,536, the counter is 1).
An nnx.Module is a normal Python object, built eagerly like an nn.Module; its weights are nnx.Param attributes and other state (counters, batch-norm statistics, RNG streams) is any other nnx.Variable. To cross into a JAX transformation it is split: nnx.split(model) returns a graphdef (the structure: classes, attribute names, shapes, no arrays; static and hashable, so it can key the compile cache) and a state (a pytree of the arrays). nnx.merge(graphdef, state) builds the object back. nnx.jit, nnx.grad and the other lifted transforms do the split before the call and the merge after, and copy any mutation (an updated counter, new weights) back into your object, which is why NNX code reads like PyTorch.
The same thing written by hand shows what nnx.jit automates: only the state crosses the jax.jit boundary, and the graphdef is closed over as a constant.
Source at flax v0.12.10: class Module(Pytree) in flax/nnx/module.py:54 (a Pytree, pytreelib.py:510); split in graphlib.py:2268, which calls flatten(node) at line 2343 to walk the object graph and returns graphdef, *states.
Flax Linen modules are dataclasses that hold no weights: params = model.init(key, x) traces the model once to create a nested dict, and model.apply(params, x) runs it. Most JAX code written before 2025 looks like this; Flax says Linen will not be deprecated soon but recommends NNX for new code (quoted in the Reading tab). Equinox makes the model itself a pytree (a frozen dataclass whose array fields are leaves), so jax.jit and jax.grad take the model directly; its layers act on one example, so you jax.vmap over the batch, and its Linear.weight is [out, in] like PyTorch. Haiku (DeepMind) turns a function that creates modules into a pure (init, apply) pair with hk.transform; DeepMind recommends Flax for new projects and Haiku is in maintenance mode (see the Tool map). Pick a library to compare with PyTorch:
nnx.Rngs, filters and the Linen bridge; the Tool map has each library's status and dates.The problem. torch.optim.AdamW is an object that holds the moment estimates and writes into the parameters in step(); parameter groups carry per-group settings such as "no weight decay on biases", and a separate scheduler object changes the learning rate. Under jit nothing may be mutated, so optax splits the optimiser into data and functions.
How it works. An optax GradientTransformation is two pure functions: init(params) returns the optimiser state (a pytree, for Adam the step count and the two moment trees), and update(grads, state, params) returns (updates, new_state). You add the updates yourself with optax.apply_updates(params, updates), a plain sum. Bigger optimisers are optax.chain(...) of small transformations, and that is literally how optax.adamw is written: chain(scale_by_adam(b1, b2, eps), add_decayed_weights(weight_decay, mask), scale_by_learning_rate(learning_rate)) (alias.py:724-727 at optax v0.2.8). A mask (a pytree of booleans, or a function returning one) replaces parameter groups, and a learning-rate schedule is just a function of the step count.
Both libraries implement decoupled weight decay (Loshchilov and Hutter). PyTorch shrinks the weights first, then takes the Adam step: param.mul_(1 - lr * weight_decay), then param.addcdiv_(exp_avg, denom, value=-step_size) with denom = sqrt(v) / sqrt(1 - b2^t) + eps (torch/optim/adam.py:419, 544-546, torch 2.14.1). optax adds weight_decay * p to the Adam direction and multiplies the sum by -lr (transform.py:300, _adding.py:72-73). Same algebra, different rounding order. To test only the optimisers, both were fed the same 50 gradients: the running example's real gradients on training batches 0 to 49, all taken at the initial weights.
The defaults are not the same. Relying on either library's defaults gives a different optimiser:
| Setting | torch.optim.AdamW | optax.adamw | Effect if a port keeps the default |
|---|---|---|---|
| weight_decay | 0.01 (adamw.py:26) | 1e-4 (alias.py:605) | |
| which tensors decay | every tensor in the group (biases and LayerNorm too, unless you build groups) | every leaf, unless mask is given | the running example decays only its 25 two-dimensional weight matrices, so both sides need it written out |
| betas, eps | (0.9, 0.999), 1e-8 | b1 0.9, b2 0.999, eps 1e-8, eps_root 0 | the same; the running example uses b2 = 0.95 on both |
| gradient clipping | clip_grad_norm_ scales by max_norm / (norm + 1e-6) (clip_grad.py:164) | clip_by_global_norm scales by max_norm / norm when norm >= max_norm (_clipping.py:101-105) | about one part in a million: float32 rounding size in float32; in float64 it is visible (the 100-step loss gap falls from 5.5e-8 to 1.4e-8 with PyTorch's formula, child page PyTorch to JAX) |
| learning-rate schedule | a LambdaLR object, stepped after opt.step() | a function of optax's own update count, starting at 0 | the same values when written as the same function (common.lr_at) |
Eight numbers from the running example (six entries of the first MLP weight, two LayerNorm scales) and their real gradients over the first six steps go through the chain you build. The page re-implements each transformation in JavaScript; src/train/check_train.mjs compares it with optax 0.2.8's own output for every combination (). Clipping uses the norm of these eight gradients alone.
optax.MultiSteps, an exponential moving average of weights is optax.ema; the child page The JAX training stack goes through them.Moved to PyTorch to JAX: section 1 steps through the root's real model_torch.py and model_jax.py side by side, the differing lines highlighted, one caption per difference (mutable modules against pure functions, implicit RNG against keys, .grad against returned gradients, optimiser state, eager against traced).
The seven pitfall runs this lab trained (a missing transpose, the LayerNorm epsilon, the tanh GELU, optax's default b2, Flax's default initialisers and others, 300 steps each from the PyTorch twin's weights) teach three things: a mistake need not make training worse, only different, so a falling loss proves nothing about a port; forward-pass mistakes show at step 0, and one batch of logits from copied weights catches them all; optimiser mistakes are invisible at step 0 and need a one-step test on the same gradients (section 2).
Moved to PyTorch to JAX: its Divergence hunter tab replays these seven runs (marked "root") with ten more, each against the ladder of tests that catches it; section 2 lists every default that differs.
Top: training loss every 10 steps (the curves overlap; thin dashes are PyTorch, the solid line JAX) and validation loss every 250 steps (dots). Bottom, log scale: the largest absolute difference in training loss within each 10-step window. measured
The setup checked 500 steps. Here the three implementations run steps side by side from the same initial weights on the same batches (the first 500 batches are the setup run's, and steps 0 to 499 reproduce its losses to within , the 6-decimal rounding of the stored values). Same hyperparameters as the setup: AdamW, peak learning rate 1e-3 after 50 warmup steps and then constant, weight decay 0.1 on weight matrices, clipping at 1.0 (src/train/run_twin_long.py).
Both frameworks compute the same function, but their matrix-multiply kernels, fusions and reductions add the same numbers in different orders, so every step differs in the last bits of float32. Training is a chaotic iteration: each step's output is the next step's input, and small differences grow. The difference in training loss first exceeds 1e-5 at step and 1e-4 at step , and never reaches 1e-3 in steps (largest , in the last 500), yet the validation losses at the end are (PyTorch), (plain JAX) and (NNX). Plain JAX and NNX lower to nearly the same XLA program, so they stay closer to each other (largest gap ) than either does to PyTorch. The validation loss bottoms out at near step and then creeps up in all three: by step 4,000 each character of the 1 MB training text has been seen about 16 times (4,000 x 4,096 / 1,003,855 derived), the start of overfitting, identical in both frameworks.
| step | weights apart (all but key biases) | key biases apart | largest key bias | logits apart (val batch 0) | largest logit |
|---|
PyTorch against plain JAX, every 500 steps; all values are maximum absolute differences measured.
The key biases are a lesson in Adam. The bias of the key projection has a true gradient of exactly zero: adding the same vector b to every key adds the same number q·b to every attention score in a row, and softmax ignores a constant added to a whole row. Both frameworks compute about 2e-11 of float noise for it. They drift because nothing restores them, not because the steps are large: with no true gradient and no weight decay, Adam's tiny steps on that noise, in a direction that differs between frameworks, add up instead of being corrected. While the gradient is far below Adam's eps (1e-8) the update is about lr × g / eps, roughly 450 times smaller than the learning rate for noise near 2e-11; at step 0, where clipping also shrinks the gradient, the measured key-bias update is 2.3e-10 against a learning rate of 2.0e-5 (child pages PyTorch to JAX and The JAX training stack). Accumulated, that is still enough to make the key biases the weights furthest apart for the first 2,000 steps or so, while being unable to change the outputs. Later the ordinary weights catch up as the chaos compounds: by step 4,000 they differ by up to (after moving up to from their initial values) and the logits by on a largest logit of . Two runs of one model end at different weights that are equally good: what to compare across frameworks is the loss, not the weights.
Median and 10th to 90th percentile over steps 10 onward; the first step includes tracing and compilation for JAX. Measured on Apple M1 Pro (CPU), shared machine, 4 threads, low priority (the 1-minute load average reached during this run, from other jobs), so these say nothing about accelerators or about which framework is faster; on a CPU this small model is dominated by fixed per-operation costs. The Compiler lab looks at what XLA did to the step.
The problem. A long run is preempted; you need its weights, its optimiser state and its place in the data, written without stalling training, and restorable even onto a different number of devices. PyTorch's torch.save(model.state_dict()) writes one file from one process; torch.distributed.checkpoint (DCP) is the sharded, multi-process path (Distributed PyTorch covers it).
How it works. orbax saves any pytree. A CheckpointManager numbers checkpoints by step, keeps the last few and writes asynchronously: save() copies the arrays off the device and returns, and a background thread writes them while training continues. Arrays are stored in a TensorStore format (OCDBT, one key-value database per process), and each process writes only the shards it holds. Restoring takes a target with shapes, dtypes and shardings, so a checkpoint saved on one layout can be loaded onto another. Source at orbax v0.12.7: enable_async_checkpointing: bool = True is the default (checkpoint_manager.py:394); save at line 1334, restore at 1671, wait_until_finished at 2054.
Three separate Python processes (src/train/ckpt_resume.py): one trains steps without stopping; one trains steps, saves {params, opt_state} and the grain data iterator in one orbax checkpoint and exits; a third restores both and trains the rest. The final parameters and Adam moments ( arrays) are compared with np.array_equal. measured
Parameters are 826,368 float32 numbers (3.3 MB) and AdamW keeps two more trees of the same size, so about 9.9 MB of arrays; the three large OCDBT data files hold them. The data/ item is grain's iterator state: {"next_index": 100}.
On 8 simulated CPU devices (a 2 x 4 mesh, the Sharding lab explains meshes), the running example's weights were placed with the two-dimensional ones split over both mesh axes: blocks[0].mlp.fc1.w, global shape [128, 512], becomes shards of under P('data', 'model'). orbax saved them and restored them twice: onto an 8-way split of the other axis (P(None, 'x'), shards ) and onto a single device. Every one of the arrays came back equal both times measured (src/train/ckpt_sharded.py). The arrays and the collectives on simulated devices are real; the write speeds are not those of a pod.
The problem. Resuming the weights is not enough: if the data loader restarts its epoch, the model sees some batches twice and others never, and the resumed run is no longer the run you planned. A PyTorch DataLoader does not save its position by default (the separate torchdata package adds a StatefulDataLoader ("a drop in replacement for torch.utils.data.DataLoader that implements state_dict and load_state_dict methods, enabling mid-epoch checkpointing") for this).
How it works. grain builds a pipeline from a random-access source (anything with __len__ and __getitem__) and transformations that are pure functions of the record index and a seed: shuffling is a fixed permutation, not a buffer. So the whole state of an iterator is a small record (MapDataset.shuffle maps each position to a shuffled index with index_shuffle: dataset.py:649, shuffle.py:68, grain v0.2.18), here {"next_index": 100}, which orbax saves next to the weights. Multi-process loading (grain.DataLoader with workers, or mp_prefetch) repeats the same stream on a rerun with the same worker count, but changing the worker count keeps it only if the batches are formed before the work is shared out: MapDataset.batch before to_iter_dataset gave the same batches with 0, 2 and 4 workers, while batching after to_iter_dataset, a filter before mp_prefetch, or a Batch operation in grain.DataLoader lets each worker batch its own share, so the batches depend on the worker count. Iterator state does not transfer across worker counts either: a 2-worker state loaded into a 0-worker pipeline fails with KeyError: 'next_index' (grain 0.2.18, measured on the child page The JAX training stack).
From src/train/ckpt_resume.py: the training text cut into non-overlapping windows of 129 characters, shuffled once with seed 0, batched by 32: batches an epoch. The checkpoint at step 100 was taken in the middle of the first epoch; the resumed process's first three losses were , the uninterrupted run's steps 100 to 102 were measured.
The problem. Matmuls in 16-bit floats run faster and halve activation memory, and TPUs and recent GPUs are built for bfloat16 (8 exponent bits like float32, so the same range, but only 8 significant bits instead of 24). The catch is the update: a weight near 1.0 can only take bfloat16 values 2-7 = 0.0078 apart, so an Adam step of about the learning rate (1e-3) rounds away to nothing.
How it works. Keep a float32 master copy of the weights and the optimiser state; cast a bfloat16 copy for the forward and backward pass; the gradient of a cast is a cast back, so the gradients reach the optimiser in float32. PyTorch does this with torch.autocast; in JAX it is written out, usually as a policy naming three dtypes (params, compute, output). DeepMind's jmp library is the reference implementation of such policies; it has had no release since 0.0.4 (2023-01-30, see the Tool map) and the libraries carry the policy themselves: NNX layers take dtype (compute) and param_dtype arguments, and MaxText's default config has dtype: "bfloat16" with weight_dtype: "float32" (base.yml:128, 202, main on 2026-10-15). Loss scaling is only needed for float16, whose range is narrow; bfloat16 does not need it.
What happened. With a float32 master copy, bfloat16 compute ends at a validation loss of against in float32, a difference under 0.001. Without the master copy the run still trains, to , but of the LayerNorm scale entries never moved from 1.0 in 300 steps: each Adam step of about 1e-3 is below half the bfloat16 spacing at 1.0 (2-7/2 = 0.0039) and rounds away derived. Weights that sit near 0.02 still move, because the spacing shrinks with the value; the failure is silent and selective. Memory: weights plus AdamW state take MB in float32 and MB in bfloat16; the master recipe keeps the float32 MB and adds a bfloat16 copy of the weights (1.7 MB) while the step runs. The saving that matters at scale is in activations, which this tiny model does not show.
| Variant | validation loss at 300 | weights + optimiser state | LayerNorm scales that never moved |
|---|
Plain-JAX twin, same weights and batches; f32 everything float32; bf16 + f32 master the policy above; bf16 everywhere weights and Adam moments stored in bfloat16 with no master copy. Here the whole forward pass runs in the compute dtype, LayerNorm and softmax included; the loss is taken in float32 (src/train/mixed.py) measured. On a CPU bfloat16 is emulated, so no speed is reported.
Linear.weight is [out, in]; Flax's kernel is [in, out]. Non-square matrices fail loudly, square ones load silently wrong: 16 of the running example's 25 weight matrices are 128 x 128. Check logits against PyTorch on one batch before training (section 4).use_fast_variance=True computes E[x2] − E[x]2; harmless on this model, so the twins leave it on), GELU (exact against tanh), initialisers (kaiming-uniform against lecun-normal), AdamW weight decay (0.01 against 1e-4) and its scope (groups against mask) all differ. Write every one of them explicitly on both sides.frameworks.py called eqx.filter_jit(jax.vmap(model)); Equinox warned that the callable returned by jax.vmap is not a pytree, so the model's arrays become constants baked into the compiled program and would get no gradient. Pass the model as an argument: eqx.filter_jit(lambda m, x: jax.vmap(m)(x))(model, x).wrt in nnx.Optimizer.valuevariable.value; use variable[...] for arrays (or get_value() and set_value()):init builds the state pytree, update returns updates and a new state, and you apply them. That makes it composable (chain), jittable and shardable like any pytree; parameter groups become masks and schedulers become functions of the step.jax.jit (the graphdef is static, part of the cache key), merges inside, and writes any changed state back into your Python objects after the call.Notes, scripts and outputs for this tab: src/train/ (README, viz_ideas.md, the scripts named in each section and their JSON in out/).
Sharding the JAX way, run for real. The running example (the 826,368-parameter character LM of the Reading tab) is laid out over a mesh of 8 devices six different ways; for each, the compiler's own output says which collectives it inserted, how many bytes they move, how much memory each device holds, and whether the loss still matches one device.
XLA_FLAGS=--xla_force_host_platform_device_count=8, jax 0.11.2). The compiled HLO, the collectives XLA inserted, the per-device shapes, memory_analysis() and the losses are real and deterministic. Speeds are not: a "collective" between simulated devices is a memory copy, nothing like ICI or NVLink, so no timing on this tab says anything about a TPU. One more difference matters and is shown below: XLA's CPU pipeline lacks two collective optimisations that the GPU pipeline runs, so a few results differ from what a GPU or TPU compile would give.Something must say which device holds which piece of every array. In PyTorch that is the wrapper you choose (DDP, FSDP2, tensor-parallel layers) or a DTensor's placements; in JAX it is three small objects. A Mesh: jax.make_mesh((2, 4), ('data', 'model')) puts the 8 devices in 2 rows and 4 columns (PyTorch: init_device_mesh("cuda", (2, 4), mesh_dim_names=("dp", "tp"))). A PartitionSpec: on a [128, 512] weight, P(None, 'model') splits the 512 columns in 4 and copies the result along data (PyTorch: placements [Replicate(), Shard(1)], one per mesh dimension instead of one per array dimension). A NamedSharding(mesh, spec), attached with jax.device_put: the array stays one logical array whose shards live on different devices.
The picture is on Sharding and scale, section 1 ("One weight, six PartitionSpecs": which block of the running example's [128, 512] weight each of the 8 devices holds, with jax.debug.visualize_array_sharding's own output). This lab uses those objects from section 2 on.
Two kinds of mesh axis, and a default that changed. A mesh axis has a type. On an Auto axis the compiler is free to choose shardings for everything you did not annotate (section 2). On an Explicit axis the sharding is part of the array's type, visible in jax.typeof(x) and checked while tracing; ambiguous cases are errors instead of compiler choices. In jax 0.11.2 jax.make_mesh creates Explicit axes unless told otherwise, while the jax.sharding.Mesh constructor still defaults to Auto (run here: ; source in section 7). The JAX changelog announced the switch in 0.8.1 ("Default axis_types of jax.make_mesh will change in JAX v0.9.0"), and the JAX sharding guide now says "By default, all mesh axis types are AxisType.Explicit". Older tutorials that call make_mesh and then rely on the compiler choosing were written for Auto: pass axis_types=(AxisType.Auto,) * 2 to get that behaviour. Every compile on this tab says which it used.
How it works. You write the single-device program and annotate some arrays: the inputs (by passing sharded arrays, or in_shardings to jax.jit), the outputs (out_shardings), and if you need to, a few intermediates with jax.lax.with_sharding_constraint(x, sharding). The compiler then does two jobs. Sharding propagation gives every other array a sharding, by pushing the known ones through each operation (a matmul whose input rows are split on data produces output rows split on data). The SPMD partitioner then rewrites the program into the one program every device runs on its own shard (SPMD: single program, multiple data), and wherever an operation needs data laid out differently from how it is, inserts a collective: an operation in which a group of devices exchange data. The design is GSPMD (Xu et al. 2021); since JAX 0.7.0 the propagation step is done by default by its successor Shardy, and both hand over to the same partitioner (XLA's source shows the switch, section 7). PyTorch has no counterpart for whole programs: DTensor decides operator by operator at run time, and torch.compile does not re-plan the communication.
The cost. You do not see the communication in your code. It appears only in the compiled program, so checking it is part of the job: jax.jit(f).lower(*args).compile().as_text() and search for all-reduce, all-gather, reduce-scatter, all-to-all, collective-permute. That is exactly how every number on this tab was obtained.
Read the playground like this. Three rules explain almost every row. (1) If both operands are split along the dimension that is summed over (x columns and W rows on the same axis: P(None,'model') @ P('model',None)), each device computes a partial sum and the compiler adds them with an all-reduce: this is Megatron's row-parallel layer. (2) If one operand is split along the summed dimension and the other is not, the compiler all-gathers the split one first. (3) If you ask for an output layout the matmul does not produce, it adds an all-gather (to replicate), an all-to-all (to move a split from one dimension to another) or a collective-permute (to swap which device holds which block). Left to itself ("compiler's choice"), it picks an output layout that needs no communication whenever one exists.
The same matmul with Explicit axes. On an Explicit mesh the shardings are in the types and the rules are checked while tracing (run here, the result types and messages pasted from the run):
| x | W | result of x @ W |
|---|
The Megatron row-parallel case, which Auto mode quietly turns into an all-reduce, is a type error in Explicit mode until you say what the output should be (jnp.matmul(x, w, out_sharding=P('data', None))); jax.reshard(x, spec) changes an array's sharding on purpose (). Explicit mode trades convenience for no surprises. MaxText offers both and defaults to Auto (shard_mode: "auto" # can be either auto or explicit, configs/base.yml line 682 at main 1a95d1e5, 2026-10-15).
x is the embedded batch 0 of the running example ([4096 tokens, 128]), W is blocks.0.mlp.fc1.w ([128, 512]). Choose a spec for each and what you ask for the output. All 108 combinations were compiled for real (Auto axes, Shardy, jax 0.11.2); what you see is read from each compiled program, and every result was checked against numpy (largest error shown).
"Bytes" is the size of the whole array a collective works on (an all-gather's result, a reduce-scatter's input, an all-reduce's operand); "sent per device" is what each device sends on a ring of that group size (section 3). derived from the HLO shapes.
One array of N bytes per device, cut into n chunks. Each step, every device sends one chunk to its right-hand neighbour. Toggle "naive" to see the same all-reduce done the obvious way (everyone sends everything to device 0, which adds and sends the sum back): same answer, but device 0 carries all the traffic.
Five collectives cover everything. Each was run here inside jax.shard_map (section 5) on 8 devices, device d starting with the row [10d, 10d+1, ..., 10d+7]; the HLO op each compiled to is from the compiled program.
| JAX call (in shard_map) | HLO op | what device 0 ends with | sent per device on a ring of n | PyTorch (torch.distributed) |
|---|
Ring costs derived for an array of N bytes: in a ring all-gather each device forwards n − 1 blocks of N/n; a ring all-reduce is a reduce-scatter followed by an all-gather, so twice that. The scaling book states the same costs as time: an AllGather or ReduceScatter takes "Data volume / bandwidth · (Axis − 1)/Axis" and an AllReduce twice that (How to Scale Your Model, part 3, 2025-02-04).
Checked by hand. The ring all-reduce written with jax.lax.ppermute (code in section 5) compiled to
The whole train step (forward, backward, gradient clipping and AdamW, parameters and optimizer state donated) compiled for each layout, then run for steps from the shared initial weights on the shared batches. Same Python function every time: only the shardings change. The parallelism strategies themselves (why each exists, what it costs in the abstract) are taught framework-free on Distributed Training; the PyTorch implementations on Distributed PyTorch. This section shows what XLA actually does with them.
| Layout | mesh | collectives in the compiled step | sent per device | params + Adam per device | temp per device | loss gap |
|---|
measured Collectives counted in compile().as_text(); "sent per device" sums the ring cost of each (section 3) derived; parameter and optimizer bytes from each array's shard shape; temp from memory_analysis().temp_size_in_bytes (activations and scratch); loss gap = largest |loss − one-device loss| over the steps. Click a row for the detail.
Sequence and context parallelism, briefly. Sequence parallelism (Megatron's sense) splits the activations that tensor parallelism leaves replicated (LayerNorm, dropout) along the sequence, turning each TP all-reduce into a reduce-scatter plus an all-gather; context parallelism splits the whole sequence over devices so that very long contexts fit, and must then bring every query together with every key. The "Sequence sharded" row does the second by annotation only: the compiler's answer is to all-gather K and V in every layer, which works but sends the full K and V to everyone. Ring attention instead passes K/V blocks round the ring with ppermute while computing, overlapping the transfer with the math; that is hand-written with shard_map, not something propagation invents. Not run here.
When propagation is not enough. You may need a communication pattern the compiler will not invent (ring attention, overlapping a collective with compute, a custom MoE dispatch), or simply want certainty. jax.shard_map(f, mesh=..., in_specs=..., out_specs=...) runs f once per device on that device's shard (shapes inside are the per-device shapes) and you write the collectives yourself: psum, all_gather, psum_scatter, all_to_all, ppermute, with jax.lax.axis_index(name) as the rank. Inside, the mesh axes are Manual: the partitioner leaves that region alone. This is the rank-view program a torch.distributed user already knows; the difference is that it is still traced and compiled as one program, so it composes with jit, grad and vmap. It left jax.experimental in JAX 0.8.0 (2025-10-15); jax.experimental.shard_map still imports in 0.11.2 with a DeprecationWarning.
A ring all-reduce written by hand, the exact code that ran (from src/shard/sh_collectives.py):
def ring_allreduce(b): # b: this device's block [1, N*k]; chunks of k me = jax.lax.axis_index("i") chunks = b.reshape(N, -1) # N chunks right = [(j, (j + 1) % N) for j in range(N)] # phase 1, reduce-scatter: at step s, send chunk (me - s) mod N to the right; add what arrives to chunk (me - s - 1) acc = chunks for s in range(N - 1): send = acc[(me - s) % N] recv = jax.lax.ppermute(send, "i", perm=right) acc = acc.at[(me - s - 1) % N].add(recv) # now chunk (me + 1) mod N holds the full sum on this device # phase 2, all-gather: pass the finished chunks round the ring for s in range(N - 1): send = acc[(me + 1 - s) % N] recv = jax.lax.ppermute(send, "i", perm=right) acc = acc.at[(me - s) % N].set(recv) return acc.reshape(1, -1) f_ring = jax.jit(jax.shard_map(ring_allreduce, mesh=mesh, in_specs=P("i", None), out_specs=P("i", None)))
Two errors you will meet, both pasted from runs here.
in_specs. out_specs=P(None, None) says "every device holds the same value". After all_gather that is true, but JAX types the result as still varying over the axis, and refuses: Either declare out_specs=P('i', None) (what the table in section 3 did: the global result is then 8 stacked copies) or pass check_vma=False if you are sure.Multi-host (not run here: this machine is one host). A TPU slice bigger than one host (typically 4 chips per host) runs the same Python script on every host. jax.distributed.initialize() connects them (on Cloud TPU it finds the coordinator by itself); then jax.devices() lists every chip in the slice, jax.local_devices() only this host's, and jax.process_index() / jax.process_count() play the role of rank and world size. A sharded array is now a global array whose shards live on several hosts; each host can only touch its own (x.addressable_shards), so data loading builds the global batch from per-host pieces with jax.make_array_from_process_local_data. The jitted program is still one program over all devices; its collectives ride ICI inside a slice and the data-centre network between slices. PyTorch's equivalent is torchrun + init_process_group, with one process per GPU rather than one per host.
History. pmap (one mapped axis, one device per element) is "in maintenance mode" since JAX 0.8.0 and, since 0.10.0, implemented on top of jit(shard_map); it still runs in 0.11.2 (). pjit was merged into jit (jax.experimental.pjit.pjit deprecated in 0.8.0); xmap was deleted in 0.4.31; with mesh: is deprecated in favour of jax.set_mesh (0.10.1); PmapSharding and device_put_sharded/replicated were removed in 0.10.0 (JAX changelog). New code: jax.jit with shardings, plus jax.shard_map where needed.
jax/_src/named_sharding.py:71 class NamedSharding: "a pair of a Mesh of devices and PartitionSpec"; lines 246–260 lower it two ways, _to_xla_hlo_sharding (GSPMD's HloSharding) and _to_sdy_sharding (Shardy's representation), so one annotation feeds either partitioner.jax/_src/sharding_impls.py:900 def make_mesh; line 975 axis_types = (AxisType.Explicit,) * len(mesh_devices.shape) when none are given. jax/_src/mesh.py:303–304: the Mesh constructor's default is AxisType.Auto.jax/_src/pjit.py:2037 def with_sharding_constraint; pjit.py:2263 def reshard.jax/_src/shard_map.py:108 def shard_map(f, /, *, out_specs, in_specs=Infer, mesh=None, axis_names=frozenset(), check_vma=True); lines 288–306 raise "in_specs passed to shard_map: ... does not match the specs of the input" only when every mesh axis involved is Explicit; lines 783–786 mark the mapped axes AxisType.Manual; lines 1109–1114 pick the Shardy lowering (sdy.ManualComputationOp, line 1066) or the GSPMD one.xla/service/cpu/cpu_compiler.cc:637–646: if (use_shardy_partitioner) spmd_pipeline.AddPass<sdy::ShardyXLA>(); else spmd_pipeline.AddPass<ShardingPropagation>(...), then spmd_pipeline.AddPass<spmd::StatefulRngSpmdPartitioner>(...): the two propagators, one partitioner. Lines 1108–1111: CpuAllReduceCombiner(kCombineBytes = max int64, kCombineCount = 256), which is why data parallelism compiles to a single all-reduce here.xla/service/gpu/gpu_compiler.cc:1099 AllReduceReassociate and :1334 ReduceScatterCreator: two passes the GPU pipeline runs and cpu_compiler.cc does not contain. The first rewrites all-reduce(a) + all-reduce(b) into all-reduce(a + b); the second turns all-reduce followed by a slice into a reduce-scatter. Their absence explains the FSDP and tensor-parallel details in section 4. The TPU compiler is not open source, so what it runs cannot be checked here.Files read at jax tag jax-v0.11.2 (commit 32544801, 2026-09-17) and openxla/xla 91888df6ce85102c30220e41d952065925e10886 (the commit jax-v0.11.2 pins); MaxText at main 1a95d1e5 (2026-10-15).
with_sharding_constraint on the residual stream per block fixed it. Constrain activations at block boundaries, as MaxText does with logical axis rules.axis_types explicitly so the code says which mode it relies on.compile().as_text(), and profile on the real hardware before drawing conclusions about cost._tree_math.py:398 and :433) and in apply_updates (update.py:42), because GSPMD split the small replicated parameters (biases and LayerNorm parameters) over the model axis, idle for them, and gathers them back every step; 29 more are in LayerNorm (model_jax.py:45–47), which it split on the feature dimension. Shardy inserts none of these. Neither is uniformly better; constraints make the result robust to both.memory_analysis() for unexpected replication; a profile to see whether collectives overlap with compute; and that the mesh axis carrying the most traffic maps onto the fastest links (ICI within a slice).src/shard/.The TPU as a JAX programmer meets it, and Pallas, JAX's kernel language, from zero. Everything about the chip comes from published specifications and from the TPU table inside JAX's own source; everything about the running example (the 826,368-parameter character model of the Reading tab) and every kernel on this tab was run here, on a CPU.
jnp, the grid order the Pallas interpreter walks, and the real Mosaic code that JAX hands the TPU compiler, produced on this CPU by lowering for platform "tpu"), and calculated (roofline arithmetic: what an operation would need at best on a TPU, never what it would get). The chip itself (systolic arrays cycle by cycle, pods, optical switches) is taught on the Hardware topic's TPUs and other accelerators page; collectives and meshes on the Sharding lab. This tab does not repeat them.The Reading tab defined the parts (MXU, VPU, VMEM, HBM, ICI) and gave each generation's peak and ridge point. Here is the one level down that a JAX or Pallas programmer touches. A TensorCore is one sequential processor with no threads: a scalar unit runs the control flow and computes addresses (from its own small SMEM), and issues wide vector instructions; the VPU works on vector registers of 8 × 128 32-bit values (128 lanes, 8 sublanes); the MXUs multiply; DMA engines copy tiles between HBM and VMEM in the background while the core computes. In PyTorch-on-GPU terms: VMEM plays the role of shared memory, but it is tens of megabytes rather than a few hundred kilobytes, and nothing caches HBM for you, so the compiler (or your Pallas kernel) decides every copy.
The picture is the hero of TPU programming and performance (one chip as your program meets it: HBM, then VMEM, then the MXUs). The table below keeps the per-core numbers from tpu_info.py that this lab uses.
| Chip | TensorCores per chip (JAX devices) | MXUs per core × size | VMEM per core | HBM per chip | HBM GB/s | ICI GB/s per chip | Ridge calc |
|---|
"TensorCores (JAX devices)": on v4 and v5p the two cores are fused into one JAX device by default (megacore; supports_megacore is true only for these two in tpu_info.py); on TPU7x each core is its own device, so one chip shows up as 2 entries in jax.devices(). Ridge = bf16 peak ÷ HBM bandwidth, FLOPs per byte, as on the Reading tab (it agrees). ICI per chip is Cloud's bidirectional figure; v4's page lists none.
tpu_info.py). So 40 MiB fits v5p and 7x too, but Pallas double-buffers every input and output by default (two copies, so the next tile loads while this one is used), so 40 MiB of tiles needs 80 MiB: only v5e and v6e. And the compiler applies a default per-kernel ("scoped") VMEM limit; a kernel that needs more asks with vmem_limit_bytes (section 7).An MXU is a systolic array: a square of multiply-accumulate cells holding one tile of the weight matrix, through which rows of activations pulse, each cell multiplying, adding and passing its result to the next cell, so each number read from VMEM is used 128 (or 256) times. It holds a whole k × n tile at a time, of side 128 (v4, v5e, v5p) or 256 (v6e, TPU7x), and the scaling book's rule follows: "Weight matrices need to be padded to at least size 128 (256 on TPU v6e) in both dimensions to fill up the MXU." A weight of 65 columns occupies a 128-wide tile and leaves the rest of the cells multiplying zeros. The cycle-by-cycle picture of the array is on the Hardware topic's TPU page; here is what it means for the shapes in your model.
The tile-by-tile picture is on TPU programming and performance, section 4 ("a last dimension of 65 is stored as 128", and a matmul on the MXU with the padding drawn). Utilisation below is calculated for every distinct matmul shape in the running example's training step (the 99 dot_general equations of jax.make_jaxpr(jax.value_and_grad(loss_fn)), 33 of them in the forward pass): useful multiply-adds ÷ multiply-adds the padded tiles issue, an upper bound.
Two lessons from the running example. Its output head (D = 128 to a vocabulary of 65) fills 51% of a 128-wide MXU and 13% of a 256-wide one; its attention, with a head dimension of 32, fills 25% and 6%. This is why production models use vocabularies padded to a multiple of 128 and head dimensions of 128 (MaxText's Llama 2 7B config: head_dim: 128, vocab_size: 32000 = 250 × 128), and why a model tuned on a v5e can lose efficiency on a v6e: every 128 × 128 projection of this model is 25% of a 256 × 256 array.
The Reading tab gave the rule in one line: an operation whose arithmetic intensity (FLOPs per byte it moves to or from HBM) is below the chip's ridge point waits on memory. Below, every distinct matmul of the running example's training step sits on the roof of the generation you pick, beside the weight matmuls of a 7B-class model (Llama 2 7B as configured in MaxText's pinned configs/models/llama2-7b.yml: D 4,096, MLP 11,008, 32 layers, 6.74 billion parameters) at the number of tokens you choose. The derivation (FLOPs, bytes, the time bound) is on the Hardware topic's Performance math page; this is the calculator.
What the running example would cost on a TPU calculated. Its 99 matmuls do 22.75 GFLOP per step (XLA's cost_analysis() on the CPU compile counts 23.69 GFLOP for the whole forward and backward, the rest being elementwise work). At bf16 peak a v6e would do them in 25 µs, but because every one is memory-bound the bound is 236 µs; v5e 473 µs, v5p 140 µs, TPU7x 52 µs. The whole step measured 0.102 s here (the shared setup's 500-step run, measured on Apple M1 Pro (CPU), shared machine, 4 threads, low priority). In practice a step this small on a TPU is dominated by fixed costs the roofline ignores (launching the program, the host loop, the optimizer's many small elementwise ops), which is why nobody trains 826,368 parameters on a TPU.
The 7B-class model calculated. Its bf16 weights are 13.5 GB, so a v5e's 16 GB holds them with little room for anything else, and one decode step for one user must read all of them: about 16 ms on v5e (62 tokens per second at best), 8.1 ms on v6e (124), 1.8 ms on TPU7x (558), whatever the MXUs could do. At 256 tokens per step v5e reaches 97% of its bf16 peak and v6e only 42%: the faster the MXUs relative to HBM, the larger the batch needed to use them. That is the ridge point turned into a batching rule.
| Matmul (running example) | count | FLOP/byte | bound | best time each |
|---|
Bytes = inputs read once plus output written once, at 2 bytes per number (bf16) or 4 (float32); time = max(FLOPs ÷ bf16 peak, bytes ÷ HBM bandwidth). The 7B point is one forward pass of its weight matmuls (attention scores and the KV cache left out), so at 1 token it is a decode step with a batch of 1, at 4,096 a training micro-batch's forward. Real kernels reach 50 to 80% of these bounds at best.
The Sharding lab built meshes on 8 simulated devices, where every device is as close as every other. On a real slice the chips sit on a torus (section 1's table), and two neighbours along one ICI link are much cheaper to talk to than two chips five hops apart. So the question a JAX programmer faces is: when I write jax.make_mesh((16, 16), ("data", "model")), which physical chips form each "model" group? JAX answers it in mesh_utils.create_device_mesh, which jax.make_mesh calls. That function only reads each device's coordinates, so it runs on this CPU against mock TPU devices built the way JAX's own tests build them.
What the runs show:
mesh_utils.py:321 assigns axes from last to first, giving each the largest set of whole physical axes still free. So list your axes least to most chatty, ("data", "fsdp", "model"). MaxText does exactly this: mesh_axes in its configs/base.yml:684 runs from data through fsdp to tensor and expert, and it builds the mesh with this same mesh_utils.create_device_mesh (maxtext_utils.py:2086, main @ 1a95d1e5).NotImplementedError because 8 is not a product of whole 4-chip axes. jax.make_mesh lets v5e (and only v5e: sharding_impls.py:962) split a physical axis instead, at the price shown in the "split" result: neighbours up to 9 hops apart.priority_map, mesh_utils.py:316), so a "model" axis of 2 lands on the two cores of one chip, 0 hops apart.Run with jax._src.mesh_utils.create_device_mesh at jax-v0.11.2 (src/tpu/tp_torus.py). "Hops" is the largest ICI distance between neighbours along a logical axis, counting the wraparound link where the slice has one. The picture shows the chips of the bottom layer (z = 0), coloured by their index along the last logical axis, the one JAX treats as most communication-heavy.
The scaling book's model for a ring over one torus axis of X chips: an all-gather or reduce-scatter of V bytes takes V ÷ Wbidi with a wraparound link (independent of X) or V(X − 1)/X ÷ Wone-way without one; an all-reduce costs twice that; spanning n physical axes divides the time by n; and nothing goes faster than about 1 µs per hop (Tmin × X ÷ 2). What each collective moves is on the Sharding lab.
Per-link bandwidths from the scaling book (2025-02-04): one-way 4.5e10 B/s on v4 and v5e, 9.0e10 on v5p, v6e and TPU7x; bidirectional twice that. Its own worked example: an all-gather of 34 MB over a 4-chip v5e axis, 377 µs with wraparound, about 560 without (measured in its profile: about 680).
A = the MLP's hidden activations of layer 0 [4,096 × 512], B = its down-projection weight [512 × 128], O = A B [4,096 × 128]. Drawn to scale. Pick a block shape; "whole arrays" is the before, a grid of one step.
The order of grid points is measured: recorded by the TPU interpreter's grid_point_recorder while it ran the kernel of section 6 (1 core with the default semantics, all "arbitrary": lexicographic, k innermost. The default is what makes it lexicographic, not the single core: the interpreter shuffles "parallel" axes even on one core, as child page Pallas kernels measured on its softmax kernel. 2 cores with ("parallel", "parallel", "arbitrary"): each core took 4 of the 8 row blocks, in an order the interpreter shuffles on purpose, here with seed 0). Copies and bytes are calculated with Pallas's rule (copy a tile only when its block index changes), bf16 inputs and a float32 output, two buffers per operand.
XLA writes nearly every kernel of a JAX program, and fuses elementwise work into its matmuls well (the Compiler lab shows it). It cannot invent an algorithm, though: it will not turn attention into flash attention (never writing the T × T score matrix to HBM), route tokens to experts with ragged matmuls, or overlap a matmul with a collective by hand. For those you write a kernel, and on JAX that means Pallas. Five ideas are all of it:
x_ref[...] and write with o_ref[...] = ; inside, ordinary jnp code runs on the tile.pl.program_id(axis) says which. On a TPU the points run in order, as nested loops (Pallas's TPU docs: "sequentially, in lexicographic order"), unlike a GPU, where Triton's program instances run in parallel."parallel" (order does not matter, so the axis may be split across a megacore's two cores) or "arbitrary" (must run in order, as an accumulation must). The default is all arbitrary (lowering.py:778).interpret=True runs it as ordinary JAX (section 6 shows what that does and does not tell you).| Idea | Pallas (TPU) | Triton (GPU) | PyTorch or CUDA counterpart |
|---|---|---|---|
| which instance am I | pl.program_id(i), grid runs in order | tl.program_id(i), instances run in parallel | blockIdx |
| which tile to load | BlockSpec index map; copies generated and pipelined for you | pointer arithmetic or block pointers, tl.load with masks | indexing by hand into shared memory |
| fast memory | VMEM, 16 to 128 MiB per core | shared memory, up to a few hundred KiB per SM | __shared__ |
| edges | block shape divisible by (8, 128) or equal to the array; ragged edges padded | masks on every load and store | bounds checks |
| matrix unit | jnp.dot on tiles goes to the MXU | tl.dot to tensor cores | WMMA, wgmma |
| calling it | pl.pallas_call(kernel, out_shape, grid, in_specs, out_specs), inside jax.jit | kernel[grid](...) | torch.library custom op |
Triton itself, and how GPU kernels are tuned, live on Triton and Gluon under Topic: cuda-and-gpu-programming.
Both run on the running example's real tensors (layer 0, training batch 0, the shared initial weights) and are checked against jnp. This is the code that ran (src/tpu/tp_kernels.py):
| Kernel, input | grid, blocks | max |error| vs jnp | time: XLA | time: interpret |
|---|
Errors measured (deterministic). Times are rough: measured on Apple M1 Pro (CPU), shared machine, 4 threads, low priority (1-minute load about 29 during the run), median of 5 after a warm-up.
What the numbers say. The matmul agrees with XLA to float32 rounding (2.5e-7 on outputs up to 0.26); fed bf16 inputs, as an MXU would be, it is off from the float32 answer by 7.1e-4, and matches XLA's own bf16 matmul to 1.2e-7, so the error is bf16's, not the kernel's. Flash attention agrees with the model's attention to 8.9e-8 while computing only 384 of its 512 blocks (for each head, the block where the first 64 queries meet the last 64 keys is entirely masked by causality, and the pl.when skips it), and never stores the 8.4 MB score matrix. Interpret mode is 10 times slower than XLA on the matmul and 70 times on attention: it is a correctness tool. What it builds explains why: the jitted interpreted matmul lowers to 147 lines of StableHLO with one while loop over the 32 grid points, 3 dynamic_slice and 3 dynamic_update_slice, where a @ b lowers to 6.
Pallas has two interpreters. interpret=True is the plain one (hlo_interpreter.py). Passing interpret=pltpu.InterpretParams(...) selects the TPU interpreter, which simulates the TPU's DMAs, semaphores and cores, checks every block index, and can run a race detector. Three deliberate bugs in the matmul above:
| Bug | interpret=True | TPU interpreter |
|---|
The second bug is the dangerous one: the plain interpreter drops compiler_params (hlo_interpreter.py:329), so it never sees the wrong semantics, and on a single-core chip the real compiler would run the axis in order anyway. On a megacore chip the two cores would race on the same output tile. The TPU interpreter shuffles parallel axes on purpose to expose this: here it ran k = 1 before k = 0 for the first output tile, so the zeroing step erased a partial sum. The third bug is silent in plain interpret mode because its dynamic_slice clamps an out-of-range start (XLA's rule) and quietly re-reads the last tile.
jax.export can lower a function for a platform the machine does not have. Lowered for "tpu", the matmul becomes one stablehlo.custom_call @tpu_custom_call whose payload is a Mosaic module; debug=True prints it. This is the program libtpu would compile (not run here: compiling needs libtpu and a TPU). Note the refs typed #tpu.memory_space<vmem>, the grid as iteration_bounds, each index map turned into a transform_ function, and jnp.dot into tpu.matmul. The flash kernel lowers too, to two tpu.matmul ops.
Lowering for TPU also enforces the tiling rule that interpret mode does not. With a block of 100 rows:
The same kernel runs under interpret=True and gives the right answer (error 2.1e-7): a kernel that passes in interpret mode can still be rejected by the TPU compiler. Lowering with jax.export(..., platforms=["tpu"]) on your laptop catches this class of error before you pay for a TPU.
The block shape is the one decision that matters in a Pallas matmul. Small blocks re-read A and B many times from HBM; large blocks need more VMEM (and, beyond what fits, the kernel fails to compile). The table counts, with Pallas's skip-if-unchanged rule, the bytes each choice moves for the running example's MLP matmul and for one 7B-class MLP matmul (4,096 tokens, 4,096 to 11,008).
| Matmul | blocks (bm, bn, bk) | grid steps | HBM to VMEM (and back) | vs the minimum | VMEM, 2 buffers | fits |
|---|
Calculated in src/tpu/tp_pallas.py; each of the running example's six choices was also lowered for TPU (all legal). "Minimum" = every input read once and the output written once. Fits = against the chosen generation's VMEM per core in tpu_info.py; the compiler also applies a default per-kernel (scoped) limit, which pltpu.CompilerParams(vmem_limit_bytes=...) overrides (mosaic/core.py:97).
The pattern: with bk the full K, A is read once, and B once per row of blocks; HBM traffic falls towards the minimum as bm grows, while VMEM grows linearly. For the 7B-class matmul, 128-cubed blocks move 19.6 times the minimum traffic, whose arithmetic intensity is then far below any ridge point; 512 × 5,504 × 256 blocks move 3.2 times the minimum in 27 MiB of VMEM, too much for v4's 16 MiB per core. Autotuning a kernel is searching this table with real timings.
jax/experimental/pallas/ops/tpu/: flash_attention, splash_attention (block-sparse attention with masks), paged_attention and ragged_paged_attention (serving), megablox (grouped matmuls for mixture-of-experts) and matmul. MaxText imports splash_attention from there (layers/attention_op.py:29, main @ 1a95d1e5) and also uses kernels from tokamax, OpenXLA's library of ready-made Pallas kernels (0.0.16 on PyPI, 2026-10-09; the Tool map dates it).pltpu.make_async_remote_copy). Start in interpret mode against a jnp reference, then lower for TPU on your laptop, then tune block sizes on the chip.while loop; it does not model DMAs, pipelining, VMEM limits or the MXU. Section 6 also shows it accepts a block shape the TPU compiler rejects. Speed is measured on the chip, with the profiler, against the XLA version you are trying to beat.Read 2026-10-15. Paid access is Cloud TPU (a TPU VM or GKE) by the chip-hour; prices are not quoted here.
Each line below was found by a regular expression in src/tpu/tp_source.py, so a wrong number fails the build rather than drifting.
| file:line | what it shows |
|---|
create_device_mesh gives the most physical axes to the last logical axis. Put tensor parallelism last; a mesh written ("model", "data") gives the chatty axis the worst placement.pl.when(pl.program_id(k_axis) == 0)."tpu" with jax.export, and use InterpretParams() for index checks.jax.make_mesh((16, 4), ("fsdp", "model")): the model axis, which communicates every layer, gets one whole physical axis with wraparound (neighbours 1 hop apart); FSDP, which gathers weights once per layer and can overlap with compute, gets the other two (y and z), so its all-gathers use two axes of bandwidth. (8, 8) is not placeable without splitting axes.jnp reference; run it with interpret=True for correctness, then with interpret=pltpu.InterpretParams(detect_races=True, num_cores_or_threads=2) for index, ordering and race bugs; lower it with jax.export(..., platforms=["tpu"]) to catch tiling errors; then measure on a real chip. All four steps but the last ran on this page.Which JAX tools are alive, which are dying, and which to pick for a job. Every tool below has its status, latest release and last commit, read live from PyPI and GitHub on 15 October 2026, plus a one-line verdict. Verdicts are judgements and are labelled judgement; statuses quote the owners' own notices where one exists.
Ten jobs a JAX user does, and the tool you would have used for each in October 2023. The changes play in date order, each explained in the list below; every change is backed by an owner's notice, a release or the JAX changelog (sources in the lineage and API sections below).
Click a column header to sort, a row for details. Latest release is the newest stable version on PyPI, else the newest GitHub release; last commit is the newest commit on the default branch (GitHub Atom feed). A recent commit is not a sign of life on its own: for T5X, Pax and jmp the 2026 commits are automated type-checker edits.
Pick a job and the hardware you have. The stack is listed in the order you would meet it; tools to steer away from are listed with the reason. judgement built from the entries above.
Each bar runs from a tool's start (first PyPI release, repository creation or announcement) to today, or to its last activity if it stopped; colour is its status today. Arrows mark a hand-over: solid when the owners documented it, dashed when it is our reading of what happened in practice (no notice found). Click a bar for details.
Inside JAX itself the multi-device API was rebuilt between 2024 and 2026: code written for pmap, pjit or xmap (most blog posts and many codebases on this map) now warns or fails. Read from the JAX changelog; the Sharding lab uses only the current APIs.
Flax NNX by default: it is what the Flax team points new users to, and MaxText and Tunix build on it; its stateful modules read like PyTorch. Equinox if you want models to be plain pytrees (common in scientific ML). Linen only to maintain existing code (it is not deprecated, but no longer the recommendation). Haiku is in maintenance mode by DeepMind's own notice since July 2023.
jax.pmap. What do you tell the team?"pmap has been in maintenance mode since JAX 0.8.0 (October 2025) and since 0.10.0 it is a wrapper over jit(shard_map). Write new code with jax.jit plus NamedSharding (let the compiler place collectives) or jax.shard_map when you want per-device code; the migration guide has drop-in replacements.
Yes. TorchTPU (a native PyTorch device, torch.compile lowered to XLA) was announced in April 2026 and open-sourced on 20 October 2026; vLLM and SGLang TPU engines are built on it, and TorchTitan trains on it. It is new (one process per chip, about 450 ATen ops, collectives compiled one by one unless marked safe), so expect gaps a mature JAX stack does not have. The honest answer is "yes for serving and training through TorchTPU; port to JAX when you want the most mature TPU path".
MaxText: it is Google's maintained reference, expresses every parallelism as a mesh axis, and has MLPerf-tagged configurations. Marin's Levanter is the best non-Google alternative (named tensors, reproducible). T5X, Pax and EasyLM teach the pjit era but are quiet and use deprecated APIs.
Look for the owner's notice first (README banners: Haiku, JetStream, XPK, Levanter), then the archived flag, then the date of the last release, and only then commits, reading what they are: T5X, Pax and jmp had commits in 2026 that were automated lint changes. A dependency with one maintainer (Equinox, EasyDeL) is alive but carries bus-factor risk.
Sources: PyPI JSON API and GitHub REST API and Atom feeds (read 2026-10-15), the owners' READMEs and notices linked in each entry, the JAX CHANGELOG on the main branch, Google's developer blog and Cloud docs. Scripts: src/map/ (fetch_meta.py, atlas_tools.py, atlas_api.py, gen_data.py, check_imports.py).
The tabs of this page, its eight child pages, the knowledge base pages it leans on and the best outside resources, each with an approximate time. Outside sources are marked Google (written by the makers of JAX, XLA or the TPU: authoritative on how things work, not neutral on whether to use them) or third-party. Links checked on 2026-10-15.
The stack as one map for a PyTorch user: why JAX, transformations, the compiler, the training stack, sharding, TPUs and Pallas, codebases, JAX against PyTorch, choosing; mistakes with real error messages and interview rehearsal closed. 32 min, plus 13 in closed details
The running example's attention traced line by line, Python loops against lax, immutable arrays and out-of-bounds clamping, the parameter pytree, grad checked against PyTorch, vmap and per-example gradients timed, a toy tracer, footguns with real messages. 22 min, plus 9 in closed details
The train step in five forms, one MLP block before and after fusion, donation, rematerialisation against memory, scan against unroll, cold against cached compiles, debugging, against torch.compile. 23 min, plus 2 in closed details
Flax NNX, Linen, Equinox and Haiku side by side, optax checked against PyTorch's AdamW, both twins trained 4,000 steps, orbax resume bit for bit, grain, three precisions. 24 min, plus 3 in closed details
A PartitionSpec playground on 8 simulated devices, the collectives animated round a ring, six layouts of the train step with what the compiler inserted, shard_map and a hand-written ring all-reduce. 18 min, plus 2 in closed details
Per-core numbers by generation, a roofline calculator with the running example on it, the mesh on the torus, Pallas from zero with two kernels run in interpret mode, block sizes against HBM traffic, free TPU access. 25 min, plus 5 in closed details
Every library, codebase and serving stack with its status, dates and licence; a picker and a lineage. 13 min, plus 1 in closed details
Times as each page's header states them.
Tracers, interpreters, jaxprs, the jit cache, control flow, autodiff and custom rules, vmap, pytrees and keys, read in JAX's source; tab Jaxpr explorer. Child page, about 45 min, plus 25 in closed details
Lowering, PJRT, the pass pipeline, fusion, layouts, buffers, remat, caches, export, recompiles, profiling and flags; tabs Pass diff viewer, Fusion explorer, Recompile detective, Profile reader. Child page, about 39 min, plus 14 in closed details
Flax NNX state and transforms, Linen and Equinox, optax, orbax, grain, float16 loss scaling, a complete script preempted and resumed. Child page, about 33 min, plus 21 in closed details
Four differences on one step, every default that differs, weights both ways, the equivalence test, drift, GPT-2 by hand, interop; tabs Divergence hunter, Port drills. Child page, about 28 min, plus 17 in closed details
Mesh and PartitionSpec, Auto, Explicit and Manual, propagation, shard_map, every strategy measured, context, pipeline and expert parallelism, choosing a mesh, many hosts; tab Mesh designer. Child page, about 46 min, plus 26 in closed details
The chip as your program meets it, generations, rooflines, tiles and padding, precision, memory planning, slices and the torus, profiling, MFU and cost per token; tabs Roofline lab, Slice planner. Child page, about 33 min, plus 13 in closed details
The grid and BlockSpecs with a grid stepper, row kernels, LayerNorm, flash attention with its replay, pipelining, scalar prefetch, testing without a TPU, production kernels, Triton compared; tab Kernel playground. Child page, about 38 min, plus 13 in closed details
MaxText's config, model, logical axis rules, train step and MFU counting, Tunix, levanter in Marin, which to start from; tabs Codebase map, Config explorer. Child page, about 34 min, plus 8 in closed details
The TPU as hardware: systolic arrays, every generation's specs, pods, against AMD, Trainium, Groq and Cerebras.
FLOPs, memory, MFU and rooflines, framework-free.
Why the network picks your parallelism; ICI against NVLink and InfiniBand.
Data, tensor, pipeline parallelism and ZeRO, framework-free.
The other side of the comparison; see its torch.compile and Distributed PyTorch children.
CUDA and Triton, the GPU counterparts to Pallas.
What the codebases of section 7 are used for.
The ideas behind FSDP, tensor parallelism and the attention kernels Pallas reimplements.
Google DeepMind's book (Austin et al., 2025): rooflines, TPUs, sharded matmuls, transformer maths, training and serving LLaMA on TPUs, profiling, JAX, and a GPU chapter. Read parts 1 to 6 and 10 at least. Google · about 3 h 30 min for those parts, about 6 h for all
The official mental model: arrays, jit, grad, vmap, keys, pytrees, sharded computation, stateful computations. Google · about 25 min, then about 1 h for the set
The official list of footguns; read before debugging anything. Google · about 25 min
A university course's from-scratch tutorial for PyTorch users (written for Linen). third-party · about 45 min
Builds tracing, jaxprs, jvp, vjp and jit from nothing: the deepest explanation of why JAX behaves as it does. Google · about 2 h
Tracing rules, static arguments, caching. Google · about 20 min
Automatic sharding, explicit sharding and per-device code. Google · about 45 min and 35 min
Xu et al. 2021: sharding propagation and how the partitioner inserts collectives. Google · about 1 h
NNX basics, transforms, and the Rosetta stone for reading Linen code. Google · about 1 h 30 min
Optimisers as gradient transformations; checkpointing; data loading. Google · about 40, 30 and 30 min
End-to-end examples wiring JAX, Flax NNX, optax, orbax and grain. Google · about 1 h 15 min
Models as pytrees, by Patrick Kidger; the main non-Google library. third-party · about 30 min
The kernel language and how tiles stream between HBM and VMEM. Google · about 45 and 25 min
Chips, slices, hosts and topologies, with per-generation pages. Google · about 40 min
Production JAX for LLMs: read MaxText's decoder and train step, Tunix's GRPO trainer, levanter's determinism. Google, Google, third-party · about 1 h 30 min, 45 min, 45 min
Running PyTorch on TPUs, if you are not porting: the native backend's design (eager modes, StableHLO lowering, collectives) and the bridge through JAX. Google and PyTorch · about 20 min each
Not used here (this page runs on a CPU); checked 2026-10-15 by the TPU and Pallas lab.