Skip to content

Route Muon by a declared muon_exempt marker, and let packed experts take Muon per expert - #781

Merged
amazloumi merged 12 commits into
mainfrom
fix/muon-declared-routing-and-packed-experts
Dec 6, 2026
Merged

amazloumi merged 12 commits into
mainfrom
fix/muon-declared-routing-and-packed-experts

Conversation

@Naeemkh

@Naeemkh Naeemkh commented Dec 5, 2026 •

Copy link
Copy Markdown
Member

Summary

#471: models declare which parameters Muon leaves to AdamW.

  • _muon_matrices no longer checks classes. It reads a muon_exempt attribute from each module, on its class or set on the module itself: "always" leaves every parameter of the module (submodules included) to the AdamW fallback, "router" does so unless optimizer.muon_router, and None exempts nothing. Any other value fails the optimizer build with a ValueError naming the module.
  • OutputHead sets "always"; SoftmaxTopKRouter, SigmoidTopKRouter and ExpertChoiceSigmoidRouter set "router". A custom block that reuses an in-tree router needs nothing, and a custom model marks its own head (for example self.head.muon_exempt = "always" on a plain nn.Linear).
  • MoEMLP gives its router "router" when the router sets nothing, so a router registered under the "router" category keeps the routing it had before (gate on AdamW unless muon_router). A router that declares its own value keeps it.
  • _build_muon logs at debug level the names it orthogonalizes, each index as * with a count per name (layers.*.attention.q_proj.weight (32), ...), so a wrong split is visible without a line of thousands of names. The names leave out the torch.compile and activation-checkpointing wrappers, as checkpoint names do. KempnerForge's logger prints debug records on rank 0; above debug level the build computes no names.

#470: packed MoE experts take Muon, one expert at a time.

  • New optimizer.muon_packed_experts (default true). When it is on, the up_w, down_w and gate_w of every packed MoEMLP go to Muon in param groups marked batched, placed after the other Muon groups. Muon.step runs Newton-Schulz on each expert's (in, out) slice and takes the update scale for the out x in nn.Linear weight the slice stands for (shape[2] x shape[1]). From the same seed, packed and unpacked experts then take the same steps, up to rounding, on one process and under muon_orthogonalize = "exact". Under FSDP2 with the default "local" they do not: FSDP2 shards an unpacked expert's weight by rows and Newton-Schulz runs on each rank's rows, while a packed slice is orthogonalized whole, so the packed experts step as on one process and the unpacked ones do not.
  • FSDP2 shards the packed weights with Shard(0) (no shard_placement_fn anywhere), expert parallelism slices whole experts (apply_expert_parallel), and tensor parallelism gives MoEMLP no plan (_build_mlp_tp_plan), so every rank holds whole experts. "local" and "exact" therefore give the same full-matrix update without a gather; "exact" refuses, with a RuntimeError, a layout that splits a slice (none exists today; holds_whole_matrices checks it).
  • The default is true, as decided in review, so packed experts train under Muon as unpacked ones do and moe_packed_experts no longer changes the optimizer of most of an MoE model's parameters. muon_packed_experts = false keeps the packed weights on the AdamW fallback, as before this PR. A resume across a change is refused by the existing "another optimizer's state" check, whose message names optimizer.muon_packed_experts among the causes and says that a packed-MoE Muon checkpoint saved before the option existed resumes as it was saved with optimizer.muon_packed_experts = false, or continues from its weights with a fresh optimizer.
  • With the flag off, the build logs one info line saying how many params of packed expert weights Muon leaves to AdamW and which flag gives them to Muon.

Behavior change

  • Runs that combine Muon with packed experts (model.moe_packed_experts = true) now orthogonalize the experts per expert by default, where they trained on Muon's AdamW fallback before. A Muon checkpoint of such a model saved before this change is refused on resume, naming optimizer.muon_packed_experts; set muon_packed_experts = false to resume it unchanged, or continue from its weights with a fresh optimizer (checkpoint.load_path and checkpoint.exclude_from_loading = ["optimizer"]).
  • No shipped config is affected. None of the 41 TOML files under configs/ and examples/ combines Muon with packed experts: the two Muon configs (configs/train/7b_16gpu_muon.toml and the image-understanding stage-2 config) are dense, and no shipped TOML sets moe_packed_experts = true. The benchmarks/moe_packed scripts that do set it train with AdamW, and the notebooks and e2e tests run no Muon on packed experts.

Other behavior changes a user will notice

  • In-tree models route as before, apart from packed experts under Muon (above). In a custom model, a module that sets muon_exempt now goes to AdamW where it went to Muon, and so does the gate of an in-tree router used outside MoEMLP and ExpertChoiceMoE (for example in the model's own MoE block) unless optimizer.muon_router = true. A Muon checkpoint of such a model saved before this change is refused on resume, naming those parameters; continue from its weights with a fresh optimizer.
  • A muon_exempt other than "always", "router" or None fails the optimizer build.
  • A Muon build prints one more debug line (rank 0), and with packed experts and the flag off, one more info line.
  • Changing optimizer.muon_packed_experts moves every packed expert weight to the other optimizer; a resume across a change is refused and needs the setting the checkpoint was saved with, or the weights-only warm start.

Known limitations

  • Newton-Schulz runs once per expert in a Python loop, as it already does for unpacked experts. Batching it into one batched matmul would cut kernel launches, but its rounding could then differ from one process's.

Docs: training/optimizers.md (routing list and a new "Packed experts" subsection, which also says when packed and unpacked experts take the same steps), configuration/config-sections.md (new row), how-to/build-a-model.md (new "Mark what Muon leaves to AdamW" section), how-to/compare-optimizers.md, moe/capacity-and-dispatch.md, how-to/moe-experiments.md, checkpointing/dcp-model.md (what the inner AdamW holds, and the resume refusal, including a checkpoint saved before the option existed), the optimizer field list of the add-optimizer skill, and codebase-map.json (also adds the missing training/orthogonalize.py and tests/unit/test_orthogonalize.py entries).

Testing

  • uv run ruff check . passes
  • uv run ruff format --check . passes
  • uv run pyright kempnerforge/ passes (0 errors)
  • uv run pytest tests/unit/ -v --timeout=60 passes, apart from failures of the CPU batch node that main shares: at e7b71b0, in one CPU-only batch job on the Kempner cluster (GPUs hidden, Python 3.14.2, torch 2.14.1, CXX set to gcc-toolset-15's g++), 6699 passed, 41 failed and 14 skipped. 38 of the failures are tests that load gpt2 from the node's Hugging Face cache offline, whose files a scratch purge removed (test_vlm_dataset.py 35, test_video_dataset.py 3); they fail on main the same way. The other 3 (test_hooks.py 2, test_convert_checkpoint.py 1) are the node's OSError: [Errno 39] Directory not empty when a temporary directory on its network scratch is removed; each file passes when rerun alone (43 and 143 passed). The 14 skips match the count at 506fb67, where they needed CUDA (13) or RUN_HF_TESTS=1 with network access (1)
  • If distributed code changed: uv run torchrun --nproc_per_node=4 -m pytest tests/distributed/ -v (not run: no GPUs here; FSDP2 with packed experts is covered on two gloo CPU ranks in tests/unit/test_orthogonalize.py, and expert parallelism (ep=2, and dp_shard=2 x ep=2) in tests/unit/test_ep_gradients.py)
  • If training loop / parallelism / optimizers changed: uv run pytest tests/e2e/ --e2e -v (not run: needs GPUs; no e2e test runs Muon on packed experts)

Failing first, with main's code (bdaf4a4) and these tests:

  • Let models declare which parameters Muon leaves to AdamW #471: 12 of the 17 new cases fail. A plain nn.Linear head marked "always" goes to Muon (assert model.head.weight in adam), an in-tree router's gate in a custom block goes to Muon with muon_router = false (all three routers), MoEMLP ignores a router's own muon_exempt (both directions), an unknown muon_exempt is not refused (DID NOT RAISE), there is no debug list (for a plain, a compiled and an activation-checkpointed model), and no _name_patterns for the test of a build above debug level to watch (AttributeError). The 5 that pass on main pin today's routing (the gate on Muon with muon_router = true, and an undeclared router inside MoEMLP).
  • Muon gives packed MoE experts to AdamW, unpacked ones to Newton-Schulz #470: of the 31 new cases, the 4 in test_orthogonalize.py fail to import holds_whole_matrices, and the other 27 all fail: main steps a batched group as one flattened matrix (8 cases, Tensor-likes are not close, every element), does not refuse a 2-D weight in it (DID NOT RAISE), has no muon_packed_experts (17 cases, TypeError or AttributeError, the 3 expert-parallel ones included), and in the default case leaves the packed experts on AdamW, where the test now expects them on Muon.
  • test_moe_router_gate_follows_muon_router now also checks that the output head stays on AdamW; it passes on main, which keeps the head there too.
  • With the PR's previous head (506fb67) and this round's tests, 4 cases fail: the new default test (OptimizerConfig().muon_packed_experts is False there), the default routing case (packed experts on AdamW), and both flipped-resume cases (a checkpoint saved with the packed experts on AdamW resumes under the old default, DID NOT RAISE, and the refusal has no muon_packed_experts = false guidance). The cases that set the flag pass there.
  • The new test of a build above debug level passes with the code as it was, since the guard predates it, and fails with the guard replaced by if True:. With --cov --cov-branch over the Muon test files, kempnerforge/training/optimizer.py listed 811->819 as a partial branch before the test (ebb0028) and lists no line of this patch after it (55f2ad2).
  • A probe of two Muon steps on the same experts, packed and unpacked, on one process: on main they end 5.4e-2 to 5.8e-2 apart (the packed ones take AdamW); with the flag on, 1.1e-7 to 1.9e-7 for every muon_adjust_lr.
  • A probe of a packed-MoE Muon checkpoint saved by main's code (bdaf4a4) and resumed at e7b71b0: with the default, the load is refused, naming the six packed weights and optimizer.muon_packed_experts = false; with that setting it resumes, and three more steps match main's uninterrupted run exactly.
  • A probe of two Muon steps under two-rank FSDP2 (gloo, CPU) against one process: packed experts match exactly under "local" and "exact"; unpacked experts match exactly under "exact" and differ under "local" by 35 to 66 percent of the step (Frobenius norm of the difference over that of the step).

Mutations, each caught by at least one test: the per-expert scale taken as in x out, batched groups stepped as flattened matrices (also under expert parallelism), the flag ignored, the groups left unmarked, the batched groups placed first, the "exact" refusal removed, holds_whole_matrices accepting any layout, judging mesh dims of size one, or refusing a split along the first dim, batched groups built without their source group's module and rate (under lr_multipliers), and packed experts inside an "always" module offered to Muon; and for the marker, an in-tree router or OutputHead without it, OutputHead marked "router", the attribute read from the class only, MoEMLP not marking an undeclared router or overwriting a router's own value, muon_router ignored, the debug names keeping the torch.compile or activation-checkpointing wrapper, and the names computed above debug level.

Also run: Sphinx -W (clean), codebase-map.json counts (only main's known mismatches, test_moe.py and test_dataloader_iter.py), and git merge-tree from e7b71b0: clean with main, #709, #787 and #789. #648, #776 and #784 conflict with main itself, in the same files, and this branch adds nothing to those conflicts. #788 conflicts with main in codebase-map.json, and this branch adds one more conflict there: the tests/unit/test_config.py count (174 here, 211 there), which resolves to 212. Main bdaf4a4 is merged in; its one conflict, the tests/unit/test_checkpoint.py count in codebase-map.json, resolved to 384 (main's 381 plus this branch's three TestMuonResume cases), and this round's new case makes it 385.

Contribution terms

Closes #471
Closes #470

@Naeemkh Naeemkh added the core Affecting core label Dec 5, 2026
@amazloumi
amazloumi self-requested a review December 5, 2026 20:59
@codecov

codecov Bot commented Dec 5, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

Files with missing lines Coverage Δ
kempnerforge/checkpoint/manager.py 99.17% <ø> (ø)
kempnerforge/config/optimizer.py 96.82% <100.00%> (+0.05%) ⬆️
kempnerforge/model/embedding.py 100.00% <100.00%> (ø)
kempnerforge/model/moe.py 100.00% <100.00%> (ø)
kempnerforge/model/moma.py 96.89% <100.00%> (+0.02%) ⬆️
kempnerforge/model/router.py 98.17% <100.00%> (+0.02%) ⬆️
kempnerforge/training/optimizer.py 97.41% <100.00%> (+0.28%) ⬆️
kempnerforge/training/orthogonalize.py 95.34% <100.00%> (+2.75%) ⬆️
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@amazloumi amazloumi left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Request changes. The debug-log condition at kempnerforge/training/optimizer.py:811 leaves one partial branch in the patch, so Codecov is not fully green; the routing, the per-expert Muon step and the checkpoint behavior otherwise checked out.

Comment thread kempnerforge/training/optimizer.py Resolved
Comment thread docs/training/optimizers.md Resolved
@Naeemkh

Naeemkh commented Dec 6, 2026

Copy link
Copy Markdown
Member Author

As agreed, muon_packed_experts is now on by default (ebb0028). A packed-MoE Muon checkpoint saved before this option existed holds AdamW state for the experts, so resuming it under the new default is refused with a message that says to set optimizer.muon_packed_experts = false, or to warm start. No shipped config combines Muon with packed experts.

@amazloumi amazloumi left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approve. Both earlier points are fixed, and with muon_packed_experts on by default a packed-MoE Muon checkpoint saved on main is refused with clear guidance and resumes exactly with the flag set to false.

@amazloumi
amazloumi merged commit d4e9b7c into main Dec 6, 2026
15 checks passed
@amazloumi
amazloumi deleted the fix/muon-declared-routing-and-packed-experts branch December 6, 2026 06:23
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

core Affecting core

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Let models declare which parameters Muon leaves to AdamW Muon gives packed MoE experts to AdamW, unpacked ones to Newton-Schulz

2 participants