model-bringup-m3
Skill2.5k starsChanged 4 days agoApache-2.0View on GitHub
Brings up a new LLM or MoE model family end-to-end in MaxText m3 (`src/maxtext/m3/`) using pure Flax NNX. Use when onboarding a HuggingFace model to `m3` (`use_m3_model=True`), implementing `Sharding` on `(data, fsdp, tensor, expert)`, writing HF/Orbax checkpoint converters, running the 8-check M3 conformance + `PerturbSpec` suite, or verifying real-weight `FrozenTopK` TPU parity. Do not use for legacy Flax Linen models under `src/maxtext/layers/`.
Trending
Less talk lately.about the whole repository
Who's talking about AI-Hypercomputer/maxtext
- ROCm/jax-titan“General Adapters”GitHub · Nov 19, 2026 · 1 reactions
- google/tunix“Let the dist_rl rollout node load MaxText checkpoints without weight sync”GitHub · Nov 19, 2026 · 1 reactions
- google/tunix“Stacked on #2979 (`uwlei/rl-4600-final-tunix` @ `54f488d8`); **retarget base branch to `atwigg/mlperf` once …”GitHub · Oct 21, 2026 · 1 reactions
- google/tunix“[MLPerf RL 397B]Supersedes #2884, #2948, #2913, and #2940 onto `atwigg/mlperf`.”GitHub · Oct 21, 2026 · 1 reactions
- AI-Hypercomputer/tpu-recipes“Add recipe for training Maxtext Qwen3.5-35B-A3B with v6e-256 #recipebot”GitHub · Oct 20, 2026 · 1 reactions
The biggest 5 of 50 mentions linking to the repository that our crawl found. Each line is their own headline.
See all 50
Talked about on GitHub (50 times).
On GitHub · 50
- Nov 19, 2026General Adapters — ROCm/jax-titan1 reaction · 2 comments
- Nov 19, 2026Let the dist_rl rollout node load MaxText checkpoints without weight sync — google/tunix1 reaction · 1 comment
- Oct 21, 2026Stacked on #2979 (`uwlei/rl-4600-final-tunix` @ `54f488d8`); **retarget base branch to `atwigg/mlperf` once #2979 merges**. — google/tunix1 reaction · 2 comments
- Oct 21, 2026[MLPerf RL 397B]Supersedes #2884, #2948, #2913, and #2940 onto `atwigg/mlperf`. — google/tunix1 reaction · 2 comments
- Oct 20, 2026Add recipe for training Maxtext Qwen3.5-35B-A3B with v6e-256 #recipebot — AI-Hypercomputer/tpu-recipes1 reaction
45 more on GitHub
- Oct 15, 2026orchestrator: compact routed_experts wire packing with uint10/uint8 encoding and unrouted-token stripping — google/tunix1 reaction · 1 comment
- Oct 6, 2026feat(maxtext): bump commit pin for RBF overflow logging — google/tunix1 reaction · 1 comment
- Sep 30, 2026Add ROLLOUT_FP8 / TRAINER_FP8 switches for FP8 MoE in all recipe launchers — google/tunix1 reaction · 1 comment
- Sep 30, 2026feat(recipes): add FP8_MOE environment variable directly to mlperf recipes — google/tunix1 reaction · 1 comment
- Sep 19, 2026Migrate Llama 3.1 8B on Trillium (v6e-8) to Cluster Toolkit — AI-Hypercomputer/tpu-recipes1 reaction
- Oct 25, 2025Feature Enhancement: Add Advanced Post-Training and Fine-Tuning Capabilities to Simply — google-deepmind/simply1 reaction
- Dec 2, 2026With `weight_sync_config.mode: none` (evaluation), a MaxText vLLM rollout had no way to load real weights because config resolution required Raiden weight sync. Add checkpoint loading support for both unscanned and scanned MaxText checkpoints on the stock `dist_rl` rollout node, plus opt-in Pathways — google/tunix0 reactions · 1 comment
- Oct 30, 2026[AutoPGLE] Let the host run ahead and enqueue work — jax-ml/jax0 reactions
- Oct 20, 2026Migrate MaxText E2E checkpoint conversion (to-mt and to-hf) to CPU cluster — GoogleCloudPlatform/ml-auto-solutions0 reactions
- Oct 19, 2026Layer streaming: measure saving the attention projections instead of recomputing the whole layer — MakazhanAlpamys/Soup0 reactions · 3 comments
- Oct 16, 2026Migrate MaxText E2E checkpoint conversion (to-mt and to-hf) to CPU cluster — CIeNET-International/ml-auto-solutions-30 reactions · 1 comment
- Oct 14, 2026update maxtext pin — google/tunix0 reactions · 1 comment
- Oct 13, 2026recipes: opt-in Raiden trainer knobs for the pathways-worker and trainer client — google/tunix0 reactions · 2 comments
- Oct 12, 2026Documentation Link Check Failed - 2026-10-12 — gitrajav/maxtext0 reactions
- Oct 10, 2026recipes: add USE_BATCHED_RPA_LONG_CTX_KERNEL switch (default true) -> attention=vllm_batched_rpa_long_ctx — google/tunix0 reactions · 2 comments
- Oct 8, 2026feat(multipod): Add DAG `maxtext_distillation` with Cluster Toolkit — GoogleCloudPlatform/ml-auto-solutions0 reactions
- Oct 7, 2026feat(multipod): Add DAG `maxtext_distillation` with Cluster Toolkit — CIeNET-International/ml-auto-solutions-30 reactions · 1 comment
- Oct 7, 2026 feat(multipod): add `maxtext_distillation` DAG with Cluster Toolkit — GoogleCloudPlatform/ml-auto-solutions0 reactions
- Oct 5, 2026Documentation Link Check Failed - 2026-10-05 — gitrajav/maxtext0 reactions
- Oct 3, 2026[Add] MaxText (AI-Hypercomputer/maxtext) — PyTorchKR/landscape0 reactions
- Oct 3, 20263. MaxText: run one small pinned configuration after lower-level checks — egesamuray/jax-rocm-systems-lab0 reactions
- Sep 28, 2026Documentation Link Check Failed - 2026-09-28 — gitrajav/maxtext0 reactions
- Sep 21, 2026Documentation Link Check Failed - 2026-09-21 — gitrajav/maxtext0 reactions
- Sep 21, 2026feat(multipod): Add test_scope param to `maxtext_e2e_tests` — GoogleCloudPlatform/ml-auto-solutions0 reactions
- Sep 21, 2026feat(multipod): Add test_scope param to `maxtext_e2e_tests` — CIeNET-International/ml-auto-solutions-30 reactions · 5 comments
- Sep 19, 2026[RL] Sever autodiff graph with jnp.where on masked/padded tokens in G… — google/tunix0 reactions
- Sep 17, 2026# Description — matrawybarte-lgtm/gpc0 reactions
- Sep 15, 2026fix(checkpointing, infra): orchestrator save interval, save-sync serialization, memory requests, and fail-fast — google/tunix0 reactions
- Sep 14, 2026Documentation Link Check Failed - 2026-09-14 — gitrajav/maxtext0 reactions
- Sep 7, 2026Documentation Link Check Failed - 2026-09-07 — gitrajav/maxtext0 reactions
- Aug 31, 2026Documentation Link Check Failed - 2026-08-31 — gitrajav/maxtext0 reactions
- Aug 24, 2026feat: support multimodal models and eager loading in checkpoint conversion — GoogleCloudPlatform/accelerated-platforms0 reactions
- Aug 24, 2026Documentation Link Check Failed - 2026-08-24 — gitrajav/maxtext0 reactions
- Aug 22, 2026feat: RLVllmSampler weight sync via Raiden, bound in-process in the EngineCore worker — vllm-project/tpu-inference0 reactions · 1 comment
- Aug 18, 2026Update MaxText E2E TPU DAG checkpoint paths for reduced step count — GoogleCloudPlatform/ml-auto-solutions0 reactions
- Aug 17, 2026Documentation Link Check Failed - 2026-08-17 — gitrajav/maxtext0 reactions
- Aug 10, 2026Documentation Link Check Failed - 2026-08-10 — gitrajav/maxtext0 reactions
- Jul 20, 2026Update maxtext_moe_tpu_e2e DAG: hf access token & refactor — GoogleCloudPlatform/ml-auto-solutions0 reactions
- Jul 17, 2026[Maxtext] [Tunix] New Weight Sync for Post-train, maxtext -> maxtext — google/tunix0 reactions
- Jul 16, 2026feat: Restrict DAG `maxtext_e2e_tests` to GitHub schedule events — GoogleCloudPlatform/ml-auto-solutions0 reactions
- Jul 16, 2026feat: Restrict DAG `maxtext_e2e_tests` to GitHub schedule events — CIeNET-International/ml-auto-solutions-30 reactions · 2 comments
- Jun 9, 2026add qwen3.5 35b to xlml tests — GoogleCloudPlatform/ml-auto-solutions0 reactions
- May 21, 2026Remove collect_stack_trace config from checkpointing test — GoogleCloudPlatform/ml-auto-solutions0 reactions
- Feb 24, 2026Experiment: cast pallas xent dW to bf16 (keep fp32 accum) and validate speed + numerics — marin-community/marin0 reactions · 2 comments
- Feb 20, 2026Add Qwen3-Next tests to MaxText_MoE DAG — GoogleCloudPlatform/ml-auto-solutions0 reactions
In this repository6 other files it gives its agents.
- AGENTS.mdAGENTS.md
- maxtext-goodputSkill
- maxtext-pr-uploadSkill
- maxtext-remat-estimatorSkill
- model-bringupSkill
- update-changelogSkill
The file
We split this skill into the rules it gives an agent
6 rules. About 0 are common, 0 are distinctive, and 6 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈0
Distinctive · estimate
This author's own choices. Worth a look.
6
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 91
2-D+ Weight Coverage: Every 2-D+ weight (>= 256 unstacked elements) must shard across at least one active axis on (data=1, fsdp=2, …
- Very specific: line 95
TPU
ragged_dotVJP Tail Masking: When sum(group_sizes) < M (partial local expert slots under EP/FSDP), explicitly mask non-local tail … - Very specific: line 102
Read upstream HuggingFace configuration_<family>.py and modeling_<family>.py plus live config.json and model.safetensors headers before …
- Very specific: line 116
Keep a single if __name__ == "__main__": absltest.main() entry point at EOF, and run pyink --pyink --pyink-indentation=2 --line-length=122 …
- Very specific: line 120
All-Leaf & Per-Expert Finite Non-Zero Gradients: Every trainable leaf is nnx.Param, and every leaf (including router and every individual …
- Very specific: line 125
Weight Sharding Coverage: Every 2-D+ weight (>= 256 unstacked elements, including non-divisible vocab_size guard) shards across (data=1, …
≈ “Common” is an estimate: at least 1 in 5 of the 408,460 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
MaxText M3 Model Bring-Up (src/maxtext/m3/)
Onboards a HuggingFace model family as a self-contained pure-NNX vertical slice in src/maxtext/m3/models/<family>/, verified end-to-end on CPU and TPU via pytest.
For the motivation and design rationale behind m3 (model garden layout, sharding as annotation, post-construction transforms, MoE runtime split), read src/maxtext/m3/DESIGN.md. Where it disagrees with the code or src/maxtext/m3/README.md, the code and README are the source of truth.
1. Vertical-Slice Isolation & M3 Architecture Rules
Allowed touch list:
src/maxtext/m3/models/<family>/:__init__.py— public exports (<Family>Config,<Family>Sharding,<Family>Model,create_<family>_model, helper and mapping exports)modeling_<family>.py— config, sharding rules, norms, attention, MLP/MoE, stacked decoder, model, losscheckpoint_mappings_<family>.py— declarative MaxText <-> HuggingFace parameter mapping (<FAMILY>_MAXTEXT_TO_HF_PARAM_MAPPING), tensor transform hooks (<FAMILY>_MAXTEXT_TO_HF_PARAM_HOOK_FN), and HF tensor shapes (<FAMILY>_HF_WEIGHTS_TO_SHAPE), plus lightweight table-driven in-memory weight helpers for unit tests (reusing the centralized conversion planner rather than a bespoke per-model CLI converter)utils_<family>.py—calculate_<family>_tflops_per_device(config, log=True)and optional model-related helpers such asconfigure_<family>_engine(engine)(MaxTextTrainingEngineaux_lossadapter)
src/maxtext/m3/models/__init__.py— lazy wrappers inMODEL_REGISTRY,MODEL_FLOPS_REGISTRY,MODEL_ENGINE_CONFIG_REGISTRY- Training Entrypoint Reuse (
src/maxtext/m3/train/loop.py): Text-only LLMs and MoEs reuse M3's dedicated training entrypointsrc/maxtext/m3/train/loop.py(train_loop/train_step) directly — do not add a specialized<family>_train.pytrainer. Only introduce a thin shim overloop.pywhen non-text/multimodal input or output modalities require model-specific data/step handling. - Centralized Checkpoint Conversion & Config Registration:
src/maxtext/configs/models/<model-name>.yml— setuse_m3_model: trueandparam_scan_axis: 0(omitting"model_type"som3.configs.configselectsBaseConfig, and keeping fields compatible withMaxTextConfigso bothpyconfig.initializeandm3.configs.config.initializeload cleanly)src/maxtext/configs/types.py&src/maxtext/utils/globals.py— register<model-name>inModelName(enforcinguse_m3_model=True) andHF_IDSsrc/maxtext/checkpoint_conversion/utils/{param_mapping.py,hf_shape.py,hf_model_configs.py}— wirecheckpoint_mappings_<family>intoPARAM_MAPPING,HOOK_FNS,HF_SHAPE, andHF_MODEL_CONFIGSsoto_maxtextandto_huggingfaceconvert checkpoints end-to-end
tests/unit/m3/<family>*_test.py— conformance,PerturbSpec, centralized checkpoint mapping/roundtrip, PyTorch parity, and TPU verification tests
Never modify legacy src/maxtext/layers/, src/maxtext/models/, or model_creation_utils.py. (Note: .agents/ is listed in .gitignore; stage new skill files with git add -f in OSS.)
Seven Load-Bearing NNX & maxtext_engine Invariants (src/maxtext/m3/README.md):
- Pure Flax NNX built-ins: Compose
nnx.Linear,nnx.Embed,nnx.RMSNorm,nnx.Param, andm3.core.rope.apply_ropedirectly. No Linen bridges, no sharedDecoder, no model-name branching. nnx.Paramis the sole trainable variable type: Othernnx.Variablesubclasses silently receive zero gradient inmaxtext_engine.- Never
sowor mutate non-Paramstate in__call__: Mutating non-Paramtreedef permanently drops the engine onto its slow path. Pass inferenceKVCacheexplicitly as an external PyTree argument; defaultreturn_aux: bool = Falsein__call__(returninglogitsform3/train/loop.pyand(logits, aux_dict)whenreturn_aux=True). - Path-transparent
scanandremat: Create decoder layers as a single stacked module viannx.vmap((num_layers, ...)leading axis on everynnx.Param). Unrolled (scan_layers=False) and scanned (scan_layers=True) execution MUST share the exact samennx.GraphDefand stacked parameter paths. Never store Pythonintself.layer_idx = ion scanned submodules (breaksnnx.splitgraphdef equality across layers). - Fold auxiliary losses into primary loss: Return
aux["moe_lb_loss"]whenreturn_aux=True, and wireutils_<family>.configure_<family>_engineintoMODEL_ENGINE_CONFIG_REGISTRYviaengine.with_loss_fn(..., has_aux=True)(keeptargets_segmentationstrictly on CE loss — never feed it into self-attentionattention_maskormoe_lb_loss). - Single shared
Mesh+nnx.eval_shape-safe eager sharding: Accept/validatequant_mode_str: str | None = Noneincreate_<family>_modelwithout forwarding it to<Family>Config. When not tracing (not isinstance(jnp.zeros(()), jax.core.Tracer)), construct insidewith jax.sharding.set_mesh(mesh), nnx.use_eager_sharding(True):; whenever tracing (nnx.eval_shapeorjax.jitinsidecreate_nnx_sharded_model/from_pretrained), construct insidewith nnx.use_eager_sharding(False):so abstract and jittednnx.Paramstates share identicaleager_shardingPyTree metadata. Setself.mesh = mesh(model.mesh is driver_mesh) and never store privateMeshobjects on child modules. - Zero post-init parameter constraints: Shard weights once at init via
kernel_metadata={"out_sharding": sharding(...)}. Inside__call__, callsharding.constrain(x, name, axes)on activations only — never callwith_sharding_constraint,reshard, ordevice_puton parameter-derived weight arrays.
Stacked Layer Construction & NamedSharding Placement Pattern:
forked_rngs = rngs.split(config.num_hidden_layers)
stacked = nnx.vmap(lambda r: FamilyDecoderLayer(config, sharding=sharding, rngs=r), in_axes=0, out_axes=0)(forked_rngs)
graphdef, state = nnx.split(stacked)
def _place_stacked(path, var):
if not isinstance(var, nnx.Variable):
return var
orig = var.get_metadata("out_sharding", None)
orig_spec = orig.spec if isinstance(orig, jax.sharding.NamedSharding) else orig
new_spec = jax.sharding.PartitionSpec(None, *orig_spec)
raw_val = var.get_raw_value()
if mesh is not None and not mesh.empty and not isinstance(raw_val, jax.core.Tracer):
return var.replace(jax.device_put(raw_val, jax.sharding.NamedSharding(mesh, new_spec)), out_sharding=new_spec)
return var.replace(raw_val, out_sharding=new_spec)
layers = nnx.merge(graphdef, jax.tree_util.tree_map_with_path(_place_stacked, state, is_leaf=lambda x: isinstance(x, nnx.Variable)))At forward time, split graphdef, params, non_params = nnx.split(self.layers, nnx.Param, ...), optionally wrap the per-layer body in jax.checkpoint(..., policy=...), and run jax.lax.scan when scan_layers=True or a Python loop slicing axis 0 when scan_layers=False.
2. 4-Axis Logical Sharding, MoE Dispatch & Lazy Registries
Subclass maxtext.m3.core.sharding.Sharding over MESH_AXIS_NAMES = ("data", "fsdp", "tensor", "expert"):
class FamilySharding(Sharding):
def __init__(self, vocab_size: int = 0, num_experts: int = 1, tp_size: int = 1, fsdp_size: int = 1, ep_size: int = 1):
self.vocab_tp = (vocab_size > 0 and vocab_size % tp_size == 0)
self.compound_ep = (num_experts % (fsdp_size * ep_size) == 0)
def map_axis(self, axis: str, tensor_name: str, tensor_type: TensorType) -> MeshAxes:
match axis, tensor_type:
case "batch", TensorType.ACTIVATION:
return ("data", "fsdp", "expert")
case "embed", TensorType.WEIGHT:
return ("fsdp", "expert")
case "experts", TensorType.WEIGHT:
return ("fsdp", "expert") if self.compound_ep else "expert"
case "embed_exp", TensorType.WEIGHT:
return None if self.compound_ep else "fsdp"
case ("heads" | "kv_heads" | "mlp"), _:
return "tensor"
case "vocab", _:
return "tensor" if self.vocab_tp else None
case ("length" | "embed" | "head_dim" | "norm"), _:
return None
case _:
raise KeyError(f"Unknown logical axis {axis!r} on {tensor_name!r}")- Non-divisible
vocab_sizeguard: Odd vocabularies (e.g.,49155) leave"vocab"replicated (None) whenvocab_size % tp_size != 0while still shardingembed_tokens(V, H)along"embed"(("fsdp", "expert")). - 2-D+ Weight Coverage: Every 2-D+ weight (
>= 256unstacked elements) must shard across at least one active axis on(data=1, fsdp=2, tensor=2, expert=1)(store router kernel as(hidden_size, num_experts)on("embed", None)). - MoE Layout & Zero-All-Gather Dispatch (
FSDP >= 1, TP >= 1, EP >= 1):- Store
gate_up_projas 4-D(E, H, 2, I)(("experts", "embed_exp", None, "mlp")) so gate[:, :, 0, :]and up[:, :, 1, :]slice the replicated size-2 axis; storedown_projas 3-D(E, I, H)(("experts", "mlp", "embed_exp")). - When
compound_epholds andfsdp * expert > 1(ortensor > 1), dispatch insidejax.shard_map(..., check_vma=False)with exact parameterPartitionSpecs: keep axis tuple order("fsdp", "expert")identical acrossP(("fsdp", "expert"), ...)weights,lax.axis_index(("fsdp", "expert"))(f_idx * ep_size + e_idx),lax.all_gather(..., ("fsdp", "expert"), axis=0, tiled=True), andlax.psum_scatter(..., ("fsdp", "expert"), scatter_dimension=0, tiled=True)(pluslax.psumover"tensor"). When token countTis not divisible byfsdp * expert(e.g.,B=1KV-cache decode), fall back activationin_specs/out_specstoP(None, None)+lax.psum(..., ("tensor", "fsdp", "expert"))while keeping expert weights sharded. - TPU
ragged_dotVJP Tail Masking: Whensum(group_sizes) < M(partial local expert slots under EP/FSDP), explicitly mask non-local tail rows[sum(group_sizes):M]to0onsorted_x, SwiGLUact, andsorted_outviajnp.where(sorted_valid, ..., 0)— TPU XLA'sragged-dotlhs VJP does not zero rows pastsum(group_sizes).
- Store
- Lazy Registries & Consolidated Model Helpers (
src/maxtext/m3/models/__init__.py,utils_<family>.py):- In
MODEL_REGISTRY, validateif rngs is None: raise ValueError(...)and import<family>modules lazily inside wrapper functions. - In
utils_<family>.py, consolidatecalculate_<family>_tflops_per_device(config, log=True) -> (total, weight, attn)(B = per_device_batch_size,3 * [2*B*S*(L*attn_params + L*H*E + L*k*3*H*I + H*V)] / 1e12weight +3 * [L * 2*B*S^2*H_q*D] / 1e12causal attention, timesgradient_accumulation_steps, verified within< 0.5%of analytical FLOPs) alongsideconfigure_<family>_engine(engine), which callsengine.with_loss_fn(<family>_engine_loss_fn, has_aux=True)andengine.with_gen_model_input_fn(None)(never mutatingengine._loss_fndirectly) and returns(WeightedMetric(unreduced_sum=(total_loss * total_weights).astype(jnp.float32), denominator=total_weights), aux).
- In
3. Source Audit, 8-Check Conformance & PerturbSpec Negative Controls
Read upstream HuggingFace configuration_<family>.py and modeling_<family>.py plus live config.json and model.safetensors headers before coding:
| Common Model Pitfall | Verification Rule |
| Non-Llama scalar multipliers | Audit embedding_multiplier, attention_multiplier (replaces 1/sqrt(head_dim)), residual_multiplier (both sublayers), and output logits / logits_scaling. |
Tied lm_head with scaled embeddings | Project final norm output with raw unscaled embed_tokens.embedding[...] (h @ W.T), never pre-multiplied by embedding_multiplier. |
| Router & top-$k$ precision | Compute router_logits in fp32 (Precision.HIGHEST); check whether softmax applies over top-$k$ logits only or full expert logits. |
Switch aux_loss normalization | Check whether tokens_per_expert divides by num_tokens ($\sum_e f_e = k$, uniform loss $= k$) or num_tokens * k, and binarize (attention_mask != 0). |
| Square-matrix transpose trap | In synthetic tests, enforce 2 * intermediate_size != hidden_size (e.g., H=64, I=48) and override router_aux_loss_coef > 0 when testing router aux_loss. |
Static Test Hygiene:
- Guard
import torch/import transformerswithHAS_TORCHand@unittest.skipUnless(HAS_TORCH, ...)sopytest --collect-onlyworks withouttorch. - Mark TPU-hardware test modules (
*_tpu_parity_test.py) withpytestmark = pytest.mark.tpu_only(guarded bytry: import pytest) —tests/conftest.pyauto-marks unmarked tests ascpu_onlyand skips them on active TPU/GPU runners. - Pass
is_leaf=lambda x: isinstance(x, nnx.Variable)to alljax.tree_utilcalls over NNX state dicts (nnx.Variableis a registered PyTree node in Flax >= 0.12). - Keep a single
if __name__ == "__main__": absltest.main()entry point at EOF, and runpyink --pyink --pyink-indentation=2 --line-length=122+pylint --rcfile=pylintrc(10.00/10) before uploading.
Mandatory 8 M3 Conformance Checks + 2 Bring-Up Gates (tests/unit/m3/<family>_test.py / conformance_spec.py):
scanEquivalence & Path Identity: Identical parameter paths/shapes and forward outputs (rtol=1e-5) acrossscan_layers=Trueandscan_layers=False;rngs=Noneraises(TypeError, ValueError).- All-Leaf & Per-Expert Finite Non-Zero Gradients: Every trainable leaf is
nnx.Param, and every leaf (including router and every individual routed expert slice) receives a finite, non-zero gradient undernnx.value_and_grad. rematEquivalence & State Stability: All(scan_layers, remat_policy)combinations match forward loss and per-leaf gradients; non-Paramstate treedef/leaves remain identical and finite before and after__call__(zerosow/nnx.Intermediate).aux_lossLive, Masked & Gradient-Connected:aux["moe_lb_loss"] > 0, masksattention_mask == 0/segment_ids == 0padding tokens (keeping SFTtargets_segmentationstrictly on CE loss), and alters router gradients whenrouter_aux_loss_coef > 0viaMODEL_ENGINE_CONFIG_REGISTRYwith_loss_fn(..., has_aux=True).- Driver
MeshIdentity & Canonical Axis Names:model.mesh is driver_mesh, zero privateMeshobjects on child modules, and everyNamedSharding/PartitionSpeconnnx.Variablemetadata andjax.Arrayleaves referencesdriver_meshandMESH_AXIS_NAMES = ("data", "fsdp", "tensor", "expert"). - Zero Post-Init Parameter Sharding Constraints: Jaxpr parameter-taint walk across unary transforms,
scan,remat, andshard_mapconfirming zerosharding_constraint,reshard, ordevice_putops on parameter-derived arrays in__call__. - Weight Sharding Coverage: Every 2-D+ weight (
>= 256unstacked elements, including non-divisiblevocab_sizeguard) shards across(data=1, fsdp=2, tensor=2, expert=1)with addressable shard smaller than global shape, exercising both"fsdp"and"tensor". - Compiled StableHLO Zero Expert
all-gather& Compound Mesh Parity: Lower and compile a sharded train step across 4-device(1, 2, 2, 1),(1, 2, 1, 2),(1, 1, 2, 2)AND 8-device(1, 2, 2, 2)(FSDP=2, TP=2, EP=2all> 1), verifyingfp32forward/grad parity vs(1, 1, 1, 1)and zeroall-gather(?:-start|-done)?ops producing full, unstacked, scanned-singleton, or TP-sliced expert weight shapes incompiled.as_text(). - Extra Gate — Autoregressive KV-Cache Equivalence: Prefill + step-by-step
KVCachedecode matches full causal forward logits (max_abs_diff <= 1e-5infp32), respectingsegment_ids(!= 0padding guard) andattention_mask. - Extra Gate — Centralized HF <-> Orbax Checkpoint Roundtrip & Torch-Free Mini-Twin Golden: 100% bijection between
PARAM_MAPPING/HOOK_FNS/HF_SHAPE(checkpoint_mappings_<family>.py) andnnx.eval_shapeabstract model leaves acrossscan_layers=Trueandscan_layers=False, losslessto_maxtext<->to_huggingface(process_maxtext_param) tensor roundtrip (max_abs_diff == 0), plus a committed torch-free mini-twin golden so forward/backward parity andPerturbSpecnegative controls run in CPU PR CI without PyTorch.
PerturbSpec Negative Controls (REL_NORM_BAND = (5e-3, 2e-2)):
@dataclass(frozen=True)
class PerturbSpec:
name: str
apply: Callable[[FamilyModel], None] # mutates cloned model weight or config scalarPerturb every custom scalar (embedding_multiplier, attention_multiplier, residual_multiplier, logits_scaling) and critical weight leaf (router kernel, gate_up_proj scaled into relative L2 norm band 5e-3..2e-2), asserting that parity assertions raise AssertionError on every perturbation. Align MaxText pre-shifted (inputs=x[:, :-1], targets=x[:, 1:]) against HF internal (logits[:, :-1], labels[:, 1:]) in loss parity checks.
4. Real-Weight /dev/shm Conversion, FrozenTopK Parity & Sharded Training
Execute real-weight TPU verification under /dev/shm/<user>_m3_poc/ (passing cache_dir explicitly without mutating global HF_HOME or jax_default_matmul_precision at import time; pin revision= in snapshot_download and scope jax_default_matmul_precision="highest" inside setUpClass/tearDownClass):
- Full Checkpoint Audit (
to_maxtext/from_pretrained/to_huggingface): Convert full HF safetensors to Orbax via centralizedmaxtext.checkpoint_conversion.to_maxtext, restore onto sharded M3 meshes viamodel_creation_utils.from_pretrained, and roundtrip back throughprocess_maxtext_param(to_huggingface); assert100%of HF keys consumed,100%of NNXParamleaves populated with exact shapes, andmax_abs_diff == 0.0. - Zero-Gen
FrozenTopKRouted-MoE Parity: Tinyfp32reduction differences can flip boundary-ULP router ties in deep MoEs. Verify:# Inside router __call__(x, frozen_topk_indices=None): top_k_indices = frozen_topk_indices if frozen_topk_indices is not None else jax.lax.top_k(router_logits, self.top_k)[1] top_k_logits = jnp.take_along_axis(router_logits, top_k_indices, axis=-1) top_k_weights = jax.nn.softmax(top_k_logits, axis=-1)- Teacher-forced (
FrozenTopK) + negative control: Inject HF's per-layertop_k_indices((num_layers, B, S, k)) into M3 while computingtop_k_logitsfrom M3's ownrouter_logits, assert E2EKL(P_hf || P_m3) <= 1e-5, and verify a negative control perturbingfrozen_topk_indicesfails the KL gate. - Teacher-forced router agreement + greedy decode: Measure router agreement on pre-override
frozen_out.router_logits, requiring zero flips on tokens whose reference marginsorted_logits[..., k-1] - sorted_logits[..., k] >= 8 * max(spacing(|logit|), finfo(float32).eps)(keep unforced rollout KL as a diagnostic), and verify multi-token greedy decode exact token-ID match vshf_model.generate(..., do_sample=False).
- Teacher-forced (
- Multi-Device Sharded Training Verification (
src/maxtext/m3/train/loop.py): Run>= 5sharded training steps on TPU (FSDP+EP/TP) viamaxtext.m3.train.loop(train_step/train_loop) and verifyutils_<family>engine loss (router_aux_loss_coef > 0), confirming finite non-zero grad norms, live non-zeroaux_loss, strictly decreasing loss, and zero OOM/NaN.
5. Standard Verification Commands
- Torch-free collection smoke check:
pytest --collect-only tests/unit/m3/<family>_test.py - CPU 8-device unit + conformance + HLO suite:
JAX_PLATFORMS=cpu XLA_FLAGS="--xla_force_host_platform_device_count=8" pytest -v tests/unit/m3/<family>_test.py - TPU VM real-weight parity + unit suite:
pytest -v tests/unit/m3/<family>_tpu_parity_test.py && pytest --noconftest -v tests/unit/m3/<family>_test.py
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

