Topic: jax-and-tpu

Reading: 32 min, plus 13 in closed details. JAX, the XLA compiler under it and the TPUs it was built for, for someone who knows PyTorch: the stack as one map, each layer compared with PyTorch, and the child page that owns it. Run on an Apple M1 Pro CPU, with 8 simulated devices for sharding; TPU numbers are published ones, kept apart. Data as of October 2026.

0. The map: one train step's life

The core idea
JAX runs your Python function once on placeholders to record it as a whole program, then transforms that program (differentiate, batch, split across devices) and hands it to the XLA compiler in one piece; TPUs were designed around exactly that compiled model, and the price is that your functions must be pure.

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.

  1. Five layers, each passing a program down. Your code hands down a pure function of (params, batch); the transformations hand down a jaxpr: JAX's typed program; the compiler and the partitioner hand down one executable per device, with collectives; and those run as kernels on chips, joined by ICI. Drawn: one station per layer, left to right; the rows, cubes and boxes stand for the counts in the steps, not one for one illustrative layout.
  2. Your model and loop. Flax NNX modules, the optax optimiser, orbax checkpoints and grain data (in PyTorch: 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.
  3. Traced to a jaxpr. 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.
  4. Lowered and fused by XLA. The jaxpr becomes StableHLO (5,318 operations), and XLA's passes leave 816 kernels, 783 of them fusions measured, compiled once in 3.6 s and then cached (in PyTorch: TorchInductor, but always the whole step). Owner: XLA and compilation, whose Fig. 1 takes one attention sub-block down through the forms and Fig. 2 sets the same chain unfused against fused. Lab: Compiler lab. Section 3.
  5. Sharded over a mesh. A 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.
  6. Run on the chip. On each TPU chip, the MXU (a 128 × 128 systolic array) does the matmuls and the VPU the elementwise work, on tiles copied into VMEM, a software-managed scratchpad, from HBM (819 GB/s on v5e); ICI links join it to its neighbours (in PyTorch's usual world: CUDA GPUs). Owner: TPU programming and performance, whose Fig. 1 draws one chip as your program meets it and Fig. 2 puts a weight on the MXU. Lab: TPU and Pallas lab. Section 6.
  7. Pallas, where XLA is not enough. A hand-written kernel runs on a grid, and a BlockSpec per input says which block each grid step copies into VMEM: the lab's tiled matmul on the running example's MLP shape copies 512 × 128 blocks of A on an (8, 1, 4) grid, 32 steps measured in interpret mode; the first 8 are drawn (in PyTorch: Triton). Owner: Pallas kernels, whose Fig. 1 follows one grid step on a TPU core and Fig. 3 the causal flash forward. Section 6.
  8. The codebases on top, and PyTorch beside. MaxText, Tunix and levanter assemble every layer for LLMs, with rules in a config that map each weight's named dimensions onto the mesh. Beside them, the PyTorch twin's eager step sends 1,302 operators from Python on every call, where JAX runs 816 kernels and Python ran once (section 2). Owner: JAX LLM codebases, whose Fig. 1 sets five boxes against four codebases and Fig. 3 maps logical names to chips. Tools and their status: the Tool map. Sections 7 and 8.

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:

tracer
a stand-in argument carrying only a shape and dtype (an abstract value, such as f32[8,128]), recording what is done to it
jaxpr
the recorded program: typed, side-effect free, a list of primitives (dot_general, add, tanh)
pure function
its result depends only on its arguments, and it changes nothing outside itself
pytree
any nesting of lists, tuples, dicts and registered classes with arrays at the leaves
key
random-number state as an explicit array value
XLA, HLO
Google's compiler for array programs, and its internal program form
Mesh, PartitionSpec
devices as a named grid, and which mesh axis splits each dimension of an array
collective
communication among devices: all-reduce, all-gather, reduce-scatter, all-to-all, permute
MXU, VMEM, ICI
the TPU's matrix unit, its software-managed on-chip memory, its chip-to-chip links
Pallas
JAX's kernel language, the counterpart of Triton
MFU
model FLOPs utilisation: useful FLOPs ÷ (step time × peak FLOP/s)

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.

1. Why JAX exists, and who uses 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).

The same train step called four times: PyTorch dispatches every op every call, JAX traces once and then runs fused kernels

op dispatched from Pythonop recorded while tracingcompilingcompiled (fused) kernel

2. The functional model and the transformations

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

  1. Before the first call. Both frameworks hold the same model and the same batch. Watch what Python does on each call.
  2. Call 1, PyTorch: every operation goes through Python. Eager mode runs the step line by line: each operation is dispatched from Python and launches its own kernel the moment it is reached.
  3. Call 1, JAX: trace. jit runs the Python function once with tracers (shapes and dtypes only) and records every primitive into a jaxpr. Nothing has been computed yet.
  4. Call 1, JAX: compile. XLA compiles the whole step, forward, backward and optimiser update together, fusing chains of operations into fewer kernels. This is the slow part of the first call.
  5. Call 1, JAX: run the executable. The compiled program runs as 816 kernels, about a quarter as many as the primitives traced. The executable is cached under the signature: shapes, dtypes and static arguments.
  6. Call 2, same shapes. PyTorch dispatches every operation from Python again. JAX finds the signature in its cache: the Python function does not run at all (a print inside it would stay silent).
  7. Call 3, same shapes. The steady state: JAX pays no Python cost per operation, and its kernels are fewer because they are fused.
  8. Call 4, a new sequence length. PyTorch does not care. For JAX this is a new signature: trace again, compile again. A batch whose length changes every step recompiles every step, which is why JAX code pads to a few fixed lengths (buckets).
Predict: a jitted function contains print("step", x). You call it three times with arrays of the same shape. What appears?
A real jaxpr, and the porting trap it shows
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.

Go deeper. JAX core owns every mechanism here: tracing (section 2), the jit cache and what recompiles (3), jaxprs (4), control flow (5), autodiff (6), vmap (8), pytrees (9), keys (10); its Fig. 2 traces once, compiles once and runs many times, the JAX lane of Fig. 2 here without PyTorch beside it. The Transforms lab keeps what spans them on the running example: its attention traced line by line, grad checked against PyTorch, vmap timed against a loop, and a toy tracer in a few dozen lines.

3. What the compiler does

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:

  • Fusion: a chain of elementwise operations (often with the reduction after it) becomes one kernel, so intermediates never make a round trip to HBM. The whole step, backward and optimiser included, is one program to fuse across, which is why a JAX step is usually fast without hand-written kernels.
  • Layout assignment (which dimension is contiguous, padding to the hardware's tiles), algebraic simplification, and buffer assignment, which lets arrays with non-overlapping lifetimes share memory; compiled.memory_analysis() reports its result before anything runs.
  • Donation: 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.
  • Rematerialisation: 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).

Two measurements on the running example

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).

Go deeper. XLA and compilation owns the compiler: lowering (section 1), the pass pipeline (3), fusion decisions (4), layouts (5), buffer assignment (6), remat (7), caches (8), recompiles (10), profiling (11); its Fig. 1 takes one attention sub-block down through the forms and Fig. 2 fuses one chain. The Compiler lab keeps the cross-cutting views on the running example: its five forms, one MLP block before and after fusion, donation, remat policies, scan against unroll and a cold against a cached compile.

The running example's train step through the pipeline: thousands of operations become about 800 kernels

4. The training stack

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.

PyTorchJAX stackThe difference that matters
nn.ModuleFlax 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.AdamWoptax (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, DCPorbax (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.
DataLoadergrain (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.

A whole train step in the running example's Flax NNX twin, run
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.

Go deeper. The JAX training stack owns the libraries: NNX state (section 1) and transforms (2), Linen and Equinox (3), optax (4), orbax (5), grain (6), float16 loss scaling (7). PyTorch to JAX owns the port: four differences on one step (section 1), every default that differs (2), the equivalence test (4) and its Divergence hunter. The Training lab keeps what spans both: the four module libraries side by side, optax against PyTorch's AdamW, both twins trained 4,000 steps, an orbax resume bit for bit, grain and three precisions.

5. Sharding and scale

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:

StrategyBatch specWeight specCollectives XLA insertsPyTorch
Data parallelP('data')replicated, P()all-reduce of gradientsDDP
FSDP (ZeRO-3 style)P('data')split on 'data' tooall-gather weights before use, reduce-scatter gradientsFSDP2
Tensor parallelP('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 backwardMegatron-style TP, DTensor

What the compiler inserted for six layouts of the running example on 8 simulated devices: one missing annotation costs 32 times the bytes

LayoutMeshCollectives in the compiled stepBytes in themWeights per deviceLoss vs one device
One device1none03.3 MB0.0e+00
Data parallel81 all-reduce3.3 MB3.3 MB4.8e-07
FSDP, weights annotated only894 all-gather, 36 all-to-all, 80 all-reduce174.1 MB0.4 MB4.8e-07
FSDP (ZeRO-3 style)878 all-gather, 70 all-reduce6.6 MB0.4 MB4.8e-07
Data x tensor parallel2 × 418 all-reduce26.1 MB0.9 MB7.2e-07
FSDP x tensor parallel2 × 44 collective-permute, 62 all-gather, 58 all-reduce28.1 MB0.5 MB7.2e-07
Sequence sharded811 all-gather, 6 all-reduce37.0 MB3.3 MB9.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.

How it was counted, and three things the counts show

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).

Details the child pages carry with their runs

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.

Go deeper. Sharding and scale owns sharding in JAX: Mesh, PartitionSpec and jit with shardings (section 1, "One weight, six PartitionSpecs"), Auto, Explicit and Manual (2), propagation (3), shard_map (5), every strategy at two sizes (6), collective costs (10), choosing a mesh (11), many hosts (12); its Fig. 1 puts two annotations on 8 devices and finds the one collective the compiler inserts. The Sharding lab keeps the running example's six layouts with their collectives, a PartitionSpec playground and a ring animator. The strategies framework-free: Distributed Training; why the interconnect decides: Interconnects and scaling.

Why sharding is not optional: replicated training state outgrows any chip; FSDP divides it by the device count

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).

6. TPUs from the programmer's side, and Pallas

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:

  • MXU: a systolic array of 128 × 128 multiply-accumulate cells (256 × 256 on v6e and TPU7x), bf16 in, fp32 accumulation; peak only when matmul dimensions are multiples of its size. VPU: the slower vector unit for everything elementwise.
  • VMEM: a software-managed on-chip scratchpad that tiles are copied into from HBM, the chip's main memory; no hardware cache does it for you.
  • ICI: direct chip-to-chip links forming a 2D torus (v5e, v6e) or a 3D torus (v4, v5p, Ironwood). A pod is the largest set joined this way, a slice the part you rent; Multislice joins slices over the slower data-centre network. v5p's pod is 8,960 chips, but the largest slice Cloud schedules is 6,144 (16 × 16 × 24), and Multislice reaches 18,432 (vendor, Cloud TPU v5p page, last updated 2026-10-13).
  • A JAX device is not always a chip: on v4 and v5p the two TensorCores are fused into one device ("megacore"); on TPU7x each core is a device, so a 4-chip Ironwood host shows 8 (jax/_src/tpu_info.py at jax-v0.11.2).

Four current generations: peak grew faster than bandwidth, so the batch needed to keep the matrix units busy (the ridge) grew too

Chip (Cloud name)Trackbf16 peak per chipHBM, bandwidthLargest podRidge point derived
v5e (2023)efficiency197 TFLOP/s16 GB, 819 GB/s256 chips, 2D torus241
v5p (Dec 2023)performance459 TFLOP/s95 GiB, 2,765 GB/s8,960 chips, 3D torus166
v6e Trillium (May 2024)efficiency918 TFLOP/s32 GB, 1,638 GB/s256 chips, 2D torus560
TPU7x Ironwood (announced Apr 2025)both2,307 TFLOP/s (4,614 fp8)192 GiB, 7,380 GB/s9,216 chips, 3D torus313

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.

Two notes on the figures

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.

Predict: a 7B model decodes for a batch of 8 users on one v6e chip. What fraction of the chip's bf16 peak can its weight matmuls reach at best?

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.

Two kernels run here in interpret mode, and corrections to the old page

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.

Corrections to the old page
The old table gave Ironwood as "GA Apr 2026"; Google's 2025-11-06 post said it "will be generally available in the coming weeks", and the exact date is unconfirmed. Its "more than 4x Trillium per chip" is Google's headline: the bf16 peaks give 2,307 ÷ 918 = 2.5x, and only the fp8 peak (which Trillium cannot run faster than bf16) gives 4,614 ÷ 918 = 5.0x derived. Read a vendor's "x times faster" by asking which precision and which workload.
Go deeper. TPU programming and performance owns the chip as a target: its Fig. 1 draws one chip as your program meets it and Fig. 2 a weight on the MXU, then generations (section 2), rooflines (3), tiles and padding (4), precision (5), slices and the mesh on the torus (7), profiling (8), MFU (9). Pallas kernels owns kernels: the grid and BlockSpecs with a grid stepper (section 2; its Fig. 1 follows one grid step on a TPU core), flash attention with its replay (5), pipelining (6), testing without a TPU (9), and the Kernel playground tab. The TPU and Pallas lab keeps what spans both: the roofline calculator, the mesh on the torus, a first tiled matmul and HBM traffic by block size. The chip as hardware: TPUs and other accelerators; Triton: Topic: cuda-and-gpu-programming.

7. The codebases worth reading

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.

CodebaseWhat it isRead it for
MaxTextGoogle'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.
TunixGoogle'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.
AXLearnApple's JAX library on which its foundation models were trained (section 1). Pushed 2026-07-08.A second large-company stack, configuration-heavy.
big_visionGoogle 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.

MaxText's own pre-training benchmarks (its "Gold" models): 44 to 65% MFU, by a FLOP count that has since changed

ModelChipsConfigurationMFUTokens/s per chip
Llama 2 70Bv6e256 chips, bf16, sequence 4,09643.8%900
Llama 3.1 8Bv6e256 chips, bf16, sequence 8,19245.46%7,207
Llama 3.1 70Bv6e256 chips, bf16, sequence 8,19250.33%960
Llama 2 70Bv5p512 chips, bf16, sequence 4,09665.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.

Go deeper. JAX LLM codebases: MaxText, Tunix, levanter reads each at a pinned commit: MaxText's config (section 1), the running example inside its decoder (2), logical axis rules (3; its Fig. 3 maps logical names to chips), its train step (4), MFU counting (6), Tunix (7), levanter in Marin (8), which to start from (10). The Tool map has their lineage (Linen to NNX, T5X and Pax to MaxText).

8. JAX against PyTorch, honestly

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.

AxisJAXPyTorchEdge
DebuggingInside 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 stepjit 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 transformsgrad, 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
ShardingOne 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
TPUsNative: 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 kernelsSupported (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 models12,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
ReproducibilityRandom 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 dataThe 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.

9. Choosing

Choose JAX when

  • you will train on TPUs and want the most mature path (XLA and the TPU grew up with it; TorchTPU is the newer route);
  • you want one program that a compiler shards across hundreds of chips, with sharding kept out of the model code (MaxText's logical axes);
  • your research composes transformations: per-example gradients, Hessian-vector products, ensembles by vmap over stacked parameters;
  • bit-reproducible runs matter (explicit keys, levanter's preemption-proof determinism).

Stay with PyTorch when

  • you train and serve on NVIDIA GPUs and need the newest kernels the week they appear;
  • you start from Hugging Face checkpoints and PyTorch-first tools (vLLM, SGLang, TRL);
  • your team debugs by stepping through eager code, and the model changes shape a lot (variable-length everything);
  • the codebase already exists: even on TPUs, try TorchTPU before rewriting in JAX.

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.

Depth: mistakes, interview rehearsal

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.

Python if on a traced value

The 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).

A shape that depends on the data

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).

Assigning into an array

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.

Side effects that run once (print, appending to a list, a global counter)

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.

A global read inside jit is frozen

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.

Reusing a random key

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.

Shapes that change every step

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).

Out-of-bounds indexing does not raise

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.

Timing dispatch instead of compute, or including the compile
JAX returns from a call as soon as the work is queued (asynchronous dispatch, like CUDA). Time with 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.
Not donating the training state
Without 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.
Expecting float32 matmuls on a TPU
On TPU the default precision of a float32 matmul uses bfloat16 passes on the MXU, so results differ from a float32 GPU or CPU run in the third or fourth digit. Ask for more with precision=jax.lax.Precision.HIGHEST or jax.default_matmul_precision("float32") when comparing against PyTorch (JAX docs, default_matmul_precision).

Interview questions

Answer each yourself first; the design questions have no single right answer, so say the constraint that decides it.

What does jax.jit do on the first call, and on the second?
First call: run the Python function once with tracers (shape and dtype only), record a jaxpr, lower it to StableHLO, compile it with XLA for this device, cache the executable under the signature (shapes, dtypes, static arguments, shardings), then run it. Second call with the same signature: look up the cache and run; Python inside the function does not run at all. A new shape, dtype or static value starts again from tracing.
How does JAX compute gradients without a tape?
It differentiates the recorded program, not a run. 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.
Why must functions be pure, concretely?
Because the function body runs only while tracing. A print, a list append or a global counter happens once, at trace time, and never again on cached calls; a global read is frozen into the compiled program as a constant. Anything that should change between calls must come in as an argument and go out as a result.
In JAX, what changes in the code to go from data parallel to FSDP to tensor parallel?
Only the partition specs. Data parallel: batch 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.
Design: shard a 70B dense model for training on a v5p pod. What mesh, and why?
Start from memory, then communication. Memory: bf16 parameters about 140 GB and fp32 Adam moments about 560 GB, plus about 10.5 TB of activation checkpoints at a batch of 1,024 sequences of 4,096 tokens (two per layer), about 11.2 TB in all against about 96 GB of HBM per chip (the scaling book's round figure; Google lists 95 GiB): about 117 chips is the floor by memory, so memory is not what decides it on a pod. Communication decides it: the batch of 1,024 sequences limits pure data parallelism to 1,024 chips, and pure FSDP over the whole pod leaves too few tokens per chip to hide its all-gathers. The scaling book's answer is mixed FSDP and tensor parallelism, about 2,048-way FSDP by 4-way tensor parallel on 8,192 of the pod's 8,960 chips, at an assumed 40% MFU about 44 days for 15T tokens (How to Scale Your Model, part 6, Google DeepMind, 2025-02-04; its takeaway also lists 1,024-way data, 2-way sequence and 4-way tensor parallel, so the exact split varies). A caveat: 8,192 chips is more than one v5p slice, since the largest Cloud schedules is 6,144 chips (16 × 16 × 24; the 16 × 20 × 28 pod is not one schedulable slice), so in practice that run is two or more slices joined by Multislice over the data-centre network, with a data-parallel axis across slices. Map the tensor-parallel axis onto the fastest, shortest ICI dimension, keep the FSDP axis on the rest, and put only the data-parallel axis across slices, on the slower data-centre network (MaxText's dcn_data_parallelism setting), and leave pipeline parallelism out unless that network becomes the bottleneck.
Debug: your JAX train step is 3x slower than expected. What do you check, in order?
  1. Are you timing correctly? Exclude the first call (compilation) and call block_until_ready(); JAX dispatches asynchronously.
  2. Recompiles: set jax_log_compiles (or jax_explain_cache_misses); varying shapes or a Python value passed as static recompiles every step.
  3. Host syncs: float(loss), .item(), printing or NumPy conversion every step stalls the pipeline; log every N steps.
  4. Input pipeline: is the device waiting on data? The profiler shows idle gaps between steps.
  5. Surprise communication: read the compiled HLO (jit(f).lower(...).compile().as_text()) for unexpected all-gathers or all-reduces; a missing sharding constraint can replicate a large array.
  6. Shapes and precision: dimensions not multiples of 128 waste the MXU; fp32 where bf16 was intended halves throughput or worse.
  7. Memory pressure: no buffer donation, or rematerialisation recomputing too much.
  8. Then profile with jax.profiler (XProf trace viewer) rather than guessing.
Why do TPUs (and GPUs) want large batches?
A weight matmul's arithmetic intensity is about the number of tokens per chip, and the chip needs about 166 (v5p) to 560 (v6e) FLOPs per byte of HBM traffic to keep its matrix units busy (section 6). Below that it waits on memory; communication sets a similar floor for sharded training.
When would you write a Pallas kernel instead of trusting XLA?
When the profile shows a memory-bound sequence XLA does not fuse well or a structure it cannot express efficiently: attention variants (flash or splash attention), ragged or block-sparse matmuls, quantised matmuls, MoE routing. Not by default: the kernel must define its own gradient and is tied to one backend's tiling rules.
pmap, shard_map, and jit with shardings: which, today?
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).
You port a PyTorch model to JAX and the losses differ. What do you check?
The defaults first, because they differ silently (read from the installed versions, 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.

Child pages

Each child owns its subject in depth with its own measured examples; times are each page's own header.

JAX core: arrays, tracing, jit, grad, vmap and pytreesHow one Python function becomes a compiled, differentiated and batched program: tracers, interpreters, jaxprs, the jit cache, control flow, autodiff and custom rules, vmap, pytrees and keys, read in JAX's source.Section 2. Child page, about 45 min, plus 25 in closed details.
XLA and compilation: jaxprs, StableHLO, fusion and recompilesFrom jaxpr to machine code: lowering, PJRT, the pass pipeline, fusion, layouts, buffers, remat, caches, export, recompiles, profiling and flags; labs Pass diff viewer, Fusion explorer, Recompile detective, Profile reader.Section 3. Child page, about 39 min, plus 14 in closed details.
The JAX training stack: Flax NNX, optax, orbax and grainFlax NNX state and transforms, Linen and Equinox, optax link by link, orbax resumes, grain, float16 loss scaling, a complete script preempted and resumed.Section 4. Child page, about 34 min, plus 21 in closed details.
PyTorch to JAX: porting a small LMThe running example ported: four differences on one step, every default that differs, weight conversion, the equivalence test, drift, GPT-2 by hand, interop; labs Divergence hunter, Port drills.Section 4. Child page, about 28 min, plus 17 in closed details.
Sharding and scale: Mesh, GSPMD, shard_map and multi-hostMesh and PartitionSpec, Auto, Explicit and Manual, propagation, shard_map, every strategy measured, context, pipeline and expert parallelism, collective costs, choosing a mesh, many hosts; lab Mesh designer.Section 5. Child page, about 46 min, plus 26 in closed details.
TPU programming and performanceThe chip as your program meets it: generations, rooflines, tiles and padding, precision, memory planning, slices and the torus, profiling, MFU and cost per token; labs Roofline lab, Slice planner.Section 6. Child page, about 33 min, plus 13 in closed details.
Pallas kernelsJAX's kernel language: the grid and BlockSpecs, row kernels, LayerNorm, flash attention, pipelining, scalar prefetch, testing without a TPU, production kernels, block sizes, Triton compared; lab Kernel playground.Section 6. Child page, about 38 min, plus 13 in closed details.
JAX LLM codebases: MaxText, Tunix, levanterProduction JAX read at pinned commits: MaxText's config, model, logical axis rules, train step, scan and remat, MFU counting; Tunix; levanter in Marin; which to start from; labs Codebase map, Config explorer.Section 7. Child page, about 34 min, plus 8 in closed details.