The JAX training stack: Flax NNX, optax, orbax and grain

How the four libraries around JAX turn a model into a training run that compiles once and resumes as the same run, measured on the parent topic's tiny character LM (Apple M1 Pro CPU). Data as of October 2026. Reading: 33 min, plus 21 in closed details.

A JAX training run is one compiled, pure step function applied to a pytree of state; Flax NNX turns your model object into that pytree, optax is a pair of pure functions over it, orbax writes it to disk, and grain makes the data position a few integers inside it. So the run you resume is the same run only when every piece of state that decides the next step (parameters, optimiser moments and step count, random streams, data position) went into the checkpoint.

One training step: everything that decides step t + 1 is state you can name, save and restore

  1. grain hands over a batch. Record i is computed from i, a seed and the epoch (section 6): a shuffled permutation of the running example's 7,781 windows, read by worker processes and batched 32 at a time. The cells are the real window indices of batch 0, coloured by index. The loader's whole position is a few integers.
  2. Flax NNX splits the model at the jit boundary. The object becomes its graphdef (the structure: 170 nodes, every attribute static; it keys the compile cache; the wire frame) and its state (69 leaves, 826,368 parameters plus the dropout stream's key and counter), which enters the compiled step as traced arrays (section 1).
  3. Loss, then nnx.grad. The batch runs forward through the state to a scalar loss; nnx.grad differentiates with respect to the nnx.Param leaves only, so the gradients are a pytree shaped like the parameters (section 2).
  4. optax: a chain the gradient passes through. Clip by global norm, Adam's moments, decoupled weight decay, times minus the learning rate: each is an update function that reads its own slice of the optimiser state and returns a new one. That state (141 leaves, two moment trees and step counts) is arrays too (section 4).
  5. The new state goes back into the object. nnx.jit writes the updated parameters, the advanced RNG counter and the optimiser state back into your Python objects after the call; metrics accumulate as running sums on the device (section 8). The graphdef did not change, so the next call reuses the compiled step.
  6. orbax saves it while training continues. One checkpoint holds four items: model state with its RNG, optimiser state, the grain iterator and a JSON item with the step. save() copies the arrays to host memory and returns (0.14 s here); a background thread writes them (done at 0.36 s) while the next batch is already being trained on (section 5). The graphdef is the one part not saved: it is rebuilt from your code, and the same structure reuses the same compiled step.

Six layer plates stand for the 69 state leaves; counts and times were measured on the running example below. Drag to turn the scene.

You need: jax.jit, jax.grad, pytrees and PRNG keys (JAX core), and a PyTorch training loop, which the table below maps onto this stack. New terms:

Variable: a typed box holding one array of an NNX module (nnx.Param, nnx.RngKey, ...).
graphdef: the module's structure with no arrays; static and hashable.
filter: a rule selecting Variables by type or path (nnx.Param, ...).
GradientTransformation: optax's (init, update) pair of pure functions.
CheckpointManager: orbax's object that saves, keeps and restores numbered steps.
MapDataset: grain's random-access dataset, record i computed from i and a seed.

What you know from PyTorch, and where it went

PyTorchJAX stackThe difference that mattersSection
nn.Module, nn.Parameter, buffersnnx.Module, nnx.Param, other nnx.Variable typesstate is typed and filterable; transformations need it split out1
the global RNG, torch.manual_seednnx.Rngs: a key and a counter stored in the modelrandomness is state you must carry through jit and into checkpoints1
torch.compilennx.jit (a jax.jit that understands modules)retraces when the module's structure changes; side effects run once2
a Python for over layersnnx.vmap to create stacked layers, nnx.scan to run themone traced layer instead of N: the program stops growing with depth2
DTensor placements on parametersnnx.with_partitioning + logical axis rulesparameters are born sharded on the mesh2
torch.optim.AdamW, param groups, schedulersoptax.chain, partition, masks, schedule functionsnothing is mutated; hyperparameters change only if injected into the state4
gradient accumulation by hand, GradScaleroptax.MultiSteps, apply_if_finite, jmp loss scalesall are transformations or tiny pure objects you jit4, 7
torch.save, torch.distributed.checkpointorbax CheckpointManagerasync and sharded by default; you restore into a target you build5
DataLoader (+ torchdata's StatefulDataLoader)grain MapDataset / DataLoaderrecords are a pure function of index and seed; the position is checkpointable6
torchmetricsnnx.metrics (or clu)metrics accumulate on device inside the compiled step8

The running example is the parent topic's decoder-only character LM: 826,368 parameters (4 layers, width 128, 4 heads, context 128, vocabulary 65) trained on TinyShakespeare's 7,781 windows of 129 characters, with the AdamW chain of section 4. Losses, equalities, counts and shapes are deterministic and transfer to any backend; times are rough single runs on a shared CPU and say nothing about TPUs or GPUs. Labels: measured run here, derived computed with the formula shown, published from a dated source.

Provenance: versions, machine, and what this page does not repeat

Every number was measured 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, jmp 0.0.4 and torch 2.14.1, unless it is labelled published; the machine was shared with other jobs (1-minute load average 30 to 57 during these runs). PyTorch, Flax NNX and plain JAX versions of the model start from the same initial weights (the root's src/data/README.md). The parent page, Topic: jax-and-tpu, introduces each library in its Training lab tab (graphdef and state, an optax chain builder checked against the library, a checkpoint resumed bit for bit, bfloat16 with a float32 master copy); this page goes one level down.

Not repeated here. The line-by-line port from PyTorch and every default that differs between the two (LayerNorm epsilon, GELU, initialisers, weight layout, AdamW decay) are on PyTorch to JAX: porting a small LM; the root's Training lab keeps the optax-against-PyTorch check. Sharding strategies are on Sharding and scale; tracing and pytrees from zero on JAX core; MaxText and other LLM codebases on JAX LLM codebases.

1. Flax NNX: where the state lives

jax.jit, jax.grad and jax.vmap transform pure functions of pytrees (nested lists, tuples and dicts whose leaves are arrays). A PyTorch-style model is an object that owns its weights and changes them in place. Flax NNX keeps the object, so model code reads like PyTorch, and converts it to a pytree at every transformation boundary.

Variables: typed boxes for every array

Every array an NNX module owns sits in an nnx.Variable, and the subclass says what kind of state it is. PyTorch has two kinds (parameters the optimiser sees, buffers it does not); NNX has as many as you like, and every API that moves state takes a filter over them.

Variable typeHoldsPyTorch counterpart
nnx.Paramtrainable weights (nnx.Linear.kernel, bias, LayerNorm.scale, Embed.embedding)nn.Parameter
nnx.BatchStatrunning mean and variance of nnx.BatchNormregister_buffer("running_mean")
nnx.RngKey, nnx.RngCount (both nnx.RngState)a PRNG key and how many times it was used, per streamthe global torch.Generator, which is not part of the model
nnx.Cache, nnx.IntermediateKV caches for decoding; values recorded with sowtensors kept on the module by hand; forward hooks
nnx.OptState and friendsthe optimiser's arrays, inside nnx.Optimizeroptimizer.state_dict()["state"]
your own subclassanything: a step counter, an EMA copya custom buffer

Source at flax v0.12.10: , , . Arrays are read and written with v[...]; v.value still works in 0.12 but warns that it is deprecated.

The running example's real state, split by a filter, module by module

Model
Filter

still in the object (by module)

group 1

rest (...)

split: one object becomes a graphdef and states

graphdef, state = nnx.split(model) walks the object graph. The graphdef records every node (module, list, Variable) and every non-array attribute; the state is a pytree of the arrays, keyed by path. nnx.merge(graphdef, state) builds an equivalent object; nnx.update(model, state) writes arrays back into an existing one. With filters, nnx.split(model, f1, f2, ...) returns one state per filter: a filter is a Variable type, a path predicate (nnx.PathContains("kernel")), a combination (nnx.All, nnx.Any, nnx.Not), or ... for "everything else". It is how you say "differentiate the Params only", "decay only the kernels", "vectorise the stacked layers, broadcast the rest".

Predict, then watch the split: with + dropout and the filter nnx.Not(nnx.Param), how many of the leaves land in group 1?

    Every leaf with its Variable type, path and shape, as recorded by src/runs/ts_nnx.py (flax 0.12.10) measured; bars are proportional to the square root of the element count. With dropout the answer is two: the dropout stream's RngKey and RngCount; the 69 others are Params. Each Variable goes to the first filter that matches it, and the filters must cover every leaf: forgetting ... raises "Non-exhaustive filters".

    The graphdef of the running example has 170 nodes and 571 attributes, against 69 state leaves measured. Its static attributes include things a PyTorch user would never think of as part of the model: in_features, use_bias, dtype, param_dtype, precision, the dot_general function itself. That is the point: everything in the graphdef is a compile-time constant. Two models built with different seeds have graphdefs and equal hashes, so nnx.jit reuses one compiled program for both; change any static attribute and the graphdef, the cache key and the program all change (section 2).

    The graphdef in detail: node kinds, static attributes, the split error, sources

    Node kinds in the running example's graphdef (src/runs/ts_nnx.py, E1). GenericPytree nodes are the per-module bookkeeping for NNX's pytree registration.

    Static attributes collected from every node (values as recorded; functions by name):

    The start of repr(graphdef) ( characters in all):

    
    

    What forgetting ... on a model with dropout prints measured:

    Source: GraphDef at ; split at ; merge at ; update at .

    Randomness is state: nnx.Rngs

    PyTorch draws dropout masks from a global generator that advances by itself. JAX has no global generator: a random function takes a key and returns the same numbers for the same key. NNX stores a key and a counter per stream (params, dropout, ...) inside the model; each draw folds the counter into the key and increments it. Measured on the running example with dropout measured:

    The third row is a real bug pattern: split once, call a pure jax.jit function with the state and never return the new state. The counter advances inside the trace, the advanced value is dropped, and every step gets the same dropout mask, with no error. nnx.jit avoids it by writing the updated state back into your object; with raw jax.jit return nnx.state(model) and use it next time. model.eval() sets deterministic=True on every Dropout (and use_running_average on BatchNorm), like PyTorch's.

    eval mode measured; sources

    The eval output equals the dropout-free model with the same weights exactly (largest difference ). Source: Rngs at , RngStream at .

    Shared modules: graph mode and tree mode

    The running example with its output head tied to the token embedding holds one Embed referenced twice. A pytree cannot express sharing: each leaf appears once. Graph mode tracks object identity, stores the shared array once and restores the sharing on merge; tree mode treats modules as plain pytrees and refuses duplicates ("Duplicate Param"). In flax 0.12.10 graph mode is by default and graph updates (, ); every API takes graph=. On the tied model graph mode splits into leaves and parameters (the untied count minus the 128 x 65 head) measured.

    The defaults are planned to change
    Flax's design note FLIP 5310 plans to make tree mode the default; shared modules and nnx.grad's Params-only default then go away. Code that ties weights by sharing a module, or relies on that default, should pin nnx.set_graph_mode(True) or use nnx.compat.*. Not yet the default at 0.12.10 measured.
    FLIP 5310 in its own words, and the tree-mode error on the tied model

    "Tree Mode NNX" (dated Mar 4, 2026, in the pinned clone) says: "The goal will be to have the default value for nnx_graph_mode and nnx_graph_updates to be set to False" (). Under tree mode, shared references, prefix filters (StateAxes, DiffState, StateSharding) and structure changes inside transforms go away, and nnx.grad returns gradients of the input's own type ().

    Pin graph mode, or tie by computing the head from the embedding's array instead of sharing the module.

    2. NNX transformations: jit, grad, the optimiser, scan, sharding

    nnx.jit: what retraces, what is written back

    nnx.jit(f) is jax.jit with a wrapper: it splits every module argument into graphdef and state, passes the graphdefs as static (hashed into the cache key) and the states as traced arrays, merges them back into objects inside, and after the call copies changed Variables back into your objects. So a Python side effect runs only while tracing, and a change to the module's structure retraces. The running example with a custom StepCount Variable incremented on every call measured:

    @nnx.jit
    def step_count(m, x):
        TR["n"] += 1                   # Python side effect: runs only when tracing
        return m(x).mean()

    From src/runs/ts_nnx.py (E5). "Traces" counts how many times Python ran the body; "StepCount" is the Variable incremented inside the compiled program and written back. Setting h to the value it already had did not retrace (the graphdef compares equal); one added Param took the trace count from 1 to 2, a new batch shape to 3.

    In a training loop the danger is code that adds, removes or re-creates a submodule or a Python attribute every step: each step then compiles from scratch. Keep per-step values in Variables or pass them as arguments. The root's Compiler lab tab measures what a recompile costs; XLA and compilation shows how to find the cause at scale. Source: .

    nnx.grad and nnx.Optimizer

    nnx.grad(loss_fn)(model, x, y) differentiates with respect to the model's nnx.Param leaves only, because its default argnums is nnx.DiffState(0, nnx.Param): on the counter model the gradient was a State of 69 Param leaves, without the StepCount measured. A narrower filter differentiates a subset: nnx.DiffState(0, nnx.All(nnx.Param, nnx.PathContains("attn"))) gave 32 leaves (the 4 x 8 attention weights and biases). The PyTorch counterpart is requires_grad_(False) on everything else, but nothing is mutated and the choice is per call (source ; tree mode will change this default, section 1).

    nnx.Optimizer(model, tx, wrt=nnx.Param) runs tx.init on the filtered state and stores the result as Variables, so the optimiser passes through nnx.jit and into a checkpoint like a model; opt.update(model, grads) calls tx.update and writes the new parameters into the model. Since Flax 0.11 it holds no reference to the model (which is why update takes it) and wrt is required. For the AdamW chain its state has 141 leaves and 1,652,739 numbers measured: two moment trees of 826,368 each plus step counters.

    Details: a gradient that is pure float noise, the missing-wrt error, the optimiser's state by type

    The key-projection bias gradient is at most (1.6e-11) against for the query kernel: zero in exact arithmetic, because a constant added to every key shifts each softmax row by a constant (the root's Training lab explains the consequences for Adam; section 4 shows what Adam's ε does with it).

    Without wrt measured:

    State by type: . A sample:

    Source: ; the message at .

    The program stops growing with depth once the layers are scanned

    Depth

    Scan over layers: one traced block instead of four

    A Python for loop over layers is unrolled when traced: 4 blocks give 4 copies of the block in the jaxpr, 48 give 48, and compile time grows with depth. Create the blocks with nnx.vmap over a split of the Rngs, so every parameter gets a leading layer axis (a [128, 512] kernel becomes [4, 128, 512]); run them with nnx.scan, which lowers to one lax.scan whose body is traced once. This is the NNX spelling of MaxText's scan_layers and of Linen's nn.scan.

    @nnx.split_rngs(splits=cfg["n_layers"])
    @nnx.vmap(in_axes=(0,), out_axes=0)
    def make_blocks(r):
        return MN.Block(cfg, rngs=r)          # the running example's Block, unchanged
    self.blocks = make_blocks(rngs)          # every Param now has a leading axis of 4
    
    @nnx.scan(in_axes=(nnx.Carry, 0), out_axes=nnx.Carry)
    def body(x, blk):
        return blk(x)
    x = body(x, self.blocks)

    Predict: at 16 layers, how many top-level jaxpr equations does each version have? Pick a depth and a mode; each replays its four steps.

    1. Before: a Python loop. The blocks are separate modules and every parameter keeps its own shape: fc1's kernel is [128, 512], once per block.
    2. Tracing runs the loop. Each block's operations are appended to the jaxpr again, about 257 top-level equations per block (derived from the 4- and 8-layer counts).
    3. XLA compiles all of it. The optimised HLO grows with the depth too: 5,497 lines at 4 layers, 19,213 at 16.
    4. Depth against size. 1,147 equations at 4 layers, 2,175 at 8, 4,231 at 16: the program grows linearly with depth, and its compile time with it (0.6 s to 1.0 s here, rough).

    Loss and gradient of a training batch, traced and compiled with jax.jit on CPU (src/runs/ts_nnx.py, E7) measured. The logits of the two versions agree to 7.2e-7 (XLA fuses the two programs differently).

    On this CPU at 4 to 16 tiny layers the scanned program compiled more slowly (about 0.9 to 1.3 s against 0.6 to 1.0 s, single rough runs): the loop machinery has a fixed cost. The saving is in growth; at the 32 to 128 layers of real LLMs the unrolled program is what dominates compile time (not run here: the measured trend is the evidence, the extrapolation is not). The cost of scanning: every layer must have identical structure, per-layer Python logic is gone, and XLA cannot fuse across layer boundaries. Pair it with nnx.remat to choose which activations each layer saves. Source: , , .

    Sharding annotations on parameters

    NNX attaches a layout to each parameter at creation: wrap an initialiser with nnx.with_partitioning(init, ("embed", "mlp")), where the names are logical axes of the weight, and map logical names to mesh axes once with nnx.logical_axis_rules. Under jax.set_mesh(mesh) the parameter is born sharded ("eager sharding", on by default in 0.12.10: ). The optimiser's moment trees inherit each parameter's sharding, so optimiser memory is split exactly like the weights; the compiler inserts the collectives (12 all-reduces in one training step of the layout below) measured. Choosing the mesh and the rules for a real model is Sharding and scale's subject; MaxText's rules are on JAX LLM codebases, section 3.

    The running example annotated Megatron-style on a (data 2, model 4) mesh: every parameter's spec and shard

    On 8 simulated CPU devices, with rules measured:

    From src/runs/ts_nnx_shard.py. "Copies" is how many of the 8 devices hold the same shard (replication along the other axis). Shapes and specs are real; the devices are simulated on one CPU.

    The fc1 moments are , shards . One compiled training step holds collectives (GSPMD and Shardy). An annotated model built with no mesh in scope now fails instead of silently ignoring the annotation:

    With nnx.use_eager_sharding(False) the annotation stays as metadata only (out_sharding=('embed', 'mlp') on the Variable) and the array sits on one device, which is how pre-0.12 code behaved; that is also the switch for single-device tests. Source: , .

    3. Reading other people's code: Linen and Equinox

    Most JAX model code written before 2025 is Flax Linen (MaxText migrated to NNX only in mid 2026, per the root's Reading tab); much research code is Equinox. What differs is where each keeps its state, which this table says in one screen; the root's Training lab runs the same block in NNX, Linen, Equinox and Haiku against PyTorch, and its Tool map has their status (Haiku in maintenance mode, Linen maintained but not recommended for new code).

    Where the state isFlax NNXFlax LinenEquinox
    arrays live inVariables inside the objecta separate variables dict of collectionsthe module's own fields
    to a pytreennx.split / nnx.mergealready one (variables)already one; eqx.partition for arrays only
    mutable stateVariables written back by NNX transformsmutable=[...], returned updatesexplicit eqx.nn.State in and out
    randomnessnnx.Rngs stored in the modelrngs={...} per callkey= per call
    shapesexplicit d_ininferred at initexplicit, one example at a time
    weight layoutkernel [in, out]kernel [in, out]weight [out, in]

    Two habits carry over. In Linen code look for init/apply, the collection names, mutable= and rngs= at every call site: the train step carries params, batch_stats and the optimiser state as three separate trees (often bundled in flax.training.train_state.TrainState). In Equinox code the model is itself the pytree, so look for the eqx.filter_* transforms. nnx.bridge.ToNNX and ToLinen wrap one in the other, which is how a codebase migrates one module at a time (Flax's bridge guide; source ).

    Linen in detail, with the errors you meet (measured)

    A Linen module is a frozen dataclass of hyperparameters. variables = model.init(rngs, x) runs it once to create every array, grouped into collections; model.apply(variables, x) runs it as a pure function. A block with Dense, BatchNorm, Dropout and sow (a test module in src/runs/ts_linen_eqx.py):

    class LBlock(nn.Module):
        d_ff: int = 512
        @nn.compact
        def __call__(self, x, train: bool):
            h = nn.Dense(self.d_ff)(x)                 # input width read from x at init time
            h = nn.BatchNorm(use_running_average=not train, momentum=0.9)(h)
            h = nn.gelu(h, approximate=False)
            self.sow("intermediates", "hidden_mean", h.mean())
            h = nn.Dropout(0.1, deterministic=not train)(h)
            return nn.Dense(x.shape[-1])(h)
    • init returned the collections : params is what the optimiser sees; batch_stats is the running mean and variance. @nn.compact defines submodules inline and infers input sizes from the first input, so there is no d_in anywhere, unlike NNX and PyTorch.
    • Training mode updates batch_stats, so the collection must be declared mutable; apply then returns (y, updates) and you merge the updates yourself. Forgetting it measured:
    • Dropout needs an RNG passed per call (rngs={"dropout": key}); without it:
    • mutable=["batch_stats", "intermediates"] returned ; the running mean moved by up to in one call; the sown value is in updates["intermediates"]. Parameters never come out of apply: they are only an input.
    • Bridging. nnx.bridge.ToNNX(linen_module, rngs=...) plus nnx.bridge.lazy_init runs a Linen module inside NNX; its state became measured. nnx.bridge.ToLinen goes the other way.
    Equinox in detail: frozen modules, non-array leaves, filtered transforms (measured)

    An eqx.Module is a frozen dataclass registered as a pytree: its fields are its leaves. There is no split; you pass the model itself to transformations. Three consequences, measured on a two-layer MLP holding jax.nn.gelu as a field:

    • Frozen. model.fc1 = ... raises : . Changes are made out of place: eqx.tree_at(lambda m: m.fc1.bias, model, new) returns a new model (bias sum became ; the original is untouched).
    • Not every leaf is an array. The function field is a leaf too, so plain jax.jit on a function taking the model fails:
      eqx.filter_jit treats array leaves as traced and everything else as static, and runs (). eqx.filter_grad differentiates only floating-point arrays: the gradient had array leaves. The general tool is params, static = eqx.partition(model, eqx.is_array) and eqx.combine(params, static) ( and leaves here), the Equinox spelling of NNX's split and merge.
    • Layers act on one example (eqx.nn.Linear maps a vector); you jax.vmap over the batch. Its weight is [out, in] like PyTorch ( for 128 to 512). Stateful layers (BatchNorm) keep their running statistics in a separate eqx.nn.State object that the call takes and returns: make_with_state built a and each call returned a new one.

    4. optax, transformation by transformation

    An optax GradientTransformation is a named tuple of two pure functions: init(params) -> state and update(grads, state, params) -> (updates, new_state) (). optax.chain(t1, t2, ...) feeds each one's output into the next and keeps a tuple of their states (). Every optimiser you know is a chain: optax.adamw is scale_by_adam, then add_decayed_weights, then scale_by_learning_rate (). Because the state is just more arrays, it is jitted, sharded and checkpointed like the model. The algorithms themselves (why Adam, AdamW, Lion, Muon, which schedule) are Optimisers and learning-rate schedulers's; this section is how optax builds and runs them.

    One real step through the running example's chain

    The running example uses chain(clip_by_global_norm(1.0), adamw(lr_schedule, b1=0.9, b2=0.95, eps=1e-8, weight_decay=0.1, mask=decay_mask)). A script recomputes every stage by hand on the real gradients of the first 12 steps and checks it against tx.update: the largest difference was 7.3e-11 measured, float rounding in the bias correction. Step 0 for the noise coordinate shows the point of ε; step 0 for any weight shows the first update is the sign of the gradient.

    Predict: at step 0 the gradient norm was 4.616. What does clipping at 1.0 multiply every gradient by, and how big is Adam's direction for a weight before the learning rate?

    1. The gradient. g for the eight tracked numbers (columns) on training batch t, from jax.grad. Every row of bars is scaled to its own largest value. At step 0 the key bias's gradient (seventh column) is about 5e-13, float noise, against 0.027 for the embedding, so it does not show.
    2. clip_by_global_norm(1.0). The global norm over all 826,368 gradients was 4.616 at step 0, so clipping scaled every gradient by 0.2166: the row keeps its shape and shrinks.
    3. scale_by_adam updates its state. m = 0.9 m + 0.1 g and v = 0.95 v + 0.05 g²; from a zero start m is a tenth of the gradient and v (always positive) a twentieth of its square. These two trees are the optimiser state a checkpoint must hold.
    4. Bias correction. Dividing by 1 − β₁t+1 and 1 − β₂t+1 (0.1 and 0.05 at step 0) undoes the pull towards the zero start: at step 0, m̂ = g and v̂ = g².
    5. The Adam direction m̂ / (√v̂ + ε). At step 0 it is ±1 (to within 0.001) for every coordinate whose gradient is well above ε: the first update is the sign of the gradient times the learning rate, whatever the gradient's size. The noise column stays near zero (about 1e-5), because its √v̂ is far below ε = 1e-8, so ε sets its step: ε is what stops Adam from normalising pure noise into full-size steps.
    6. add_decayed_weights(0.1, mask). Adds 0.1 × p only where the mask is true, the 25 weight matrices (the first four columns); biases, norms and embeddings are left alone.
    7. scale_by_learning_rate. Multiplies by minus the learning rate, 2.0e-5 at step 0 (linear warmup to 1e-3 over 50 steps): an update of 2.0e-5 for a weight and 2.3e-10 for the key bias.
    8. apply_updates. p + update is the new parameter. optax returned it with the new state; nothing was mutated, so the same step can be jitted, sharded and checkpointed.

    Values from src/runs/ts_optax.py (S1) measured: eight tracked numbers (weights with and without decay, a LayerNorm scale, an embedding, a bias whose gradient is float noise), shown for the chosen training step and number; the highlighted column and the cards follow your choice.

    g → g·min(1, c/‖g‖) → m = β₁m + (1−β₁)g, v = β₂v + (1−β₂)g² → m̂/(√v̂ + ε) → + λ·p·mask → ×(−ηₜ)
    c
    clip threshold 1.0, applied to the global norm of all gradients (clip_grad_norm_)
    m, v
    Adam moments (exp_avg, exp_avg_sq); m̂ = m/(1−β₁ᵗ), v̂ = v/(1−β₂ᵗ)
    λ
    weight decay 0.1, only where the mask is true (25 weight matrices)
    ηₜ
    learning rate at step t: linear warmup to 1e-3 over 50 steps
    The whole tree at the chosen step: global norm after each stage

    Global L2 norm over all 826,368 numbers after each stage. The update norm is small because the learning rate is still warming up (step t uses (t + 1)/50 x 1e-3).

    The four things PyTorch does by mutation, done as transformations

    • Changing a hyperparameter mid-run: inject_hyperparams. An optax optimiser closes over its hyperparameters, so they are constants in the compiled step; optax.inject_hyperparams(optax.adamw)(learning_rate=1e-3, ...) moves them into the state as traced arrays you can overwrite (). Changing it four times traced the step once; rebuilding optax.adamw(lr) with a new Python float traced it once per value measured. A schedule needs neither: it is evaluated inside the step from the step count.
    • Parameter groups: masks and optax.partition. A mask (a pytree of booleans, or a function returning one) switches one transformation per leaf (adamw(mask=...) decays only masked leaves); optax.partition sends each leaf to a different optimiser by label (; optax.multi_transform is now its backwards-compatible alias, ). Freezing with set_to_zero() also saves memory: it keeps no moments.
    • Gradient accumulation: optax.MultiSteps(tx, every_k_schedule=4). For three calls it adds the gradient to an accumulator and returns zero updates; on the fourth it passes the mean to tx (). Cost: one more parameter-sized accumulator. Trap: the step count and every schedule now advance once per four calls, so count real updates (state.gradient_step).
    • Skipping bad steps: optax.apply_if_finite(tx, max_consecutive_errors=3). If any gradient is NaN or infinite it returns zero updates and leaves the inner state untouched (); after max_consecutive_errors bad steps in a row it applies the update anyway, so persistent NaNs still surface. It is the JAX counterpart of the skip that PyTorch's GradScaler performs on overflow.
    The four measured: traces, partition sizes, MultiSteps and apply_if_finite call by call

    inject_hyperparams. Four steps with the learning rate set to 1e-3, 1e-3, 5e-4 and 2.5e-4 in state.hyperparams traced the step once; rebuilding optax.adamw(lr) with a new Python float traced it 3 times for 3 values measured. Injection also puts the current learning rate in the checkpoint.

    partition. With AdamW on the 25 weight matrices, Adam on the 42 biases and norms, and set_to_zero() on the two embeddings, the embeddings stayed frozen after 5 steps and the optimiser state held 1,603,330 numbers against 1,652,737 for AdamW on everything measured.

    MultiSteps. Against one step on the batch of 32, the parameters differed by at most 6.5e-6 measured: the mean of four micro-batch gradients equals the batch gradient only in exact arithmetic, and Adam's first step turns a tiny difference on a near-zero coordinate into a sign. State: 2,479,107 numbers against 1,652,737.

    apply_if_finite. With a NaN injected at step 3 measured: .

    MultiSteps(adamw, 4) on 4 micro-batches of 8 (S4).

    apply_if_finite(adamw, 3), NaN injected at step 3 (S5).

    Schedules are functions of the step

    A schedule is any function from the step count to a number, evaluated inside the compiled step. The old page's warmup_cosine_decay_schedule(0.0, 3e-4, warmup_steps=2000, decay_steps=100000, end_value=3e-5), evaluated by optax, gives 3.00e-4 at step 2,000, 1.650e-4 at step 51,000 (halfway through the cosine: (3e-4 + 3e-5)/2 derived) and 3.00e-5 at 100,000: decay_steps includes the warmup (). Warmup-stable-decay (WSD) is join_schedules of three linear or constant pieces.

    decay_steps counts from step 0, warmup included

    Both schedules evaluated by optax (S6) measured.

    Lion and Muon in optax

    Both are in optax (Lion in core, Muon in optax.contrib, where optax keeps newer optimisers alongside schedule-free, Prodigy and SOAP-style ones); how they work is on the optimisers page. One optax-specific trap matters in practice:

    optax's Muon applies to every 2-D parameter by default
    By default optax.contrib.muon labels every two-dimensional leaf "muon" and everything else "adam" (). In the running example that includes the token and position embeddings and the output head, which Muon's authors keep on AdamW. Pass muon_weight_dimension_numbers returning None for them.
    Lion and Muon measured here: Lion's sign step, Muon's Newton-Schulz on a real gradient, and 300 steps with four optimisers

    Lion (Chen et al., 2023) keeps one moment and steps by its sign: every coordinate moves by exactly the learning rate. On one step at lr 1e-4, 99.92% of the updates had magnitude 1e-4 and the rest were exact zeros (zero gradients) measured. Its state is one tree (826,369 numbers, half of AdamW's), its default weight decay is 1e-3 (), and its authors recommend a learning rate 3 to 10 times smaller and decay 3 to 10 times larger than AdamW's (arXiv 2302.06675, section 5).

    Muon (Jordan, 2024) applies momentum, then replaces each weight matrix's update by an approximately orthogonal one (the same singular vectors, singular values pushed towards 1) through five iterations of a quintic Newton-Schulz map with optax's coefficients (3.4445, −4.7750, 2.0315) (, ). On the running example's real first-layer MLP gradient ([128, 512]) the singular values spanned a ratio of 1.2e8; after normalisation and five iterations 122 of the 128 ended between 0.5 and 1.20, close to the 0.5 to 1.5 band the optax docstring describes, while the smallest stayed near zero (5.7e-6): a direction with essentially no gradient is not amplified in five iterations.

    1. Before: the gradient divided by its Frobenius norm. Largest singular value 0.92, smallest 8e-9: the raw gradient's singular values span a ratio of 1.2e8, and plain momentum SGD would step mostly along the top few directions.
    2. Iteration 1 of X ← 3.4445 X − 4.7750 (XXᵀ)X + 2.0315 (XXᵀ)²X: the small singular values grow fastest; 4 of 128 are at or above 0.5.
    3. Iteration 2. The largest overshoots to 1.20; 10 of 128 at or above 0.5.
    4. Iteration 3. 33 of 128 at or above 0.5.
    5. Iteration 4. 84 of 128 at or above 0.5.
    6. Iteration 5. 122 of 128 between 0.5 and 1.20: the update direction Muon uses (then scaled by the learning rate and a shape factor). The near-zero direction stays near zero (5.7e-6).

    The gradient normalised by its Frobenius norm, then each Newton-Schulz iteration (S8); bars are its 128 singular values, sorted, on a log scale. The library's own orthogonalize_via_newton_schulz agrees with the hand iteration to 3.6e-7 in every singular value measured.

    Training loss every 10 steps and validation loss after 300 steps on the Training lab's 8 validation batches; same initial weights, same batches, clipping at 1.0, 50 warmup steps (src/runs/ts_optax.py, S9) measured. One seed, untuned learning rates, 300 steps of a 0.8M-parameter model: this shows the mechanics run, not which optimiser is better. The AdamW run is the root's running example and reproduces the Training lab's float32 validation loss after 300 steps (2.26352, src/train/out/mixed.json) to within 1e-7.

    5. orbax: checkpoints that resume the same run

    A run is preempted at step 80. To continue the same run, not a similar one, you need everything that decides step 81: the parameters, the optimiser's moments and step count (the schedule reads it), the random streams (dropout) and the data loader's position. PyTorch scatters these across model.state_dict(), optimizer.state_dict(), scheduler.state_dict(), the global RNG states and a loader with no state; in JAX all of them are pytrees, and orbax saves pytrees.

    What each missing piece costs, measured

    The running example in NNX with dropout 0.1, its AdamW chain and a grain pipeline. One process trains 160 steps without stopping; another trains 80, saves and exits; then a fresh process per variant restores part of the checkpoint and trains steps 80 to 159, compared with the uninterrupted run over all 210 arrays of parameters and optimiser state (src/runs/ts_ckpt.py) measured.

    Predict: you restore parameters and optimiser state but build a new grain iterator. Is the resumed loss at step 80 equal to the uninterrupted run's? Pick "no data iterator" in the chart.

    Reading the signatures. Restoring everything gives an identical run, every array bit for bit. A fresh data iterator re-reads batches 0, 1, 2, so the very first resumed loss is off (by 0.015). A fresh optimiser gives the same first loss (the forward pass does not read it) but restarts warmup and zeroes the moments, so the curve then drifts. Fresh RNG streams repeat the dropout masks of steps 0 onward: a tiny first difference (1.9e-4) that compounds. "Params only", what torch.save(model.state_dict()) keeps, combines all three. The step count is in the optimiser state here (opt.step), so the schedule followed it.

    Each omission gives a different run with no error, and its own signature

    Restored

    Top panel: training loss, resumed against uninterrupted; bottom: the absolute difference on a log scale (exactly zero sits on the floor). "First loss off by" is the gap at step 80, the first step after resuming.

    How a CheckpointManager save works

    • Items. One checkpoint holds named items, each with a handler: ocp.args.Composite(model=StandardSave(nnx.state(model)), opt=StandardSave(nnx.state(opt, nnx.Not(nnx.Param))), data=grain.checkpoint.CheckpointSave(it), meta=JsonSave({...})), each a directory under <dir>/<step>/.
    • Async. enable_async_checkpointing defaults to True (): save() copies the arrays to host memory and returns while a background thread writes (call 0.14 s, write done at 0.36 s here, rough). Call wait_until_finished() before exiting; orbax ignores unfinished checkpoints (finished ones carry commit_success.txt files).
    • Sharded. Arrays go to TensorStore in OCDBT format, one key-value store per process (ocdbt.process_0/), each process writing only the shards it owns: no gather to rank 0, unlike a naive torch.save; the PyTorch counterpart is torch.distributed.checkpoint.
    • Restore into a target. You pass a pytree with the shapes, dtypes and shardings you want (a freshly built model's state, or an abstract one from nnx.eval_shape) and orbax reads each shard into place; the layout on disk does not constrain the layout you restore to.
    • Which checkpoints to keep. In orbax-checkpoint 0.12.7, max_to_keep, keep_period and best_fn are documented as "deprecated, do not use. use preservation_policy instead" (). The replacements compose: save_decision_policy=FixedIntervalPolicy(100) and preservation_policy=AnyPreservationPolicy([LatestN(1), BestN(get_metric_fn=..., reverse=True, n=2)]). BestN sorts by the metric and keeps the last n (), so for a loss you need reverse=True, or it keeps the two worst (the old best_mode="min" was translated to exactly that: ).
    Found here: the policy API alone does not save the metrics
    In orbax-checkpoint 0.12.7 a CheckpointManager writes the metrics you pass to save() only when best_fn is set (the _track_best check at ). With preservation_policy=...BestN(...) and no best_fn, ranking works inside one process, but after a restart the old checkpoints have no metrics, BestN keeps checkpoints without metrics by default, and they are never deleted. With section 9's script, the uninterrupted run kept steps 300, 400; the preempted and restarted run kept 100, 200, 300, 400 measured. Setting the deprecated best_fn and best_mode="min" as well makes the metrics persist (section 9 runs that way).
    The step-80 checkpoint on disk: files, RNG state, iterator state

    The step- checkpoint: . The model and opt items are TensorStore OCDBT stores; data is grain's iterator state as JSON; meta is a JSON item with the step.

    The RNG state saved with the model: . The data iterator state: .

    Restoring onto a different mesh

    A checkpoint saved sharded on one mesh restores exactly onto any other layout, because you restore into a target that carries the shardings you want; continuing bit for bit is another matter (Fig. 3). Pin the state's shardings in the train step (out_shardings or jax.lax.with_sharding_constraint), and when the mesh really changes, compare losses, not bits.

    1. Saved on (data 2, model 4). Eight simulated CPU devices. fc1's kernel [128, 512] is annotated P(None, 'model'): each device holds one 128-column block (its glass plate, drawn at the block's offset) and the two data rows hold copies.
    2. The compiler re-shards. After one jitted step, 81 of the 210 parameter and optimiser leaves had shardings other than their annotations: the fc1 bias, annotated P() (a full copy on every device), came back as P('model',) (a quarter each).
    3. orbax saves at step 20. Every device's shards go into TensorStore, one OCDBT store per process (ocdbt.process_0, 9.5 MB here), each process writing the shards it owns: no gather to one device.
    4. Restore onto five targets. The same mesh built fresh, (8 x 1), (1 x 8), one device, and the same mesh with the shardings the state had when saved. Each target is a pytree carrying the shardings you want, and every restore was exact, bit for bit.
    5. Continue to step 40. Only the run restored into the saved shardings stayed bit-identical to the uninterrupted run. Every other target compiles a different step that sums in a different order, and its parameters drifted by 2.7e-6 to 3.4e-6 by step 40.
    The five restores, layout by layout, and why this is not nondeterminism

    The running example was restored onto the same mesh, (8 x 1), (1 x 8) and one device, plus the same mesh into the saved shardings, and trained to step 40 (src/runs/ts_ckpt_mesh.py). The model's annotations replicate the biases (spec P()); after one step the fc1 bias, for example, came back as P('model',). The same 20 steps run three times on one mesh were identical every time (src/runs/ts_mesh_det.py).

    Emergency checkpointing and orbax's new API (read, not run)

    On a large TPU job the cost of a checkpoint is the write to remote storage (Cloud Storage), so you checkpoint rarely and lose up to an interval of work on each failure. orbax's experimental.emergency.CheckpointManager keeps two tiers: frequent local checkpoints to fast local storage (RAM disk) on each host (default save_interval_steps 10: ) and rare persistent ones to remote storage (default 1000: ); after a failure, a slice that still holds a complete local checkpoint broadcasts it to the replaced hosts, and the persistent tier is the fallback (docstring at ). The module is marked "experimental; do not use without specific approval" (). Not run here: it needs several hosts and slices. orbax also ships a new API, orbax.checkpoint.experimental.v1 (), still under experimental at 0.12.7; the code on this page uses the stable CheckpointManager, as Tunix does. MaxText has moved to the v1 API (ocp.training.Checkpointer, on JAX LLM codebases, section 5).

    6. grain: a data pipeline that is a function of the index

    For a resumed run to be the same run, the loader must produce the same batches in the same order and be able to jump to the middle of an epoch; on many hosts, each host must read a disjoint part of the data, deterministically. PyTorch's DataLoader gets order from a sampler in the main process, randomness inside __getitem__ from per-worker generators, and has no position to save.

    How grain works. A MapDataset is random-access: ds[i] computes record i from a source (anything with __len__ and __getitem__, such as an ArrayRecord file or a numpy array) and a chain of transformations. shuffle(seed) is a fixed permutation of indices (); random_map(f, seed) hands f a numpy generator seeded from the seed and the record's index (); repeat() reseeds every random transformation per epoch, so each epoch is shuffled differently but deterministically (). to_iter_dataset() turns it into an iterator, read by 16 threads by default (), and mp_prefetch adds worker processes. Because record i depends only on (i, seed, epoch), the iterator's whole state is a few integers. The older grain.DataLoader(data_source, sampler, operations, worker_count) API does the same with an IndexSampler.

    On the running example's 7,781 windows measured (src/runs/ts_grain.py): record 100,000 of shuffle(0).repeat() (epoch 12) is window 3986, computed with no iteration, and a random crop drawn in random_map was identical for 192 records with 0 and 4 worker processes. The same crop drawn with torch.randint in a PyTorch __getitem__ agreed between 0 and 2 workers for only 12.5% of 128 records (chance is 1 in 8), because torch seeds each worker differently (src/runs/ts_torch_loader.py, torch 2.14.1).

    Where you batch decides whether the worker count matters

    mp_prefetch gives each worker process a slice of the MapDataset's elements and interleaves their outputs; anything after to_iter_dataset() runs inside each worker on its own slice. The same pipeline written four ways:

    Predict: with pipeline B and 2 workers, which records make up batch 0? Pick a pipeline and a worker count; the stage replays.

    Pipeline
    Worker processes
    1. The shuffled order. shuffle(0) is a fixed permutation of the 7,781 windows; the back rows are its first 64 positions, the records the 0-worker pipeline A puts in batches 0 and 1. Record i is computed from i and the seed, so any position can be read directly.
    2. The worker processes. With the batch in the MapDataset (A) one element is a whole batch, so workers share out batches. With the batch after to_iter_dataset() but before mp_prefetch (B) each worker batches its own slice of records.
    3. Batch 0 fills. Each record flows from its position in the order to its slot. Pipeline A takes positions 0 to 31 at every worker count; B with 2 workers takes positions 0, 2, 4, ... (one worker's slice), with 4 workers 0, 4, 8, ...
    4. Batch 1 fills. A takes positions 32 to 63; B with 2 workers takes 1, 3, 5, ..., the other worker's slice.
    5. Against the 0-worker stream. A record that is not where the same pipeline with 0 workers put it is lifted and outlined. A and D match at every worker count; B, C (a filter before the workers) and the DataLoader API with 2 workers do not.

    Each box is one record, coloured by its window index; the batches are the first two of each recorded run measured. A record from beyond position 63 of the shuffled order flows in from the right. The DataLoader API ran with 0 and 2 workers only; the table above compares six batches. Which worker process handled which record was not recorded, so the flows cross the worker plate as a whole.

    A filter (many-to-one) before mp_prefetch also changes the stream, as grain's docstring warns (). The output stays deterministic for a fixed worker count (the DataLoader run with 2 workers repeated exactly); what is lost is elasticity: change the worker count between save and resume and you get a different run.

    Checkpointing the iterator, and many hosts

    With 2 worker processes the iterator state records per-worker positions; a fresh 2-worker iterator given the state after 7 batches produced the same next 3 batches, but loading it into a 0-worker pipeline raised KeyError: 'next_index' measured. So resume with the same worker count. orbax writes the state through grain.checkpoint.CheckpointSave/CheckpointRestore as a small JSON item per process. On a multi-host slice each host reads its own shard: IndexSampler(shard_options=ShardOptions(shard_index=k, shard_count=2)) gave two simulated hosts 3,888 records each, disjoint, together 7,776 of 7,781 (the remainder dropped so shards are equal) measured. In real use grain.sharding.ShardByJaxProcess() fills in jax.process_index() and jax.process_count(), and jax.make_array_from_process_local_data assembles the global batch (Sharding and scale); with the dataset API, ds[k::n] slices the same way.

    The iterator state, epochs, hosts and the PyTorch contrast in full

    With 2 worker processes, the state after 7 batches was:

    
    

    Epoch 0 of shuffle(0).repeat() starts with windows 3746, 2851, 6667, 3304, epoch 1 with 6158, 4966, 4010, 4273; with reseed_each_epoch=False epoch 1 repeats epoch 0 measured. A 0-worker iterator's state looks like .

    The same windows through torch.utils.data.DataLoader(shuffle=True, generator=torch.Generator().manual_seed(0)) with a random crop offset drawn by torch.randint inside __getitem__ measured:

    Order agrees across worker counts because the sampler runs in the main process; augmentation does not, because each worker process gets its own torch seed (base seed plus worker id). grain's random_map derives each record's generator from the seed and the record index.

    Threads, processes and speed; grain against the alternatives

    Two kinds of slow transformation behave differently. With a 2 ms per-record map (rough timings, load average about 40): a map that waits (sleep, like reading a file) ran at batches per second (115) with no worker processes, against the 15.6 a serial loop would allow (1 / (32 x 2 ms) derived), because the default 16 read threads overlap the waits; a map that computes in Python (a busy loop holding the GIL) ran at , the serial rate, since threads cannot run Python in parallel. Worker processes are the fix for the second kind; on this heavily loaded shared machine their speed-up was not measurable reliably ( and batches per second with 2 and 4 workers), so no claim is made about it. On a TPU host: profile the input pipeline (xprof's input pipeline analyser) and add workers until the device never waits.

    A Python generator over a numpy memmap (the root's running example) is fine when the data fits on one host and you never resume mid-epoch. tf.data is what older JAX code (T5X, big_vision) uses. PyTorch's DataLoader works from JAX too (convert batches with np.asarray); torchdata's StatefulDataLoader adds state_dict for mid-epoch resume (not run here). MaxText's default dataset_type is synthetic, with grain, Hugging Face and tfds options (root's Tool map).

    7. float16 and loss scaling

    On TPU use bfloat16: it has float32's 8 exponent bits, so its range is float32's and it needs no loss scaling (the root's Training lab measured bf16 compute with a float32 master copy ending within 0.001 of float32). float16 (5 exponent bits, smallest normal 6.10e-5, largest 65,504) is still what many GPU recipes use, and gradients are small: the running example's float32 gradients at initialisation have a median magnitude of 1.1e-3, and many land among float16's subnormals. Loss scaling multiplies the loss by S before the backward pass and divides the gradients by S in float32 before the optimiser; dynamic loss scaling starts S high, halves it and skips the step whenever a gradient is not finite, and doubles it after a run of good steps. In JAX the reference implementation is jmp's DynamicLossScale (last released 2023), a small pytree carried through the jitted step; PyTorch's torch.amp.GradScaler is the same algorithm. Formats, subnormals and a loss-scale slider are taught on Numerical computing for ML (section 9); mixed precision across frameworks on Quantization and Precision.

    Measured here measured: at S = 1 the median relative error of float16 gradients was about ten times that at S = 256; at S = 224 almost every gradient overflowed. Over 200 steps with float32 master weights, a static scale of 212 stayed on top of float32 (validation loss 2.36050 against 2.36054); no scaling wandered off the float32 trajectory (2.3319: not worse here, a different run); the dynamic scale started at 215, skipped the overflowing steps 111 and 144, halving each time, and ended at 213.

    The loss-scale table, the jmp step and the 200-step runs

    float16's smallest normal number is (subnormals go down to , with fewer and fewer significant bits), its largest . One batch at the initial weights, gradients computed through a float16 copy of the model measured:

    At S = 1 few gradients become exactly zero, but many land among float16's subnormals and lose precision. bfloat16 at S = 1 has a larger median error still (8 significant bits against float16's 11) but loses nothing to range; its handful of zeros are sums that cancel, not underflow.

    ls = jmp.DynamicLossScale(jnp.asarray(2.0 ** 15, jnp.float32))
    @jax.jit
    def step(p, s, ls, x, y):
        def f(pc):
            logits = MJ.apply(jax.tree.map(lambda a: a.astype(jnp.float16), pc), x, CFG).astype(jnp.float32)
            return ls.scale(optax.softmax_cross_entropy_with_integer_labels(logits, y).mean())
        l, g = jax.value_and_grad(f)(p)          # float32 master weights; float16 inside
        g = ls.unscale(g)
        finite = jmp.all_finite(g)
        u, s2 = tx.update(g, s, p)
        p, s = jmp.select_tree(finite, (optax.apply_updates(p, u), s2), (p, s))   # skip the step on overflow
        return p, s, ls.adjust(finite), ls.unscale(l), finite

    Difference of each run's training loss from the float32 run, every 10 steps, and validation loss after 200 steps on the Training lab's 8 validation batches (src/runs/ts_mixed.py) measured. On a CPU float16 is emulated, so no speed is reported. jmp doubles the scale again only after 2,000 good steps by default. A tiny model at initialisation has large gradients; deep models late in training have far smaller ones, which is where unscaled float16 loses updates outright.

    8. Evaluation loops and metrics

    loss.item() every step forces the host to wait for the device, serialising a pipeline that JAX runs asynchronously (dispatch returns before the device finishes). So accumulate metrics on the device, inside the compiled step, and read them every N steps. nnx.MultiMetric(loss=nnx.metrics.Average("loss"), accuracy=nnx.metrics.Accuracy()) is a module whose state is running sums in Variables; metrics.update(loss=..., logits=..., labels=...) inside an nnx.jit step adds to them on device; metrics.compute() and reset() on the host every N steps are the only syncs (source ; also Welford for mean and variance). An evaluation loop is the same with a second MultiMetric and an eval_step that does not touch the optimiser; call model.eval() first if the model has dropout or BatchNorm. clu (Google's CommonLoopUtils), which older Flax code uses for metrics and periodic actions, last released 0.0.12 on 2024-04-10 (PyPI, read 2026-10-15) published; for NNX code nnx.metrics is enough.

    9. A complete training script, preempted and resumed

    Everything above in one file, as it ran (src/runs/ts_full.py, the train function): grain pipeline reshuffled per epoch, NNX model loaded from the shared initial weights, optax chain with a warmup-cosine schedule and a decay mask, nnx.Optimizer, on-device metrics, evaluation every 100 steps on 256 fixed validation windows, orbax policies keeping the latest and the two best checkpoints, and resume from the latest checkpoint if one exists. It ran three times in separate processes measured: A trained 400 steps; B ran the same command and was stopped after step 250, the way a preemption would stop it; C ran the same command again, found the step-200 checkpoint and continued.

    B then C ended with parameters bit-identical to A; steps 201 to 250 ran twice, which is the cost of saving every 100 steps.

    The script

    Checklists and provenance

    Pre-flight checklist: the mistakes that give a different run with no error
    • State and RNG. A pure jax.jit step that does not return nnx.state(model) reuses the same dropout mask every step (section 1). Filters must end with ... on a model with any non-Param state. A module shared twice is a "Duplicate Param" in tree mode.
    • Recompiles. Adding an attribute, rebuilding a submodule or flipping a Python flag stored on the module changes the graphdef and recompiles (section 2); so does rebuilding the optimiser with a new Python learning rate (one compile per value, section 4).
    • Linen and Equinox. Every training apply needs mutable=["batch_stats"] and rngs={"dropout": key}, and you merge the returned updates; plain jax.jit on an Equinox model holding a function fails: use eqx.filter_jit (section 3).
    • optax. Under MultiSteps a schedule written for 10,000 updates and a loop of 10,000 micro-batches with k = 4 reaches only a quarter of the schedule. optax.contrib.muon orthogonalises embeddings and the head unless told not to (section 4).
    • orbax. Save model state (with RNG), optimiser state and the data iterator in one checkpoint; parameters alone silently restart warmup, zero the moments, re-read the first batches and repeat the masks. BestN for a loss needs reverse=True; with 0.12.7 set best_fn too or metrics are not persisted; call wait_until_finished() before exiting. Expect bitwise resumes only into the saved shardings (section 5).
    • grain. Batch in the MapDataset before to_iter_dataset(), keep filters after mp_prefetch, and resume with the same worker count (section 6).
    • Sharding. With eager sharding (default in 0.12) an annotated model needs a mesh in scope: "An auto mesh context or metadata is required if creating a variable with annotation out_sharding=..." (section 2).
    • Metrics. No loss.item() per step; accumulate with nnx.metrics and read every N steps (section 8).
    Interview rehearsal: two questions that combine the sections
    Why does NNX store RNG keys in the model, and what breaks if you forget them in a checkpoint?
    JAX has no global generator; a key plus a counter per stream makes randomness explicit state that transforms can carry and checkpoints can save. Without it a resumed run repeats the dropout masks of the first steps: a different run, silently.
    Your resumed run's loss differs from the original from the first step. What do you check?
    If the first resumed loss differs, the forward pass saw different inputs or weights: the data iterator position, or the RNG streams. If the first loss matches and then drifts: the optimiser state (moments, step count, schedule). If it matches for many steps then drifts very slowly: a different compiled program changing reduction order: another mesh, or the same mesh with the state restored into its annotated shardings rather than the ones the compiler had given it (section 5).
    Design: design the checkpointing for a 2-week run of a 70B model on a TPU pod that is preempted a few times a day.
    Save one checkpoint item for model state, one for optimiser state, one for each host's data iterator and a JSON item for the step and config; async, sharded, each host writing its own shards (orbax OCDBT). Two tiers: local checkpoints every few minutes of work to host RAM disk, replicated across slices so a replaced slice can be refilled, and persistent ones to Cloud Storage every hour or so (orbax's emergency manager is built for this, still experimental); keep the latest plus a few by evaluation loss, and some at fixed periods for analysis. Make data order a function of (seed, step) and keep the worker count fixed. Measure: time the save call blocks the step, write bandwidth, restore time, and test a real kill and resume in staging, comparing losses for 100 steps. Restoring onto a different slice shape works (restore into the new shardings) but will not be bitwise.
    What changed from the old Notion page (corrections)

    This page reuses the old Notion page "Flax NNX, optax, orbax: the training stack" (Notion 3c65c17b0d0d817ea0ace9a2ca8677ec, saved verbatim in src/live.md). Every claim was checked against the pinned sources and runs here; the full list is in src/coverage.md. The corrections:

    • "nnx.split(model) ... ckptr.save(path, state); restore into nnx.state(...)": correct, but saving only the model state loses the optimiser, RNG and data position; measured consequences in section 5.
    • "Per-parameter behaviour: optax.multi_transform": now optax.partition; multi_transform remains as a backwards-compatible alias in optax 0.2.8.
    • "Use ocp.CheckpointManager for rotation/retention": still right, but max_to_keep and best_fn are marked deprecated in orbax-checkpoint 0.12.7 in favour of preservation_policy and save_decision_policy.
    • "@nnx.jit ... donates internally": not shown by anything run here, and nnx.jit takes donate_argnums/donate_argnames like jax.jit; dropped.
    • "There is no .train()/.eval() global mode": NNX modules do have model.train() and model.eval(), which set deterministic / use_running_average on every submodule (measured in section 1).
    • "EMA (optax.ema), SAM, Lion, Muon, apply-if-finite are all stock transformations": Lion, EMA and apply_if_finite are in core optax; SAM and Muon are in optax.contrib, and Muon's default applies to embeddings too (section 4).
    • "NNX ... interops via flax.nnx.bridge": verified (ToNNX, ToLinen, lazy_init, section 3). New since the old page: graph mode versus tree mode, eager sharding, and the planned switch to tree mode by default (section 1).
    Reading tab of the training-stack child page of Topic: jax-and-tpu, built 2026-10-15, rebuilt to the teaching contract 2026-10-23 (no new runs). Runs used jax and jaxlib 0.11.2, flax 0.12.10, optax 0.2.8, orbax-checkpoint 0.12.7, grain 0.2.18, equinox 0.13.8, jmp 0.0.4, torch 2.14.1 and Python 3.12.11 on an Apple M1 Pro, CPU only. Scripts and recorded outputs: this page's src/runs/; source quoted from google/flax v0.12.10, google-deepmind/optax v0.2.8, google/orbax v0.12.7, google/grain v0.2.18, patrick-kidger/equinox v0.13.8 at the commits linked.