Repository navigation
Route Muon by a declared muon_exempt marker, and let packed experts take Muon per expert - #781
Conversation
Codecov Report✅ All modified and coverable lines are covered by tests.
🚀 New features to boost your workflow:
|
amazloumi
left a comment
There was a problem hiding this comment.
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.
|
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
left a comment
There was a problem hiding this comment.
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.
Summary
#471: models declare which parameters Muon leaves to AdamW.
_muon_matricesno longer checks classes. It reads amuon_exemptattribute 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 unlessoptimizer.muon_router, andNoneexempts nothing. Any other value fails the optimizer build with aValueErrornaming the module.OutputHeadsets"always";SoftmaxTopKRouter,SigmoidTopKRouterandExpertChoiceSigmoidRouterset"router". A custom block that reuses an in-tree router needs nothing, and a custom model marks its own head (for exampleself.head.muon_exempt = "always"on a plainnn.Linear).MoEMLPgives 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 unlessmuon_router). A router that declares its own value keeps it._build_muonlogs 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 thetorch.compileand 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.
optimizer.muon_packed_experts(defaulttrue). When it is on, theup_w,down_wandgate_wof every packedMoEMLPgo to Muon in param groups markedbatched, placed after the other Muon groups.Muon.stepruns Newton-Schulz on each expert's(in, out)slice and takes the update scale for theout x innn.Linearweight 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 undermuon_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.Shard(0)(noshard_placement_fnanywhere), expert parallelism slices whole experts (apply_expert_parallel), and tensor parallelism givesMoEMLPno 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 aRuntimeError, a layout that splits a slice (none exists today;holds_whole_matriceschecks it).true, as decided in review, so packed experts train under Muon as unpacked ones do andmoe_packed_expertsno longer changes the optimizer of most of an MoE model's parameters.muon_packed_experts = falsekeeps 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 namesoptimizer.muon_packed_expertsamong the causes and says that a packed-MoE Muon checkpoint saved before the option existed resumes as it was saved withoptimizer.muon_packed_experts = false, or continues from its weights with a fresh optimizer.Behavior change
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, namingoptimizer.muon_packed_experts; setmuon_packed_experts = falseto resume it unchanged, or continue from its weights with a fresh optimizer (checkpoint.load_pathandcheckpoint.exclude_from_loading = ["optimizer"]).configs/andexamples/combines Muon with packed experts: the two Muon configs (configs/train/7b_16gpu_muon.tomland the image-understanding stage-2 config) are dense, and no shipped TOML setsmoe_packed_experts = true. Thebenchmarks/moe_packedscripts 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
muon_exemptnow goes to AdamW where it went to Muon, and so does the gate of an in-tree router used outsideMoEMLPandExpertChoiceMoE(for example in the model's own MoE block) unlessoptimizer.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.muon_exemptother than"always","router"orNonefails the optimizer build.optimizer.muon_packed_expertsmoves 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
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 theadd-optimizerskill, andcodebase-map.json(also adds the missingtraining/orthogonalize.pyandtests/unit/test_orthogonalize.pyentries).Testing
uv run ruff check .passesuv run ruff format --check .passesuv run pyright kempnerforge/passes (0 errors)uv run pytest tests/unit/ -v --timeout=60passes, 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,CXXset to gcc-toolset-15's g++), 6699 passed, 41 failed and 14 skipped. 38 of the failures are tests that loadgpt2from the node's Hugging Face cache offline, whose files a scratch purge removed (test_vlm_dataset.py35,test_video_dataset.py3); they fail on main the same way. The other 3 (test_hooks.py2,test_convert_checkpoint.py1) are the node'sOSError: [Errno 39] Directory not emptywhen 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) orRUN_HF_TESTS=1with network access (1)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 intests/unit/test_orthogonalize.py, and expert parallelism (ep=2, and dp_shard=2 x ep=2) intests/unit/test_ep_gradients.py)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:
nn.Linearhead marked"always"goes to Muon (assert model.head.weight in adam), an in-tree router's gate in a custom block goes to Muon withmuon_router = false(all three routers),MoEMLPignores a router's ownmuon_exempt(both directions), an unknownmuon_exemptis not refused (DID NOT RAISE), there is no debug list (for a plain, a compiled and an activation-checkpointed model), and no_name_patternsfor 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 withmuon_router = true, and an undeclared router insideMoEMLP).test_orthogonalize.pyfail to importholds_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 nomuon_packed_experts(17 cases,TypeErrororAttributeError, 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_routernow also checks that the output head stays on AdamW; it passes on main, which keeps the head there too.OptimizerConfig().muon_packed_expertsisFalsethere), 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 nomuon_packed_experts = falseguidance). The cases that set the flag pass there.if True:. With--cov --cov-branchover the Muon test files,kempnerforge/training/optimizer.pylisted811->819as a partial branch before the test (ebb0028) and lists no line of this patch after it (55f2ad2).muon_adjust_lr.optimizer.muon_packed_experts = false; with that setting it resumes, and three more steps match main's uninterrupted run exactly."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_matricesaccepting 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 (underlr_multipliers), and packed experts inside an"always"module offered to Muon; and for the marker, an in-tree router orOutputHeadwithout it,OutputHeadmarked"router", the attribute read from the class only,MoEMLPnot marking an undeclared router or overwriting a router's own value,muon_routerignored, the debug names keeping thetorch.compileor activation-checkpointing wrapper, and the names computed above debug level.Also run: Sphinx
-W(clean),codebase-map.jsoncounts (only main's known mismatches,test_moe.pyandtest_dataloader_iter.py), andgit merge-treefrom 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 incodebase-map.json, and this branch adds one more conflict there: thetests/unit/test_config.pycount (174 here, 211 there), which resolves to 212. Main bdaf4a4 is merged in; its one conflict, thetests/unit/test_checkpoint.pycount incodebase-map.json, resolved to 384 (main's 381 plus this branch's threeTestMuonResumecases), and this round's new case makes it 385.Contribution terms
Closes #471
Closes #470