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
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.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.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.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:
embed, mlp, heads), never a device.layers axis.| Codebase | What it is | Status, October 2026 | PyTorch counterpart |
|---|---|---|---|
| MaxText | 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 | 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_vision | A 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.
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.
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:
configs/base.yml: 1,669 lines, 828 top-level keys, every default with a comment.configs/models/<model_name>.yml (86 model files): shapes, activations, tokenizer, sometimes extra sharding rules.key=value pairs and Python keyword arguments.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.
model_name=llama2-7b base_emb_dim=128. What does MaxText do?validate_no_keys_overridden_twice () raises 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`. (the missing space is in the source). With override_model_config=True the command line wins and you get a 128-wide model with Llama 2 7B's 32 heads of 128: a shape no checkpoint will load into.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.
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.
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.
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
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.[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.[embed, heads, kv] = [128, 4, 32]. Each colour is one head; nothing moves in memory.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.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.blocks.{0..3}.ln1.weight, four vectors of 128 ones at initialisation; the output is normalised x weight + bias.Gpt3LayerNorm initialises its scale to zeros () and multiplies by scale + 1 (), so the stored value is the offset from 1: 1.0 becomes 0.0.[norm, layers] = [128, 4], path decoder.layers.pre_self_attention_norm.scale.blocks.{0..3}.mlp.fc1.weight, four [512 out, 128 in] matrices.[embed, mlp] = [128, 512].[embed, layers, mlp] = [128, 4, 512], path decoder.layers.mlp.wi.kernel, logical names ("embed", "layers", "mlp"): the same names the Llama weights carry in section 3.mlp_activations=[gelu] resolves to getattr(jax.nn, "gelu") (), the tanh approximation; the running example uses exact erf GELU, and no MaxText flag spells it. Against exact GELU the logits differ by up to ; with a tanh-GELU twin the gap falls to , float32 rounding.| 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.
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:
), 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.), applied by logical_to_spec (): "A dimension takes the first matching rule whose mesh axes no other dimension uses yet" ().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:
Fig. 3, step by step: one weight walks the rule table onto 8 chips
layers axis left out), each edge labelled with its logical name and size. The model never says more than this about placement.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.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.| Rule | Dimension | Result |
|---|
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.
| Parameter | Shape | Logical names | PartitionSpec | Per 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.
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.
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):
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).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.grad_dtype, clipped by global norm () and applied by state.apply_gradients(grads) (), the optax chain.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
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.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.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.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.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).value_and_grad builds the backward program now.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.donate_argnums=0), and the executable runs. Step 0 took s of wall time ( s of CPU time across threads).p_train_step(state, batch): JAX flattens the arguments (the NNX state is a pytree: Flax made Python calls) and looks the signature up in its cache.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 .
optax.linear_schedule(0.0, lr, warmup_steps) is 0 at count 0; the recorded schedule reads 0.0, 2e-4, 4e-4, ... every 10 steps up to 1e-3 at step 50. AdamW's decay is multiplied by the learning rate too. The loss at step 1 (4.2184) is the initial model on a new batch, higher than the running example's 4.1822 after one real update.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.
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.
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.
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.
| remat_policy | scan_layers | XLA temp | XLA FLOPs | compile | HLO lines | loss, 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.
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.
| Model | Chip, sequence | published MFU | published tokens/s/chip | implied, current count | implied, 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.
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.
# 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
| Run (100 steps) | trainable parameters | share | validation loss before | after |
|---|
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.
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
rl_cluster.generate): the rollout role samples num_generations completions per prompt (default 2) with the vanilla JAX sampler, vLLM or SGLang-JAX.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.). No critic model.update_actor): a PeftTrainer step on the actor role's mesh with the clipped objective (epsilon = 0.2) plus the KL term.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.
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).
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 ().
| Weight | Levanter (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.
| Codebase | Status | Read it for judgement |
|---|---|---|
| EasyDeL | active 0.3.0 (2026-07-27), mostly one maintainer | Many 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. |
| T5X | quiet recent commits are automated | Gin 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-09 | PaLM-era Google training framework; history only. |
| Saxml | quiet 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. |
| EasyLM | quiet last commit 2024-08-13 | A complete pjit-era LLM trainer small enough to read in an afternoon; uses APIs deprecated since (pjit). |
| big_vision | quiet last commit 2025-05-19 | The 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.
| Your job | Start from judgement | Because (sections above) |
|---|---|---|
| Pretrain or continue pretraining a dense or MoE LLM on TPU (or GPU) at scale | MaxText | 86 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 model | Tunix, or MaxText's post-training entry points for MaxText models | A 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 name | Levanter in Marin | Named axes, seekable data cache, keys in checkpoints (8). |
| Try a Hugging Face architecture in JAX quickly | EasyDeL | Breadth of models and trainers; mostly one maintainer (9). |
| Learn how a JAX LLM trainer is built | The running example, then MaxText's five files (Further reading), EasyLM for the pjit era | The five boxes are the same; read the box you need next. |
| Serve what you trained | vLLM 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.
| Idea | From | Why it pays |
|---|---|---|
| Logical axis names on every weight and activation, one mapping table in the config | MaxText (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 keys | MaxText | The silent errors move to start-up. Log the resolved config of every run. |
| Build the abstract model first | MaxText (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 keep | MaxText (scan_layers, checkpoint_name, remat_policy) | Compile time independent of depth; memory against recompute chosen by config. |
| Donate the train state; return metrics as arrays | MaxText, Tunix | One copy of parameters and optimizer state; no host synchronisation inside the step. |
A thin trainer: value_and_grad, optimizer.update, nnx.jit | Tunix (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 down | MaxText | Comparable across implementations and remat policies; the causal halving changed the published numbers by up to 5 points. |
| Data that can seek to batch n | Levanter (cache, permutation), grain | Bitwise resumption after preemption. |
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.
Parsing succeeds; the error comes when the mesh is built. Leave exactly one ICI degree at -1 and let it absorb the rest.
IndivisibleError: ... spec=P('fsdp', 'tensor') ... implies that array axis 1 is partitioned 4 times, but the dimension size is 65Pad the vocabulary (and head counts) to multiples of the axis sizes you will use; 128 or 256 for the vocabulary.
ImportError: cannot import name 'diffusion' from 'tunix.sft' (unknown location)
Install both from MaxText's requirement files.
adamw_mask empty with RMSNorm-style scalesBiases, 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.
cost_analysis() of a scanned programXLA counts the loop body once: 7.40 GFLOP for the scanned step against 28.90 GFLOP unrolled, same computation.
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.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.
Three LLM codebases, box by box. Each row is a part of a repository at its pinned commit, its bar the lines of Python (and YAML for MaxText's configs) it holds, counted by runs/lc_map.py without tests. Pick a concern to see where each codebase keeps it; click a row for its role, its PyTorch counterpart, the symbols worth reading at their lines, and where this topic teaches it.
Lines are physical lines of source files (comments and blank lines included), so they measure reading effort, not complexity. Commits: MaxText main 1a95d1e5 (2026-10-15), Tunix v0.1.7 (2026-06-09), Levanter in Marin main 1290cfb5 (2026-10-15). The roles are this page's summaries of each part, checked against the code at those commits.
MaxText's base.yml at main 1a95d1e5 has 1,669 lines and 828 top-level keys. These 81 are the ones that change what gets trained and how it is laid out. For each: its line, the default and the comment as written, what it does (this page's words), and the value in eight model files when they set it.
Extracted from the file by runs/lc_cfgdata.py: the line number, default and comments are verbatim. "Running example" is the override this page passed to run the topic's model through MaxText (runs/lc_cfg.py); blank means the default applied. Model-file values are read from configs/models/*.yml; a model file only lists what it changes.
This page's tabs, the knowledge base pages it leans on, and the best outside resources, each with an approximate time. Outside sources are marked Google (MaxText, Tunix, JAX: authoritative on how their code works, not neutral on whether to use it) or third-party. Links checked on 2026-10-15; GitHub links from this page point at the pinned commits.
The five boxes and what each codebase invests in; MaxText's config, model, logical-axis sharding, train step (traced function by function), scan and remat, and MFU count, with the running example run through all of them; Tunix's trainer and RL placement; Levanter's named axes; the others and serving; which to start from. 27 min, plus 8 in closed details
MaxText, Tunix and Levanter part by part with sizes, roles, PyTorch counterparts and the symbols worth reading at their lines. about 2 min, longer as a reference
81 MaxText flags: line, default and comment from base.yml, what each does, values in eight model files. about 2 min, longer as a reference
The root: the comparison, the running example, the labs. Its Reading tab section 7 introduces these codebases; its Tool map tab dates every library and serving engine. Reading: 32 min, plus 13 in closed details
Tracing, jaxprs, jit, grad, vmap, scan against Python loops: why MaxText's Python runs once. 44 min, plus 25 in closed details
What happens after tracing: StableHLO, fusion, recompiles, profiles, and MaxText's XLA flag library. 39 min, plus 13 in closed details
Flax NNX split and merge, optax chains, Orbax and grain, run on the running example: the pieces MaxText and Tunix are built from. 33 min, plus 21 in closed details
Porting the running example from PyTorch, default by default; the method this page used to check MaxText's step. 28 min, plus 17 in closed details
Meshes, PartitionSpecs, GSPMD and Shardy, every parallelism measured, pipeline bubbles (MaxText's formula), MoE all-to-all, choosing a mesh for a slice. 45 min, plus 26 in closed details
The chips MaxText's MFU table was measured on: rooflines per generation, memory planning, MFU from published step times. 33 min, plus 13 in closed details
The kernels MaxText calls on TPU (splash attention, megablox), written and tested in interpret mode. 37 min, plus 13 in closed details
torchtitan, the Hugging Face stack, Lightning, DeepSpeed: the PyTorch side of this page's comparison. 27 min, plus 12 in closed details
FSDP2, DTensor, tensor and pipeline parallelism in PyTorch, against MaxText's logical axes. 35 min, plus 20 in closed details
Tensor parallelism inside the model code, the design MaxText's rules replace. about 23 min
FLOPs, MFU and tokens per second from first principles. about 24 min
What the LoRA run on this page only demonstrates mechanically. 22 and 21 min
The algorithms Tunix implements: DPO, PPO, GRPO and their variants. 25 and 43 min
The serving engines behind tpu-inference and SGLang-JAX. 41 min, plus 15 in closed details; 34 min, plus 16 in closed details; 35 min, plus 3 in closed details
Start at README.md, src/maxtext/configs/base.yml, trainers/pre_train/train.py, layers/nnx_decoders.py, utils/sharding.py. about 2 h for those five
Architecture overview, performance metrics (the MFU definition and the causal-attention change), the tiering table, decoupled mode for running without Google Cloud. about 1 h
Read tunix/sft/peft_trainer.py, tunix/rl/rl_cluster.py and tunix/rl/grpo/grpo_learner.py; the docs' design overview and examples. about 1.5 h
The Levanter 1.0 release note (in lib/levanter/docs) explains named tensors and bitwise determinism with figures; the data loader design document explains resumable data. about 1 h
The scaling book: the sharding and roofline reasoning behind MaxText's defaults, applied to Llama 3 70B on a v5p pod. several hours
Why vLLM's TPU backend replaced JetStream as the place to serve JAX models. about 15 min
Read beside MaxText: the same five boxes in PyTorch, with parallelism as wrappers. about 1 h