JAX LLM codebases: MaxText, Tunix, levanter

What MaxText, Tunix and Levanter each optimise for, how a config becomes a sharding and a compiled train step, and which to start from; read at pinned commits and run on the topic's running example (Apple M1 Pro CPU). Data as of October 2026. Reading: 33 min, plus 8 in closed details.

A production JAX LLM codebase is the same five boxes as your own training loop (configuration, model, sharding, train step, data and checkpoints) with one difference that reshapes all of them: the model never names a device, so a config decides the shapes, the sharding and the remat policy, and one jitted pure step turns them into a single XLA program. The codebases differ in which box they invest in: MaxText in config and sharding for scale on TPU, Tunix in the train step for post-training, Levanter in named axes and reproducible data.

Fig. 1, step by step: same five boxes, different investments

  1. Five boxes in 268 lines. The running example is the topic's 826,368-parameter character model (268 lines: model_jax.py plus common.py): a CFG dict, an apply() model, no sharding (one device: the faint slab), a six-line step under jit with donation, numpy batches and no checkpoint. The config sits on top because it feeds every box below it.
  2. MaxText holds the same boxes in 213,293 lines of Python. Highlighted, what it is built for: config (configs/, 17,445 lines of Python and YAML) and sharding (logical names plus 80 rules). The dots run from the config into every box: shapes, sharding and remat are config values read while the step is traced. The sharding code is small (utils/sharding.py, 1,262 lines) because the rules are data.
  3. Tunix, 47,599 lines, is built around the train step. sft/, rl/ and distillation/ hold 18,164 lines: PeftTrainer and the RL learners for post-training. Config, sharding and data have no part of their own in the map (faint slabs): YAML configs and mesh helpers sit in cli/ and utils/, RL placement is role_to_mesh per RL role inside rl/ (section 7), and checkpoints go through Orbax's CheckpointManager.
  4. Levanter, 87,114 lines, is built around named axes and reproducible data. Sharding is a mapping dictionary from the model's own axis names (228 lines); data and checkpoints (12,418 lines) give a seekable cache and checkpoints that keep the keys (section 8). The model is Equinox plus Haliax (20,762 lines); the config is draccus dataclasses, with no part of its own in the map.
  5. Side by side. The arc is a real dependency: MaxText's post-training entry points import Tunix's trainers. Reading a large codebase is finding these five boxes and the one or two ideas it adds to each.

Slabs are equal in height; their labels give lines per part from the Codebase map tab's measurement (runs/lc_map.py: Python files, plus YAML for MaxText's configs, tests excluded). A faint slab is a box with no part of its own in the map. The Codebase map tab has every part of the three repositories with its size and the symbols worth reading at their lines.

You need: tracing and jax.jit (JAX core), meshes and PartitionSpec (Sharding and scale), Flax NNX split and merge, optax and Orbax (The JAX training stack). New terms:

Logical axis names: one name per dimension of a weight or activation (embed, mlp, heads), never a device.
Logical axis rules: an ordered table in the config mapping each name to mesh axes; the first free rule wins.
scan_layers: run one traced layer over weights stacked on a layers axis.
remat_policy: which named intermediates the backward pass keeps instead of recomputing.
role_to_mesh: Tunix's map from an RL role (actor, reference, rollout) to a device mesh.
Named axis (Haliax): an array dimension addressed by name in every operation, not by position.
CodebaseWhat it isStatus, October 2026PyTorch counterpart
MaxText
Google
Reference LLM library in pure JAX for TPUs and GPUs: dense and MoE families (Llama, Gemma, Qwen, DeepSeek, Kimi, GPT-OSS), pretraining to tens of thousands of chips; post-training through Tunix.active PyPI 0.2.5 (2026-10-02); the README says main "is not expected to be production-ready" ().Megatron-LM, torchtitan
Tunix
Google
Post-training on Flax NNX: SFT (full and LoRA), DPO, ORPO, PPO, GRPO and variants, agentic multi-turn RL, distillation; vLLM or SGLang-JAX for rollouts.active v0.1.7 (2026-06-11), "Current Status: V2 Release".TRL, verl, OpenRLHF
Levanter in Marin
Stanford CRFM, now Marin
Trainer on Equinox and the Haliax named-tensor library, "bitwise deterministic" on TPU even across preemption.moved merged into the Marin monorepo in November 2025; PyPI marin-levanter dev builds.Composer, torchtitan
EasyDeL, AXLearn, Pax and Saxml, T5X, EasyLM, big_visionA community library, Apple's stack, and the pjit-era Google and research trainers.active to dormant: section 9

Which one to start from, by job, is section 10. Labels: measured ran here, published a project's own figure, derived arithmetic on them, judgement this page's opinion.

Provenance: commits, machine, and what ran

Everything marked measured ran on an Apple M1 Pro CPU (jax 0.11.2, flax 0.12.10, shared machine at load 30 to 60, low priority, 4 threads): MaxText at main 1a95d1e5 (2026-10-15), Tunix at v0.1.7 (2026-06-09), Levanter at Marin main 1290cfb5 (2026-10-15, lib/levanter) and the frozen Levanter repository 982cef7f. Configurations, shapes, shardings, losses and differences are deterministic; times are rough. Every file and line quoted is located by pattern in src/runs/lc_source.py; runs are in src/runs/, outputs in src/out/. The root page's Reading tab, section 7 lists the codebases with MaxText's MFU table, and its Tool map (tab "Tool map") dates every library and its lineage; this page goes inside them.

The CPU runs exercise every line of MaxText except the TPU kernels: AttentionOp.apply_attention () uses plain dot-product attention when attention=dot_product, and also under autoselected during decoding, for sequences under 128, or on CPU (). Otherwise flash means the splash attention Pallas kernel on TPU (; Pallas kernels reads it) and cudnn_flash_te Transformer Engine's cuDNN kernel on GPU.

1. MaxText's config is the program's input

One codebase trains a 0.6B Qwen on 8 chips and a 671B DeepSeek on thousands. PyTorch codebases carry the choices in argument parsers (Megatron's arguments.py, hundreds of flags) or TOML job files (torchtitan); MaxText reads a layered YAML into a validated object, and the model and train step read that object while they are traced, so every value is baked into the compiled program. pyconfig.initialize () builds it in this order, later layers winning:

  1. configs/base.yml: 1,669 lines, 828 top-level keys, every default with a comment.
  2. configs/models/<model_name>.yml (86 model files): shapes, activations, tokenizer, sometimes extra sharding rules.
  3. Command-line key=value pairs and Python keyword arguments.
  4. Environment variables named M_<KEY> ().

A pydantic class with 907 fields, MaxTextConfig (), then validates and derives what the code reads: emb_dim from base_emb_dim, global_batch_size_to_train_on from per_device_batch_size times the device count. Logical axis rules are merged by hand (): a model file's rule replaces every base rule with the same name. Degrees set to -1, such as ici_fsdp_parallelism, are resolved only when the mesh is built.

Predict: model_name=llama2-7b base_emb_dim=128. What does MaxText do?

What it catches, and what it does not. A typo fails at start-up (remat_polcy=full raises ValueError: 'remat_polcy' not in 'emb_dim', 'mlp_dim', ... and lists every valid key); a valid key with a surprising default does not. Three to know before copying MaxText's numbers elsewhere: learning_rate: 3.e-5 (a fine-tuning value), adam_b2: 0.95 (optax and PyTorch default to 0.999), and adamw_mask: [], which decays every parameter including biases, norm scales and embeddings (section 4 measures what that costs). To check a run, diff resolved configs, not command lines: log_config (true by default, ) logs every resolved key, and cfg.get_keys() returns them. The Config explorer tab has 81 flags with line, default, comment and value per model file.

Ten real parses: pick an override set and see what the code will read measured

Each is a real call of pyconfig.initialize then maxtext_utils.get_mesh_from_config at main 1a95d1e5 on 8 simulated CPU devices (runs/lc_cfg.py, out/cfg.json), about 0.1 to 3 s each.

A PyTorch weight becomes a MaxText weight by transpose, reshape and stack; the LayerNorm scale also shifts by 1

Tensor

Shapes and transforms are those runs/lc_fwd.py applied; every final shape matched the one MaxText created (the script asserts it). One cell is 8 × 8 numbers for matrices, one number for the scale.

2. The model, with the running example inside it

Transformer () is a Flax NNX module (MaxText "migrated to Flax NNX from Linen" in June 2026, ) owning the token embedding and an NNXDecoder (layers/nnx_decoders.py, 2,943 lines). Which layer it runs is a config value, decoder_block, one of 25 DecoderBlockType values () each mapped to a class: DecoderBlockType.GPT3: [gpt3.Gpt3DecoderLayer] (). The layers run inside jax.lax.scan over stacked weights, each wrapped in jax.checkpoint with the configured remat policy (; section 5). Attention is also chosen at trace time, by attention= and the hardware.

The running example as a MaxText model measured. The root's model is GPT-2 shaped (pre-LayerNorm with biases, learned positions, GELU MLP, untied head), the family of MaxText's gpt3 block. These overrides describe it:

decoder_block=gpt3 base_emb_dim=128 base_num_query_heads=4 base_num_kv_heads=4 head_dim=32
base_mlp_dim=512 base_num_decoder_layers=4 vocab_size=65 max_target_length=128
trainable_position_size=128 mlp_activations=[gelu] logits_via_embedding=false fused_qkv=false
enable_dropout=false dtype=float32 attention=dot_product normalization_layer_epsilon=1e-5

MaxText builds 826,368 parameters, the running example's count exactly, in 21 arrays instead of 69 because the four layers are stacked. With the running example's initial weights copied in (runs/lc_fwd.py), MaxText's forward pass on the first batch (32 × 128 characters) gives logits within of the plain-JAX twin, loss against . Four conversions got it there: transpose to [in, out] with named output axes, stack the layers on axis 1, store each LayerNorm scale as its offset from 1 (copied unchanged, every LayerNorm silently doubles its output), and accept tanh GELU. Pick a tensor on the figure:

Fig. 2, step by step: one tensor from PyTorch to MaxText

  1. PyTorch. Four separate tensors blocks.{0..3}.attn.wq.weight, each [128 out, 128 in]: nn.Linear stores the output dimension first and computes x @ W.T. The highlighted row is output 3.
  2. Layout: transpose. PyTorch stores a linear weight [out, in]; MaxText's DenseGeneral stores [in, out...] and computes x @ W, like Flax and the plain-JAX twin. The rows are now the input (embed) dimension and output 3 is a column.
  3. Name the output axes. The 128 outputs are 4 heads of 32: reshape to [embed, heads, kv] = [128, 4, 32]. Each colour is one head; nothing moves in memory.
  4. Stack the layers. With scan_layers=true each per-layer weight gains a layers axis at param_scan_axis = 1 (): four [128, 128] query weights become one [128, 4, 4, 32] array, the tensor MaxText created at decoder.layers.self_attention.query.kernel. This is why checkpoint converters exist.
  5. The bias follows. wq.bias [128] per layer becomes [heads, layers, kv] = [4, 4, 32]. With every tensor converted, MaxText's forward pass on the first batch gives logits within of the tanh-GELU twin.
Every tensor's conversion, and what looks different but is not
Running example (PyTorch name, shape)MaxText (path, shape)Conversion

Logits against the exact-GELU running example differed by 7.0e-5: enough to fail a tight equivalence test, small for training. MaxText divides the query by √head_dim right after the projection () where the running example divides the scores; the product is the same. Both runs set matmul_precision=highest (no effect on CPU). What transfers to TPU: every conversion above. What does not: on TPU the default precision runs float32 matmuls in bfloat16 passes, so a TPU comparison needs highest or a looser tolerance. Porting defaults in general (GELU, epsilon, initialisers) are on PyTorch to JAX.

3. How a config becomes a sharding: logical axis names and rules

In Megatron-LM tensor parallelism lives in the model: a ColumnParallelLinear knows it is split and calls the all-reduce, so changing the parallelism means changing model code. MaxText's model never names a device. Every parameter is created with one logical axis name per dimension: Llama 2's MLP input kernel is ("embed", "layers", "mlp"), the query kernel ("embed_attn", "layers", "q_heads", "kv"); activations get names through maybe_shard_with_logical, which becomes with_sharding_constraint. Three config entries then decide where everything lives:

  • The mesh: 12 named axes (), diloco, data, stage, fsdp, fsdp_transpose, context, context_usp_ulysses, context_autoregressive, tensor, tensor_sequence, expert, autoregressive, sized by ici_*_parallelism (inside a slice) and dcn_*_parallelism (across slices); most are 1.
  • The 80 logical axis rules (), applied by logical_to_spec (): "A dimension takes the first matching rule whose mesh axes no other dimension uses yet" ().
  • Size-1 axes are dropped, which is why long rule lists collapse to a short PartitionSpec. Flax Linen's logical_to_mesh_axes does the same; what a PartitionSpec does and which collectives the compiler inserts is on Sharding and scale.

A rule whose mesh axis is taken is skipped, so changing one degree re-shards the model without touching it. Pick a weight of Llama 2 7B and a mesh of 8 devices; the figure walks the weight through the rules:

Weight
Mesh

Fig. 3, step by step: one weight walks the rule table onto 8 chips

  1. The weight and its logical names. The glass plate is the weight drawn by its two largest dimensions (the stacked layers axis left out), each edge labelled with its logical name and size. The model never says more than this about placement.
  2. The mesh. Eight chips with named axes. Under fsdp 8 all eight sit on fsdp; under fsdp 2 × tensor 4 the rows are fsdp and the columns tensor. MaxText's other mesh axes have size 1.
  3. The rules, in order. Each rule naming one of this weight's dimensions is tried in config order; a dimension takes the first rule whose mesh axes no other dimension uses yet, and a rule whose axis is taken is skipped. The table under this list shows every rule tried for the chosen weight and mesh.
  4. Drop size-1 axes. What is left is the PartitionSpec; the plate is cut into one block per distinct shard. The page computes it in your browser and checks it against the spec MaxText's own code produced for the same weight.
  5. Onto the chips. Each block flows to the chips that hold it: one block per chip when every mesh axis is used, the same block on several chips (replicated over the unused axis) when not. The label gives the bytes each chip holds.
RuleDimensionResult

The rules are base.yml's at 1a95d1e5 as MaxText's parser returned them; the page applies logical_to_spec's algorithm in your browser and checks the result against the PartitionSpec MaxText produced for the same weight on 8 simulated CPU devices (runs/lc_shard.py). Shapes, specs, block shapes and bytes per device are those recorded; the plate's longer edge is the weight's longer dimension, not to scale.

Rule order explains a puzzle in the YAML: embed has two rules, one with fsdp_transpose and one without (). mlp's rule comes first () and takes fsdp_transpose; the first embed rule collides and is skipped, the second applies. One table serves every weight, and two-dimensional FSDP falls out of rule order.

What MaxText's own code produced measured (runs/lc_shard.py, abstract model, 8 simulated devices). Llama 2 7B: 6,738,415,616 parameters in 12 arrays (32 layers stacked), 26.95 GB in float32 and 3.37 GB per device under FSDP over 8. Adding tensor parallelism splits mlp, q_heads and vocab over tensor and keeps embed on fsdp. Under fsdp 2 × tensor 4 the norm scales are split only two ways and copied over tensor, because llama2-7b.yml replaces base.yml's ['norm', ['tensor']] with ['norm', 'fsdp'] (): an extra 399,360 bytes per device. With scan_layers=false the same model is 291 arrays and the specs lose the layers dimension.

Every parameter of Llama 2 7B and of the running example, sharded by MaxText's own code (five cases)

Every parameter of a real config, sharded by MaxText's own code measured

ParameterShapeLogical namesPartitionSpecPer device

runs/lc_shard.py builds the abstract model with create_nnx_abstract_model (): shapes and shardings only, no memory, so a 6.7B-parameter model costs under a second on a laptop. Mesh from get_mesh_from_config on 8 simulated devices; float32 bytes (weight_dtype), per device counting every local shard.

When it fails. The running example's vocabulary of 65 cannot be split four ways. Under ici_tensor_parallelism=4 MaxText still builds the abstract model, with P('tensor', 'fsdp') and P('fsdp', 'tensor') on the embedding and output kernel, and asking for their per-device shape raises IndivisibleError: ... implies that array axis 1 is partitioned 4 times, but the dimension size is 65. base.yml's comment on vocab_size says "powers of 2 for sharding"; real vocabularies are padded to a multiple of 128 or more (which also suits the MXU).

How to check. Print the shardings of the abstract model before compiling anything (debug_sharding=true makes setup_train_loop call print_shardings_params); at start-up assert_params_sufficiently_sharded allows sharding_tolerance (2% by default) of parameters unsharded. Pipeline parallelism uses the stage axis; its bubble formula is in base.yml () and measured on Sharding and scale.

Step 0 enters 90 MaxText functions to build the program; step 1 enters none

Step

The list: the 90 MaxText functions in the order first entered, indented by call depth, each at the line where it is defined (recorded co_firstlineno, out/train.json; links open MaxText at 1a95d1e5). The panel: what the step is doing, with the running example's line from the root's src/data/model_jax.py. Times measured on Apple M1 Pro (CPU), shared machine, 4 threads, low priority; step 0 includes tracing and XLA compilation.

4. The train step: one pure function, compiled once

A PyTorch step mutates objects (loss.backward() fills .grad, optimizer.step() updates in place). MaxText's train_step () is a pure function from (state, batch) to (new state, metrics):

  1. nnx.merge(model, state) () rebuilds the TrainStateNNX module (model plus nnx.Optimizer) inside the trace from a static graph definition and a pytree of arrays (the split/merge pattern of the training stack).
  2. jax.value_and_grad(diff_wrapper, argnums=(0, 1), has_aux=True) () differentiates loss_fn () over the trainable nnx.Param leaves: forward, cross-entropy over non-padding tokens, auxiliary losses (MoE load balance, z-loss, multi-token prediction) when configured.
  3. Gradients are cast to grad_dtype, clipped by global norm () and applied by state.apply_gradients(grads) (), the optax chain.
  4. Metrics (loss, raw and clipped gradient norm, parameter norm) come back as arrays, so logging never forces a device-to-host copy inside the step.

jit_train_step () wraps it in jax.jit with in_shardings and out_shardings from the logical rules and donate_argnums = 0 (): the old state's buffers become the new state's, which keeps peak memory at one copy of parameters and optimizer state; the donated input arrays are invalid after the call.

Python runs once measured. runs/lc_train.py recorded every Python call during MaxText's first two steps on the running example with sys.setprofile. Step 0 (trace, lower, compile, run): 757,992 Python calls, 1,063 of them in MaxText's own code across 90 functions, 3.09 s. Step 1: 805 calls (Flax flattening the state, JAX dispatching the cached executable), none in MaxText, 0.235 s. MaxText's Python is the recipe for one XLA program. The figure lists the 90 functions in the order they were first entered; each step lights the ones that do its part, beside the running example's line that does the same:

Fig. 4, step by step: what step 0 traces, in eight stretches

  1. Enter and differentiate. train_step receives the train state as a pytree of tracers; nnx.merge rebuilds the NNX train state, and config reads (HyperParameters.__getattr__) are plain Python whose values are baked into the program. jax.value_and_grad(diff_wrapper, ...) then calls loss_fn, which slices this step's microbatch and calls the model with tokens, positions and segment ids.
  2. The model and the embedding. Transformer hands over to NNXDecoder, which reads remat_policy (here full, policy None: keep only layer inputs), embeds the tokens plus learned positions and constrains the activation's sharding: logical_to_spec and _mesh_axes_free are section 3's rule resolution, running at trace time.
  3. Scan the layers. The stacked weights' layer axis (axis 1) is moved to the front and layer_fn, wrapped in jax.checkpoint, is handed to jax.lax.scan. The layer's Python in the next two stretches runs once, for all four layers.
  4. One gpt3 layer: sharding, norm, projections. Every activation passes through maybe_shard_with_logical, which becomes a with_sharding_constraint from logical names (batch, length, embed); LayerNorm multiplies by scale + 1; DenseGeneral computes dot_general into named output axes ([batch, length, heads, kv]), checks for quantisation and serving mode, and adds the bias.
  5. Attention and MLP. apply_attention chooses the kernel (dot_product here: CPU), checks for context parallelism, then qk_product, the causal mask, softmax (compute_local_attention) and wv_product. The MLP has its own pre-norm; "gelu" is looked up on jax.nn (tanh approximation).
  6. After the scan, the loss. The layer axis goes back to position 1; the final norm and output projection give the logits. Cross-entropy uses MaxText's own custom VJP (a forward and a hand-written backward rule), summed over tokens with nonzero segment ids; the backward rule is traced here too, so value_and_grad builds the backward program now.
  7. Gradients, optimizer, metrics. Gradients are cast to grad_dtype and clipped by global norm 1.0; apply_gradients runs the optax chain, where the adamw_mask regexes decide which leaves decay (evaluated on parameter paths, at trace time) and the schedule gives this step's learning rate; gradient and parameter norms come back as arrays with the loss.
  8. Lower, compile, run. The trace is one jaxpr; JAX lowers it to StableHLO, XLA compiles it with the state donated (donate_argnums=0), and the executable runs. Step 0 took s of wall time ( s of CPU time across threads).

Is it the same computation as yours? measured runs/lc_train.py drove MaxText's real machinery (setup_train_loop, jit_train_and_eval_step, train_step) on the running example's weights and Shakespeare batches with its AdamW settings (peak 1e-3, b1 0.9, b2 0.95, epsilon 1e-8, decay 0.1, clip 1.0, 50 warmup steps, then constant), then trained the root's plain-JAX twin for the same 200 steps. Three settings could not be matched from MaxText's side, so the twin took MaxText's behaviour: tanh GELU; a warmup that starts at learning rate 0 (optax.linear_schedule(init_value=0.0, ...), ) where the running example starts at 1e-3 × 1/50; and the weight decay mask (the run passed adamw_mask=["bias", "scale", "embedding"], leaving exactly the seven stacked kernels decayed). Result: the two loss curves differ by at most over 200 steps, float32 rounding. Flip each setting back on the chart:

The warmup offset moves the loss by up to 0.088 (early, while the rate ramps), decaying 1-D parameters by 0.0035 within 200 steps and growing, the activation by 0.00012. None of the three shows in a config diff that only compares model shapes. Median later step: measured on Apple M1 Pro (CPU), shared machine, 4 threads, low priority, load about .

Predict: in that run, what does MaxText's first optimizer step do to the weights?

A one-step warmup offset costs more than the activation and the decay mask together

Twin with

Absolute loss difference between the plain-JAX twin and MaxText's step on the same batch, log scale, steps 0 to 199 (out/train.json). "Every leaf decayed" is MaxText's default adamw_mask: []. "The running example's settings" reproduces the root's published 500-step curve (src/data/equiv.json) within 4.9e-7 for these 200 steps.

5. Scan over layers, and what remat keeps

With scan_layers: true () the decoder traces one layer inside jax.lax.scan over stacked weights, so the program and the compile time stop growing with depth (PyTorch eager has no counterpart; under torch.compile the closest is compiling one block and reusing it; scan against a Python loop is measured on JAX core; nnx.scan is on the training stack). Each scanned layer is wrapped in jax.checkpoint(layer_fn, policy=policy) with the policy named by remat_policy (, default full) through get_remat_policy (): full keeps only each layer's input and recomputes the rest in the backward pass; the others keep tensors the layers name with checkpoint_name (query_proj, key_proj, value_proj, out_proj, mlpwi, mlpwo, context; e.g. ). minimal () keeps every projection output; the *_offloaded policies move them to host memory. PyTorch's counterpart is torch.utils.checkpoint with a selective policy.

Predict: for the running example's step compiled by MaxText, which policy needs the most temporary memory, and which does the most FLOPs?

What it shows. For a given scan setting every policy gives bit-identical losses: remat changes what is stored, never the result. minimal stores 50% more than full and saves 15% of the FLOPs (4.29 GFLOP of recomputed forward). save_out_proj came out below full (87.4 MB against 100.1 MB): XLA's buffer assignment on CPU is not monotone in what the policy saves, so measure rather than assume. Scan: 8,166 lines of optimised HLO against 22,270 unrolled, for only four layers. On TPU the ordering transfers and the sizes do not (bfloat16 activations, thousands of tokens, HBM per chip): pick the policy that fits HBM with the fewest recomputed FLOPs, the arithmetic TPU programming and performance does for real chips.

Two details of the remat runs, and MaxText's checkpoints

The unrolled rows start from different random weights (first-step loss 4.5451 against 4.5840 scanned): with the same seed, creating four layers one by one does not draw the same numbers as one stacked array. Converting a checkpoint between layouts is stacking or unstacking the same numbers. minimal_with_context equals minimal here because the gpt3 block names no context tensor.

Checkpoints. MaxText writes them with Orbax's v1 API (from orbax.checkpoint import v1 as ocp, ; ocp.training.Checkpointer, ), asynchronously by default (), every 10,000 steps (), and resumes automatically: "If there is already a checkpoint for this run_name, we load the latest entire checkpoint" (). Not run here (every run sets enable_checkpointing=false); the training stack runs Orbax itself.

Saving more trades memory for recompute, and never changes the loss measured

remat_policyscan_layersXLA tempXLA FLOPscompileHLO linesloss, 3 steps

runs/lc_remat.py: MaxText's train step for the running example's shape (batch 32 × 128, float32, MaxText's own initialisation), compiled on CPU; memory_analysis().temp_size_in_bytes and cost_analysis()["flops"]. XLA's cost analysis counts a scanned loop body once (as XLA and compilation found: 7.40 GFLOP scanned against 28.90 unrolled for the same computation), so compare FLOPs only between unrolled rows. Compile times rough.

6. How MaxText counts MFU, and what its published table used

Model FLOPs utilisation (MFU) is the model's FLOPs per step divided by step time and peak FLOP/s (Performance math derives it). MaxText's count, calculate_tflops_training_per_device (), takes every weight matmul at 2 FLOPs per multiply-add, times 3 for forward plus backward ("multiply by 3 to account for 1 forward pass + 2 backward passes", ), plus attention's score and value products, halved for the causal mask since July 2025 (causal_attention_flops = noncausal_attention_flops / 2, ; the docs, ). It counts the output projection, not the embedding lookup, and never recomputation, so heavier remat lowers MFU without changing the count. On the running example's step: 21.14 GFLOP (19.53 in weight matmuls, 1.61 in attention), against 23.69 from XLA's cost analysis (the JAX core page's measurement), which counts unmasked attention, elementwise work and softmax. MFU uses the analytic count on purpose: it does not depend on the implementation.

MaxText's own MFU table matches its old, non-causal count, not the current one derived

ModelChip, sequencepublished MFUpublished tokens/s/chipimplied, current countimplied, pre-July-2025 count

Published: vendor figures from at 1a95d1e5 (undated). Implied MFU = tokens/s/chip × training FLOPs per token ÷ peak, FLOPs per token from calculate_tflops_training_per_device run on CPU for each model config at that sequence length (runs/lc_mfu.py), peak bf16 per chip from Google's Cloud TPU pages (v6e 918, v5p 459 TFLOP/s; the root's FACTS, read 2026-10-15). "Pre-July-2025" doubles the attention term back, the count before MaxText PR #1988.

What it shows. Five of the eight rows reproduce within 0.02 points under the old count (Llama 3.1 8B: 45.47% implied against 45.46% published) and none under the current one (40.41% for the same row): the table predates the halving, as its own footnote warns for "some older" results. The other three match neither closely: Llama 2 70B on v6e (43.58% old, 42.00% current, against 43.8%), on v5p (67.01% or 64.58% against 65.4%), Llama 3.1 405B (35.18% or 33.82% against 38.55%); the tokens/s column is labelled approximate, but rounding cannot explain a 3-point gap. An MFU is comparable only with its FLOP count and version; tokens per second need no correction.

7. Tunix: a thin trainer and RL placement by mesh

Tunix ("Tune-in-JAX", ) is Google's post-training library on Flax NNX: SFT with full weights or LoRA, DPO and ORPO, PPO, GRPO and its variants (GSPO-token, DAPO, Dr.GRPO), multi-turn agentic RL and distillation, with vLLM's TPU backend or SGLang-JAX for generation. MaxText's post-training is Tunix underneath: its SFT, DPO and RL entry points import tunix.sft.peft_trainer, tunix.sft.dpo.dpo_trainer and tunix.rl.grpo.grpo_learner (, , ). The algorithms are taught on Alignment: SFT, RLHF, DPO family, RLVR and RL for LLMs; this section is about the code.

The trainer is twenty lines measured. PeftTrainer._train_step () is the whole algorithm, wrapped in nnx.jit(train_step, donate_argnames=("optimizer",)) (); the rest of the 882-line file is data iteration, metrics, profiling and checkpoints:

inputs = self.gen_model_input_fn(inputs)
grad_fn = nnx.value_and_grad(self.loss_fn,
    argnums=nnx.DiffState(0, nnx.LoRAParam) if self._lora_enabled else 0, has_aux=self._has_aux)
out, grads = grad_fn(model, **inputs)
grad_norm = optax.global_norm(grads)
optimizer.update(model, grads)

LoRA is not a separate code path: if the model carries nnx.LoRAParam variables, the optimizer is built with wrt=nnx.LoRAParam () and only they get gradients. Gradient accumulation is optax.MultiSteps around your optimizer (). So Tunix trains the running example as it is: runs/lc_tunix.py gave PeftTrainer the root's NNX model, optax chain and loss (with_loss_fn, with_gen_model_input_fn), and 100 steps matched the root's own NNX run to in loss. Its default loss () normalises by target tokens plus 1e-8 (), so an all-padding batch gives zero loss instead of NaN.

The Tunix run's code, and LoRA through Qwix on the running example (a toy)
# runs/lc_tunix.py (abridged)
trainer = peft_trainer.PeftTrainer(model, tx, peft_trainer.TrainingConfig(eval_every_n_steps=10**9, max_steps=100))
trainer = trainer.with_loss_fn(loss_fn).with_gen_model_input_fn(lambda b: {"x": b["x"], "y": b["y"]})
trainer.train(batches(0, 100, 500))     # dicts of the running example's int32 batches

LoRA through Qwix, as Tunix's own tests apply it measured

Run (100 steps)trainable parameterssharevalidation loss beforeafter

Base: the root's model after its 500-step run (validation loss 2.0692, the root's figure). LoRA from qwix.LoraProvider(module_path=".*(wq|wk|wv|wo|fc1|fc2).*", rank=r, alpha=2r) and qwix.apply_lora_to_model, the call in Tunix's tests/test_common.py; Tunix detected the LoRA parameters and trained only them. Each run: 100 more batches (500 to 599), optax.adamw(1e-3, b1=0.9, b2=0.95, weight_decay=0), constant rate, one seed, nothing tuned; validation on the root's 8 fixed batches. A toy: it shows the mechanics and parameter counts; that LoRA beats full fine-tuning here says more about an untuned rate on fresh Adam state than about LoRA. PEFT and the LoRA paper page have the real comparisons.

One GRPO step: colocated roles take turns on one mesh; disaggregated roles overlap but move weights every step

Placement

Read from grpo_learner.py and rl_cluster.py at v0.1.7 (_generate_and_compute_advantage, : generate , reference log-probabilities , advantages ; defaults num_generations = 2, beta = 0.04, epsilon = 0.2, ). Not run here: Tunix's samplers need a model with a key-value cache interface and a tokenizer, which the running example lacks; an illustrative sequence, not a timing.

RL: models by role, each on a mesh. RL for an LLM needs up to five models: the actor being trained, a frozen reference for the KL penalty, a rollout engine that generates, a reward model and, for PPO, a critic. Tunix's Role enum names them (), and ClusterConfig.role_to_mesh is "Key config for colocated vs disaggregated setup" (). Same mesh for actor and rollout: they share one copy of the weights (), and with LoRA the reference shares the actor's frozen backbone too (). Different meshes: every step ends with sync_weights () pushing the actor's parameters to the rollout engine, which is "vanilla", "vllm" or "sglang_jax" ().

Fig. 5, step by step: one GRPO step through RLCluster

  1. Prompts. A batch of prompts arrives from the data iterator; the learner asks the cluster for completions.
  2. Generate (rl_cluster.generate): the rollout role samples num_generations completions per prompt (default 2) with the vanilla JAX sampler, vLLM or SGLang-JAX.
  3. Score. Reward functions (Python, often a verifier) give each completion a scalar.
  4. Reference log-probabilities (get_ref_per_token_logps) on the reference role's mesh, for the KL penalty (beta = 0.04 by default). With LoRA the reference is the actor's frozen backbone, so no second copy.
  5. Advantages. Each completion's reward minus its group's mean, divided by the group's sample standard deviation plus 1e-6 (the "grpo" estimator, ). No critic model.
  6. Update the actor (update_actor): a PeftTrainer step on the actor role's mesh with the clipped objective (epsilon = 0.2) plus the KL term.
  7. Sync weights (sync_weights). Colocated, the actor and rollout are the same NNX model on the same mesh (the backbone-sharing map), so the next generation already sees the update; no transfer. Disaggregated, the rollout engine holds its own copy, so the actor's parameters (only the LoRA ones if LoRA is on) are pushed to it after every step: the price of running generation and training on separate chips.

Colocated is simpler and moves no weights, but training and generation take turns on the same chips; disaggregated lets a generation-optimised engine (vLLM's TPU backend) run on its own slice, at the cost of a weight transfer every step. PyTorch's verl makes the same choice ("hybrid engine" against separate placement).

Version skew, measured. MaxText's post-training does not use the Tunix release: src/dependencies/extra_deps/post_train_github_deps.txt pins google-tunix @ https://github.com/google/tunix/archive/c2ee3bd8...zip (). With PyPI v0.1.7 installed, MaxText main's SFT entry point fails at import, ImportError: cannot import name 'diffusion' from 'tunix.sft'; its DPO entry point imports fine. Install both from MaxText's own requirement files.

8. Levanter in Marin: named axes and bitwise reproducibility

Levanter is Stanford CRFM's trainer, "built with JAX, Equinox, and Haliax", designed to be "legible, scalable, and reproducible": "Levanter is bitwise deterministic, meaning that the same configuration will always produce the same results, even in the face of preemption and resumption" (). It now lives in the Marin monorepo (lib/levanter).

Where Levanter lives now, and what Marin is

The standalone repository says "Levanter has been merged into Marin as of November 2025" (, frozen at 982cef7f); development continues in the Marin monorepo under lib/levanter (255 Python files, 87,114 lines at 1290cfb5), on PyPI as marin-levanter development builds (0.2.180.dev38754195437, uploaded 2026-10-15), requiring jax>=0.9.2,<0.12 (). Marin is an open research programme that logs every experiment; its README lists a scaling suite trained on Google's TPU Research Cloud and, as current work, a 500B+ parameter mixture-of-experts model. Its newer grug/ package (28 files) holds array-first building blocks for model templates; it was not read in depth here.

Named tensors. Haliax arrays carry a name per dimension and every operation names the axes it touches. Levanter's GPT-2 attention splits its fused projection with q, k, v = qkv_out.unbind("qkv") () and renames the keys' sequence axis, k.rename({"position": "key_position"}) (), because a product of two arrays that both have position would contract or broadcast the wrong one. In PyTorch you track this in comments next to transpose(1, 2); its experimental named tensors are little used. Modules are Equinox modules (plain pytrees), not Flax. The running example's attention, with named axes:

# runs/lc_haliax.py (abridged): block 0's attention of the running example, with named axes
Batch, Pos, KPos = Axis("batch", 32), Axis("position", 128), Axis("key_position", 128)
Embed, Heads, HeadSize = Axis("embed", 128), Axis("heads", 4), Axis("head_size", 32)
q = hax.dot(hn, W("wq"), axis=Embed) + Bv("wq")                        # [batch, position, heads, head_size]
k = (hax.dot(hn, W("wk"), axis=Embed) + Bv("wk")).rename({"position": "key_position"})
scores = hax.dot(q, k, axis=HeadSize) / math.sqrt(32)                  # no transpose to remember
probs = hax.nn.softmax(hax.where(causal, scores, -jnp.inf), axis=KPos)
ctx = hax.dot(probs, v, axis=KPos)
out = hax.dot(ctx, wo, axis=(Heads, HeadSize)) + bo
# result, on the running example's initial weights and first batch (marin-haliax 0.2.180.dev38754195437)
max |named - plain JAX attention| =      shape [32, 128, 128]
hax.dot(q, k, axis="embed")  ->  

Sharding by name. Levanter has no separate logical vocabulary: a dictionary maps the model's own axis names to mesh axes (, , ). Mesh axes data (absorbs all devices), replica and model (1 each), replica_dcn across slices; mlp and heads map to model; for parameters only, embed maps to data, which is FSDP. Parameters and activations get separate mappings (parameter_axis_mapping, compute_axis_mapping), and the trainer reshards the new state with the parameter mapping after every update ().

WeightLevanter (default mapping, mesh data × model)MaxText (base rules, mesh fsdp × tensor)

Same idea, different spelling: FSDP on the embedding dimension, tensor parallelism on mlp and heads. Levanter specs from Haliax's pspec_for_axis with the default mapping (runs/lc_haliax.py); MaxText specs from runs/lc_shard.py on the running example's gpt3 config under fsdp 2 × tensor 4, without the stacked layers dimension.

Reproducibility. Bitwise determinism needs three things, all visible in the code: explicit PRNG keys (JAX has no global random state), a data loader that can jump to batch n without replaying the stream (Levanter writes a preprocessed cache with random access and shuffles with a pseudo-random permutation, ), and checkpoints that hold the step and the keys. The README's caveat: training "can even be resumed on a different number of hosts, though this breaks reproducibility for now". The TPU claim was not tested here; the CPU side was: the running example's reruns are deterministic, and the training stack shows a restored Orbax checkpoint continuing bit for bit on the same mesh, and drifting by about 3e-6 within 40 steps when restored into freshly annotated shardings.

9. The others, the history, and where serving went

CodebaseStatusRead it for judgement
EasyDeLactive 0.3.0 (2026-07-27), mostly one maintainerMany Hugging Face architectures in Flax NNX with SFT, DPO and GRPO trainers: good for trying a model quickly, a bus-factor risk in production.
AXLearn (Apple)active pushed 2026-07-08; trained Apple's foundation models (the root's Reading tab, section 1)A second large-company design, configuration-heavy; worth an afternoon to compare with MaxText.
T5Xquiet recent commits are automatedGin configs and partitioning rules of the pjit era: MaxText's logical axis rules descend from this style.
Pax (paxml, praxis)quiet last release 1.4.0, 2024-04-09PaLM-era Google training framework; history only.
Saxmlquiet last tag v1.2.0 (2024-02-21); recent commits automated (checked 2026-10-23)Pax's serving side: "an experimental system that serves Paxml, JAX, and PyTorch models for inference" (its README). History only; serve with vLLM on TPU.
EasyLMquiet last commit 2024-08-13A complete pjit-era LLM trainer small enough to read in an afternoon; uses APIs deprecated since (pjit).
big_visionquiet last commit 2025-05-19The cleanest Linen-era training code (ViT, SigLIP, PaliGemma); read to understand older Flax code.

Status from the root's Tool map (read 2026-10-15) except Saxml (GitHub, 2026-10-23). None of the quiet ones carries an official deprecation notice; "quiet" is a reading of commit and release dates. The lineage, on the root's Tool map: T5X and Pax (with Saxml) gave way to MaxText in Google's practice, EasyLM to mesh-based trainers, Levanter to Marin.

Serving. Training codebases decode, but serving at scale is a separate engine. vLLM on TPU (tpu-inference 0.31.0, 2026-10-06, with vllm 0.31.0) is the default: vLLM's scheduler and paged KV cache with a TPU backend that, in vLLM's words, unifies "JAX and PyTorch under a single lowering path" (vLLM blog, 2025-10-16). MaxText ships an adapter (integration/vllm/, inference/vllm_decode.py) and its post-training pins a tpu-inference commit for RL rollouts (); the engine is taught on vLLM: inside the default engine. SGLang-JAX (0.1.0rc0, 2026-08-29) is a JAX-native engine from the SGLang team, separate from SGLang's PyTorch code; Tunix can use it for rollouts (SGLang has the radix cache). JetStream, Google's earlier engine for MaxText models, announced it would archive on 2026-02-01 with its functions moved to tpu-inference; on 2026-10-15 GitHub still showed it unarchived, and MaxText still contains its engine (inference/maxengine/; decoupled mode stubs it out). Do not start new work on it.

10. Which one to start from

Your jobStart from judgementBecause (sections above)
Pretrain or continue pretraining a dense or MoE LLM on TPU (or GPU) at scaleMaxText86 model files, parallelism and remat as config (1, 3, 5), published MFU tables with a stated FLOP count (6). Pin a commit: main is "not expected to be production-ready".
SFT, LoRA, DPO or GRPO on a Flax NNX modelTunix, or MaxText's post-training entry points for MaxText modelsA trainer you can verify against your own loop in an afternoon; RL placement by role_to_mesh (7). With MaxText, install the Tunix commit MaxText pins.
Research that needs bit-identical reruns, or code you want shape-checked by nameLevanter in MarinNamed axes, seekable data cache, keys in checkpoints (8).
Try a Hugging Face architecture in JAX quicklyEasyDeLBreadth of models and trainers; mostly one maintainer (9).
Learn how a JAX LLM trainer is builtThe running example, then MaxText's five files (Further reading), EasyLM for the pjit eraThe five boxes are the same; read the box you need next.
Serve what you trainedvLLM on TPU (tpu-inference)JetStream is retired; Saxml is history (9).

Whichever you pick, port with an equivalence test first: same weights and batch, logits, then loss, then a few hundred steps against your own loop. On this page it found three silent differences (activation, warmup, decay mask) between two correct-looking configs.

Depth: what to copy, the real errors, design questions

What to copy into your own JAX code, and why it pays
IdeaFromWhy it pays
Logical axis names on every weight and activation, one mapping table in the configMaxText (rules), Levanter (dictionary)Parallelism becomes configuration; the same model runs on 8 devices or 8,960. Start with FSDP on the embedding dimension; add tensor when FSDP's all-gathers stop hiding behind compute.
A validated config object that refuses double overrides and unknown keysMaxTextThe silent errors move to start-up. Log the resolved config of every run.
Build the abstract model firstMaxText (create_nnx_abstract_model)Shapes, shardings and bytes per device for a 7B model before any memory is allocated.
Scan over layers, and name the tensors remat may keepMaxText (scan_layers, checkpoint_name, remat_policy)Compile time independent of depth; memory against recompute chosen by config.
Donate the train state; return metrics as arraysMaxText, TunixOne copy of parameters and optimizer state; no host synchronisation inside the step.
A thin trainer: value_and_grad, optimizer.update, nnx.jitTunix (PeftTrainer)Easy to verify against your own loop; LoRA by variable type, accumulation by optax.MultiSteps.
An analytic FLOP count for MFU, with its version written downMaxTextComparable across implementations and remat policies; the causal halving changed the published numbers by up to 5 points.
Data that can seek to batch nLevanter (cache, permutation), grainBitwise resumption after preemption.
The real errors you will meet, and the fix for each

Overriding a model file's key on the command line

ValueError: Keys ['base_emb_dim'] are overridden by both model config and CLI/kwargs with different values.This is not allowed, unless setting `override_model_config=True`.

Drop model_name and set every shape key yourself, or pass override_model_config=True knowingly.

Parallelism degrees that do not multiply to the device count

Parsing succeeds; the error comes when the mesh is built. Leave exactly one ICI degree at -1 and let it absorb the rest.

A dimension the mesh cannot divide

IndivisibleError: ... spec=P('fsdp', 'tensor') ... implies that array axis 1 is partitioned 4 times, but the dimension size is 65

Pad the vocabulary (and head counts) to multiples of the axis sizes you will use; 128 or 256 for the vocabulary.

Installing MaxText main with the Tunix release

ImportError: cannot import name 'diffusion' from 'tunix.sft' (unknown location)

Install both from MaxText's requirement files.

Leaving adamw_mask empty with RMSNorm-style scales

Biases, norm scales and embeddings get weight decay. For the gpt3 block the scale is an offset, so decay pulls it toward 1; for scales stored directly (RMSNorm models) it pulls them toward 0. Set the mask explicitly.

Reading FLOPs from cost_analysis() of a scanned program

XLA counts the loop body once: 7.40 GFLOP for the scanned step against 28.90 GFLOP unrolled, same computation.

Design question: GRPO fine-tuning of an 8B dense model on one v5p-64 slice. What do you build?
MaxText's model with Tunix's GRPO learner (what MaxText's RL entry point does), versions pinned together. Trainer: FSDP over the slice's ICI, bfloat16 activations, float32 master weights, remat_policy chosen by compiling a step and reading memory. Rollout: vLLM TPU; start colocated on the full slice (simplest, no weight sync), move to a split (for example 48 chips training, 16 generating) if generation dominates step time. Consider LoRA to cut memory and weight-sync volume. Checkpoint asynchronously with the data iterator state. Validate with a tiny config on CPU first (this page's method), then a short run measured against MFU with a stated FLOP count.
Design question: two teams report 45% and 40% MFU for the same run. How?
Different FLOP counts. MaxText halved attention FLOPs for causal masking in July 2025; its own table's Llama 3.1 8B row is 45.46% under the old count and 40.41% under the new one. Also check whether recomputation or the embedding is counted, and the peak FLOP/s used.
Design question: what breaks bitwise reproducibility when resuming?
A data loader that cannot seek (or reshuffles), PRNG keys not saved, a different number of hosts or a different mesh (reductions in a different order; Levanter's README says so), restoring into different shardings (the training stack page measured a 3e-6 drift), and nondeterministic kernels.
Design question: Levanter's named axes against MaxText's logical rules?
Levanter: the model's own axis names, mapped by a dictionary, separately for parameters and compute; operations name their axes, so shape bugs fail at trace time. MaxText: positional arrays with logical names attached, an ordered rule list with fallbacks (the two embed rules), more machinery for many parallelism kinds. Same compiler underneath.

Sources quoted at MaxText main 1a95d1e5 (2026-10-15), Tunix v0.1.7 (ce63a9fd, 2026-06-09), Levanter in Marin main 1290cfb5 (2026-10-15) and the frozen Levanter repository 982cef7f; every file and line is located by pattern in src/runs/lc_source.py. Runs: src/runs/, outputs in src/out/, all on 2026-10-15 on an Apple M1 Pro CPU with jax 0.11.2 and flax 0.12.10.