diff --git a/codebase-map.json b/codebase-map.json index 3a91fff46..1251c4662 100644 --- a/codebase-map.json +++ b/codebase-map.json @@ -96,7 +96,7 @@ "kempnerforge/config/optimizer.py": { "classes": { "OptimizerConfig": { - "purpose": "Optimizer settings (name, lr, betas, weight_decay, muon params, schedule_free_warmup_steps, weight_decay_scope, lr_multipliers per vlm.module_patterns module)" + "purpose": "Optimizer settings (name, lr, betas, weight_decay, muon params incl. muon_packed_experts (packed MoE expert weights to Muon, one expert at a time, by default; False keeps them on AdamW), schedule_free_warmup_steps, weight_decay_scope, lr_multipliers per vlm.module_patterns module)" } }, "functions": [ @@ -618,7 +618,7 @@ ] }, "OutputHead": { - "purpose": "Linear output projection (hidden -> vocab logits)", + "purpose": "Linear output projection (hidden -> vocab logits); muon_exempt = 'always' keeps its weight on Muon's AdamW fallback", "methods": [ "forward(x)", "tie_weights(embedding)" @@ -650,7 +650,7 @@ "kempnerforge/model/moe.py": { "classes": { "MoEMLP": { - "purpose": "Mixture-of-Experts feed-forward layer with router dispatch", + "purpose": "Mixture-of-Experts feed-forward layer with router dispatch; gives a router that sets no muon_exempt 'router'", "properties": [ "aux_loss", "expert_counts" @@ -689,7 +689,7 @@ "kempnerforge/model/router.py": { "classes": { "SoftmaxTopKRouter": { - "purpose": "Mixtral-style softmax top-k router with aux load-balancing loss", + "purpose": "Mixtral-style softmax top-k router with aux load-balancing loss; muon_exempt = 'router'", "properties": [ "aux_loss", "expert_counts" @@ -706,7 +706,7 @@ ] }, "SigmoidTopKRouter": { - "purpose": "DeepSeek-V3 style sigmoid router: expert_bias frozen to the optimizer (always_frozen), balanced once per optimizer step from pending_counts; adaptive scheduling, sequence aux loss", + "purpose": "DeepSeek-V3 style sigmoid router: expert_bias frozen to the optimizer (always_frozen), balanced once per optimizer step from pending_counts; adaptive scheduling, sequence aux loss; muon_exempt = 'router'", "properties": [ "aux_loss", "expert_counts", @@ -818,7 +818,7 @@ ] }, "Muon": { - "purpose": "Momentum with Orthogonalized Updates optimizer (Newton-Schulz)", + "purpose": "Momentum with Orthogonalized Updates optimizer (Newton-Schulz); a param group marked batched holds 3-D (E, in, out) stacks, orthogonalized one (in, out) slice at a time and scaled as the out x in Linear weight, with no gather under exact, which refuses a layout that splits a slice", "methods": [ "step(closure)", "state_dict()", @@ -833,9 +833,14 @@ "_split_by_module(model, param_groups, config, module_patterns) -> list[dict]", "_module_owners(model, modules, module_patterns) -> (owners, enclosing) (over every parameter name; a parameter several listed modules match goes to the one whose matches the others strictly contain; identical or partly overlapping matches are refused)", "_newton_schulz(G, steps) -> Tensor", - "_muon_matrices(model, *, routers) -> set[Tensor]", + "_orthogonalize_slices(stack, newton_schulz) -> Tensor (Newton-Schulz of each matrix of a 3-D stack)", + "_muon_matrices(model, *, routers) -> (set[Tensor], set[Tensor]) (the nn.Linear weights, and the packed expert weights of every packed MoEMLP, which optimizer.muon_packed_experts gives Muon in batched groups; both less every parameter of a module whose muon_exempt is 'always', or 'router' unless routers; refuses other values)", + "_name_patterns(model, params) -> str (the names without the activation-checkpoint and torch.compile wrappers, each index as *, and each pattern's count; Muon's build logs them at debug level)", "_should_decay(name, param, scope) -> bool" ], + "globals": [ + "MUON_EXEMPT: the muon_exempt values Muon reads ('always', 'router')" + ], "registry": [ "@registry.register_optimizer('adamw')", "@registry.register_optimizer('lion')", @@ -854,6 +859,20 @@ "tests/unit/test_additional_optimizers.py::TestScheduleFreeAdamW" ] }, + "kempnerforge/training/orthogonalize.py": { + "purpose": "Exact Newton-Schulz orthogonalization of sharded matrices for Muon", + "functions": [ + "orthogonalize_exact(params, updates, newton_schulz) -> list[Tensor] (each update as its full matrix: row-sharded ones gathered onto one rank of their group by all-to-all, other layouts all-gathered; a collective over every rank)", + "holds_whole_matrices(param) -> bool (every rank holds whole param[i] matrices of a 3-D stack: not a DTensor, or split only along its first dim)" + ], + "tested_by": [ + "tests/unit/test_orthogonalize.py::TestRowChunks", + "tests/unit/test_orthogonalize.py::TestOrthogonalizeExact", + "tests/unit/test_orthogonalize.py::TestMuonOnRowShards", + "tests/unit/test_orthogonalize.py::TestMuonOnPackedExperts", + "tests/unit/test_ep_gradients.py::TestMuonPackedExpertsUnderExpertParallelism" + ] + }, "kempnerforge/training/scheduler.py": { "functions": [ "build_scheduler(optimizer, config, max_steps) -> LambdaLR", @@ -1965,7 +1984,7 @@ "classes": [ "TestModelConfig(23)", "TestTrainConfig(24)", - "TestOptimizerConfig(6)", + "TestOptimizerConfig(7)", "TestDistributedConfig(6)", "TestCheckpointConfig(2)", "TestSchedulerConfig(3)", @@ -1984,7 +2003,7 @@ "TestChecksReadTheMergedLayers(7)", "TestDerivedDefaultsFollowTheMergedLayers(3)" ], - "count": 173 + "count": 174 }, "tests/unit/test_training.py": { "classes": [ @@ -2082,7 +2101,7 @@ "TestCheckpointManagerLoad(3)", "TestResumeWithUnsteppedParameters(18)", "TestFreshIfUnheld(9)", - "TestMuonResume(26)", + "TestMuonResume(30)", "TestSaveBeforeFirstStep(21)", "TestResumeWithoutTrainState(10)", "TestResumeWithoutTrainStateAcrossRanks(2)", @@ -2096,7 +2115,7 @@ "TestTornStageAcrossRanks(1)", "TestOptimizerTypeChangeOnResume(6)" ], - "count": 381 + "count": 385 }, "tests/unit/test_checkpoint_publish.py": { "classes": [ @@ -2230,12 +2249,21 @@ "tests/unit/test_optimizer.py": { "classes": [ "TestNewtonSchulz(5)", - "TestMuon(35)", - "TestMuonRouting(6)", + "TestMuon(38)", + "TestMuonRouting(17)", "TestAdamW(2)", "TestWeightDecayScope(8)" ], - "count": 56 + "count": 70 + }, + "tests/unit/test_orthogonalize.py": { + "classes": [ + "TestRowChunks(1)", + "TestOrthogonalizeExact(2)", + "TestMuonOnRowShards(2)", + "TestMuonOnPackedExperts(3)" + ], + "count": 8 }, "tests/unit/test_muon_ns_dtype.py": { "note": "Module-level pytest functions (no Test* classes): optimizer.muon_ns_dtype defaults to fp32, takes bf16 and refuses other values; Muon refuses other ns_dtype values too; build_optimizer passes it to every Muon param group; _orthogonalize_matrix iterates Newton-Schulz in the dtype it is given (fp32 and bf16) and returns fp32; the bf16 path casts before normalizing and back to fp32 at the end; bf16 Newton-Schulz stays within accumulated bf16 rounding of fp32 and orthogonalizes alike; the default step is bitwise the fp32 formula and the fp32 setting's step; a bf16 step iterates in bf16, keeps the parameter and momentum buffer in fp32 and tracks the fp32 step; a resume keeps the saved dtype, and a state saved before the option resumes as fp32", diff --git a/docs/checkpointing/dcp-model.md b/docs/checkpointing/dcp-model.md index 9994ee122..5861e6d80 100644 --- a/docs/checkpointing/dcp-model.md +++ b/docs/checkpointing/dcp-model.md @@ -111,10 +111,11 @@ metadata. Those go in `train_state.pt` alongside — `get_optimizer_state_dict` keeps only an optimizer's own `state` and `param_groups`; any other key its `state_dict()` returns is dropped. -Muon hands every parameter but the hidden `nn.Linear` weights — the -embedding and output head, conv kernels, packed expert weights, MoE -router gates unless `optimizer.muon_router` is set, norms and biases — -to an inner `torch.optim.AdamW` that its own `param_groups` do not list, so +Muon hands every parameter it does not orthogonalize (the embedding and +output head, conv kernels, packed expert weights when +`optimizer.muon_packed_experts` is off, MoE router gates unless +`optimizer.muon_router` is set, norms and biases) to an inner +`torch.optim.AdamW` that its own `param_groups` do not list, so passing Muon alone would leave that AdamW's moments out of the checkpoint and restart them from zero on every resume. @@ -386,11 +387,15 @@ orthogonalized before it routed parameters by module has a saved `momentum_buffer` where its AdamW now keeps `exp_avg`, `exp_avg_sq` and `step`. The same holds for any other parameter that change moved, such as a vision tower's position table or an MQA key projection, for a -router gate when `optimizer.muon_router` changes, and for every +router gate when `optimizer.muon_router` changes, for the packed expert +weights when `optimizer.muon_packed_experts` changes, and for every parameter when `optimizer.name` changes. The load compares the template's state entries with the checkpoint's metadata before reading anything and fails naming those parameters, instead of leaving `dcp.load` to stop at the -first missing key. Continuing from the weights takes the same warm start, +first missing key. A packed-MoE Muon checkpoint saved before +`optimizer.muon_packed_experts` existed holds AdamW state for the packed +expert weights, so it resumes as it was saved with that option off. +Continuing from the weights takes the same warm start, from a `checkpoint.dir` that holds no checkpoint yet. A parameter saved with only part of the state its optimizer keeps now fails the same way, before anything is read: a `schedule_free_adamw` checkpoint written diff --git a/docs/configuration/config-sections.md b/docs/configuration/config-sections.md index 96e4c230b..978f13d2a 100644 --- a/docs/configuration/config-sections.md +++ b/docs/configuration/config-sections.md @@ -155,6 +155,7 @@ are shared (AdamW/Lion) or optimizer-specific. | `muon_orthogonalize` | `"local" \| "exact"` | `"local"` | Newton–Schulz on each rank's shard, or on the full matrix | | `muon_ns_dtype` | `"fp32" \| "bf16"` | `"fp32"` | dtype Newton–Schulz iterates in; the momentum and the applied update keep the parameter dtype, so with bf16 parameters (the default without `train.fp32_master_weights`) `"bf16"` changes only that precision, and with fp32 parameters it also halves the `"exact"` all-to-alls; see [Optimizers § Muon](../training/optimizers.md#muon) | | `muon_router` | `bool` | `False` | Orthogonalize MoE router gates with Muon instead of its AdamW fallback | +| `muon_packed_experts` | `bool` | `True` | Orthogonalize packed expert weights (`model.moe_packed_experts`) with Muon, one expert at a time as unpacked experts are, instead of its AdamW fallback. A resume across a change is refused, so a packed-MoE Muon checkpoint saved before the option existed resumes with `False`; see [Optimizers § Packed experts](../training/optimizers.md#packed-experts) | | `schedule_free_warmup_steps` | `int` | `0` | internal warmup for schedule-free | | `weight_decay_scope` | `"exclude_norms_and_biases" \| "all"` | `"exclude_norms_and_biases"` | which parameters are decayed; `"all"` decays every parameter, as `torch.optim.AdamW` does by default. A resume that restores optimizer state saved under the other scope is refused | | `lr_multipliers` | `dict[str, float]` | `{}` | per-module learning rates: each `vlm.module_patterns` module listed trains at `lr` times its multiplier, in its own param groups (see [Optimizers § Per-module learning rates](../training/optimizers.md#per-module-learning-rates)). A resume that restores optimizer or scheduler state saved with other multipliers, or other patterns for their modules, is refused | diff --git a/docs/how-to/build-a-model.md b/docs/how-to/build-a-model.md index 323ab6e44..a41b2004f 100644 --- a/docs/how-to/build-a-model.md +++ b/docs/how-to/build-a-model.md @@ -204,6 +204,35 @@ registered `mlp` names. List the module in `plugins`, or import it at the top of your entry point before it calls `load_config`. ``` +## Mark what Muon leaves to AdamW + +With `optimizer.name = "muon"`, Muon orthogonalizes the weight of every +`nn.Linear` and, one expert at a time, the packed expert weights of every +`MoEMLP`, and leaves the other parameters to its AdamW fallback (see +[Optimizers § `muon`](../training/optimizers.md#muon)). A module keeps its +parameters on the fallback by setting `muon_exempt`: `OutputHead` sets +`"always"`, and the routers set `"router"`, which keeps a gate on AdamW +unless `optimizer.muon_router = true`. A model registered with +`registry.register_model` whose head or MoE block is built from its own +classes marks them the same way: + +```python +import torch.nn as nn +from kempnerforge.model.router import SoftmaxTopKRouter + +class MyModel(nn.Module): + def __init__(self, dim: int, vocab_size: int, num_experts: int) -> None: + super().__init__() + self.router = SoftmaxTopKRouter(dim, num_experts, top_k=2) + self.head = nn.Linear(dim, vocab_size, bias=False) + self.head.muon_exempt = "always" +``` + +The in-tree router needs nothing: its class sets `"router"`. A head +class of your own can set `muon_exempt = "always"` as a class attribute +instead. The marker covers the module's submodules, and an unmarked +`nn.Linear` head is orthogonalized like any hidden matrix. + ## What's *not* registered `TransformerBlock` itself is **hardcoded**, not registered. There's no diff --git a/docs/how-to/compare-optimizers.md b/docs/how-to/compare-optimizers.md index b5fa55b54..6f36a3688 100644 --- a/docs/how-to/compare-optimizers.md +++ b/docs/how-to/compare-optimizers.md @@ -102,13 +102,16 @@ uses `lr = 0.003` as a working reference. module that owns it, with [`_muon_matrices`](https://github.com/KempnerInstitute/KempnerForge/blob/main/kempnerforge/training/optimizer.py): -- **Muon group**: the weight of every `nn.Linear` except the output - head and, unless `muon_router = true`, the MoE router gates, whatever - its shape: the attention, MLP and unpacked expert projections. +- **Muon group**: the weight of every `nn.Linear`, whatever its shape, + except in a module that sets `muon_exempt`: the output head, and the + MoE router gates unless `muon_router = true`. That leaves the + attention, MLP and unpacked expert projections. It also takes the + packed expert weights, one expert at a time, unless + `muon_packed_experts = false`. - **AdamW fallback group**: the token embedding and output head, any other `nn.Embedding` or conv kernel, MoE router gates (unless - `muon_router = true`), packed expert weights, and 1D params (biases, - norm scales). + `muon_router = true`), packed expert weights (with + `muon_packed_experts = false`), and 1D params (biases, norm scales). The builder logs the two counts. For `7b_16gpu_muon.toml`: diff --git a/docs/how-to/moe-experiments.md b/docs/how-to/moe-experiments.md index 64d60014c..ec4bfd266 100644 --- a/docs/how-to/moe-experiments.md +++ b/docs/how-to/moe-experiments.md @@ -225,7 +225,11 @@ Replaces the `ModuleList` of experts with three packed At 8 experts the win is marginal; at 16+ it's worth the flag. Default is off because the EP integration (slicing packed tensors on the -expert axis) is newer than the unpacked path. +expert axis) is newer than the unpacked path. Under Muon the packed +experts take Muon one expert at a time, as unpacked experts do; +`optimizer.muon_packed_experts = false` leaves them to Muon's AdamW +fallback instead (see +[Optimizers § Packed experts](../training/optimizers.md#packed-experts)). ## Composition caveats diff --git a/docs/moe/capacity-and-dispatch.md b/docs/moe/capacity-and-dispatch.md index d12e1d14f..1b511ae2a 100644 --- a/docs/moe/capacity-and-dispatch.md +++ b/docs/moe/capacity-and-dispatch.md @@ -196,6 +196,12 @@ as E grows. Peak memory is approximately the same. along the expert axis) is newer than the unpacked path. Flip it on for MoE runs with ≥ 16 experts. +Under [Muon](../training/optimizers.md#packed-experts) the packed +weights get Muon one expert's slice at a time, as unpacked experts get +it, so turning packing on keeps the experts' optimizer. +`optimizer.muon_packed_experts = false` leaves them to Muon's AdamW +fallback instead. + A checkpoint keeps the layout it was saved with: packed experts are saved as `up_w` and `down_w`, with `gate_w` for SwiGLU experts, and unpacked ones as `experts.{i}.*`, so a checkpoint loads only with the diff --git a/docs/training/optimizers.md b/docs/training/optimizers.md index 68c7f6d4d..f076ff2d1 100644 --- a/docs/training/optimizers.md +++ b/docs/training/optimizers.md @@ -266,6 +266,7 @@ muon_adjust_lr = "original" muon_orthogonalize = "local" muon_ns_dtype = "fp32" muon_router = false +muon_packed_experts = true # muon_adam_lr omitted -> the internal AdamW uses Muon's LR weight_decay = 0.1 betas = [0.9, 0.95] # used by the internal AdamW @@ -287,22 +288,42 @@ the module that owns it rather than by its shape: - Weight of an `nn.Linear` → Muon orthogonalized update, however rectangular: attention, MLP, expert, cross-attention and adapter projections. -- The output head (`OutputHead`), `nn.Embedding` tables (the token - embedding, a vision tower's position embedding), conv kernels (a vision - tower's patch embedding), packed 3-D expert weights, norms and biases → - internal AdamW fallback. -- MoE router gates (`MoEMLP`'s and MoMa's) → internal AdamW, or Muon with - `muon_router = true`. Practice is split: +- `nn.Embedding` tables (the token embedding, a vision tower's position + embedding), conv kernels (a vision tower's patch embedding), norms and + biases → internal AdamW fallback. +- Packed 3-D expert weights (`model.moe_packed_experts = true`) → Muon + one expert at a time, or the internal AdamW fallback with + `muon_packed_experts = false` (see [Packed experts](#packed-experts)). +- Every parameter of a module that sets `muon_exempt = "always"`, as the + output head (`OutputHead`) does → internal AdamW fallback. +- Every parameter of a module that sets `muon_exempt = "router"`, as the + MoE routers do (`SoftmaxTopKRouter`, `SigmoidTopKRouter` and MoMa's + `ExpertChoiceSigmoidRouter`) → internal AdamW, or Muon with + `muon_router = true`. `MoEMLP` gives its router `"router"` when the + router sets nothing, as a registered router may not. Practice is split: [Moonlight](https://arxiv.org/abs/2502.16982) trained its MoE router with Muon, while [Qwen3.8-Next](https://arxiv.org/abs/2608.30320) keeps it on AdamW because Muon destabilized it early in training. +A model built from its own classes marks its head and routers the same +way (see [Build a model](../how-to/build-a-model.md#mark-what-muon-leaves-to-adamw)): +the builder reads `muon_exempt` from each module, so a class attribute +and an attribute set on one module both work, and it covers the module's +submodules too. A value other than `"always"`, `"router"` or `None` fails +the build. An unmarked `nn.Linear` head is orthogonalized like any hidden +matrix. At debug level, which KempnerForge's logger prints on rank 0, the +builder lists the names it orthogonalizes, each index as `*`, with a +count per name. The names leave out the `torch.compile` and +activation-checkpointing wrappers, as checkpoint names do. + A resume needs the split its checkpoint was saved with. One saved before Muon routed by module, from a model whose embedding or head Muon then -orthogonalized, or saved with the other `muon_router`, fails to load and -names the parameters that moved. A Muon checkpoint saved before the inner -AdamW was checkpointed is the exception — see -[DCP model § Loading](../checkpointing/dcp-model.md#loading). +orthogonalized, or saved with the other `muon_router` or +`muon_packed_experts`, fails to load and names the parameters that moved. +A packed-MoE checkpoint saved before `muon_packed_experts` existed was +saved with it off (see [Packed experts](#packed-experts)). +A Muon checkpoint saved before the inner AdamW was checkpointed is the +exception; see [DCP model § Loading](../checkpointing/dcp-model.md#loading). DTensor / FSDP2 notes: @@ -389,6 +410,45 @@ The shipped combines Muon with z-loss + chunked cross-entropy as an integration test of all three features together. +### Packed experts + +With `model.moe_packed_experts = true` an MoE layer keeps its experts' +weights as `up_w`, `down_w` and, under SwiGLU, `gate_w`: one +`(num_experts, in, out)` tensor per projection, each expert's slice the +transpose of the `nn.Linear` weight it replaces. The same experts +unpacked are `nn.Linear` weights and get Muon, and so do the packed ones, +so the flag meant for grouped-GEMM speed leaves the experts' optimizer +as it is. + +Under `muon_packed_experts = true`, the default, they go in param groups +marked `batched`, after the other Muon groups, and each step runs +Newton-Schulz on every expert's `in × out` slice and takes the update +scale for the `out × in` weight that slice stands for. +Newton-Schulz runs once per expert, as it does on unpacked experts. FSDP2 +shards the packed tensors by expert (`Shard(0)`), expert parallelism gives +each rank whole experts, and tensor parallelism leaves experts whole, so +every rank holds whole slices: `"local"` and `"exact"` give the same, +full-matrix update, and neither gathers anything. `"exact"` refuses a +layout that splits a slice. + +From the same seed, packed and unpacked experts take the same steps, up +to rounding, on one process and under `"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 +expert's slice is orthogonalized whole. The packed experts then step as +they would on one process, and the unpacked ones do not. + +`muon_packed_experts = false` leaves the packed weights to the internal +AdamW, as Muon did before the option existed, and the build logs a line +saying so. Turning it off, or on, moves the packed weights to the other +optimizer, and a resume across the change is refused, naming them. A +packed-MoE Muon checkpoint saved before the option existed holds AdamW +state for them, so it resumes as it was saved with +`muon_packed_experts = false`. To switch a run to the other optimizer, +continue from its weights with a fresh optimizer: `checkpoint.load_path` +set to the checkpoint and `checkpoint.exclude_from_loading = ["optimizer"]`, +with a `checkpoint.dir` that holds no checkpoint yet. + ## Picking one | Situation | Pick | diff --git a/kempnerforge/checkpoint/manager.py b/kempnerforge/checkpoint/manager.py index 89eb30320..6c40429ee 100644 --- a/kempnerforge/checkpoint/manager.py +++ b/kempnerforge/checkpoint/manager.py @@ -947,9 +947,12 @@ def _check_saved_state_matches( f"{where} holds another optimizer's state for {len(moved)} parameters: " f"{moved[:8]}. {first} was saved with " f"{sorted(saved[first])} and is now kept with {sorted(kept[first])}: its optimizer " - "changed since the save, e.g. optimizer.name or optimizer.muon_router changed, " - "or Muon used to orthogonalize it before it routed parameters by module. " - "To continue from these weights with a fresh optimizer, set " + "changed since the save, e.g. optimizer.name, optimizer.muon_router or " + "optimizer.muon_packed_experts changed, or Muon used to orthogonalize it before " + "it routed parameters by module. A packed-MoE Muon checkpoint saved before " + "optimizer.muon_packed_experts existed holds AdamW state for the packed expert " + "weights: set optimizer.muon_packed_experts = false to resume it as it was saved. " + "To continue from these weights with a fresh optimizer instead, set " "checkpoint.load_path to this checkpoint and checkpoint.exclude_from_loading = " '["optimizer"], with a checkpoint.dir that holds no checkpoint yet.' ) diff --git a/kempnerforge/config/optimizer.py b/kempnerforge/config/optimizer.py index f85214b61..ddd4454e9 100644 --- a/kempnerforge/config/optimizer.py +++ b/kempnerforge/config/optimizer.py @@ -54,6 +54,7 @@ class OptimizerConfig: muon_orthogonalize: str = "local" muon_ns_dtype: str = "fp32" muon_router: bool = False + muon_packed_experts: bool = True schedule_free_warmup_steps: int = 0 weight_decay_scope: str = "exclude_norms_and_biases" lr_multipliers: dict[str, float] = field(default_factory=dict) diff --git a/kempnerforge/model/embedding.py b/kempnerforge/model/embedding.py index 5972eda54..eb3a46861 100644 --- a/kempnerforge/model/embedding.py +++ b/kempnerforge/model/embedding.py @@ -33,8 +33,11 @@ class OutputHead(nn.Module): """Linear output projection from hidden dim to vocab size. Produces logits (no softmax). Can optionally share weights with an embedding layer. + ``muon_exempt`` leaves its weight to Muon's AdamW fallback. """ + muon_exempt = "always" + def __init__(self, dim: int, vocab_size: int) -> None: super().__init__() self.proj = nn.Linear(dim, vocab_size, bias=False) diff --git a/kempnerforge/model/moe.py b/kempnerforge/model/moe.py index d07596fdb..e08e24322 100644 --- a/kempnerforge/model/moe.py +++ b/kempnerforge/model/moe.py @@ -162,6 +162,10 @@ class MoEMLP(nn.Module): registry). Drop-in replacement for dense MLP — same forward signature. Stores aux_loss after each forward for collection by the training loop. + + A ``router`` that sets no ``muon_exempt`` gets ``"router"``, so Muon leaves its + parameters to the AdamW fallback unless ``optimizer.muon_router``, as it does the + in-tree routers'. """ def __init__( @@ -174,6 +178,8 @@ def __init__( packed_experts: bool = False, ) -> None: super().__init__() + if not hasattr(router, "muon_exempt"): + vars(router)["muon_exempt"] = "router" self.router = router self.shared_expert = shared_expert self.num_experts = len(experts) diff --git a/kempnerforge/model/moma.py b/kempnerforge/model/moma.py index c9d9b75d7..d2777aa07 100644 --- a/kempnerforge/model/moma.py +++ b/kempnerforge/model/moma.py @@ -91,8 +91,12 @@ class ExpertChoiceSigmoidRouter(nn.Module): ``N`` is the number of tokens of this modality in the current batch. The paper's default ``c_e = 1/|E^M|`` gives ``k_e ≈ N/|E^M|`` so each expert sees the average load (perfect balance under EC routing). + + ``muon_exempt`` leaves the gate to Muon's AdamW fallback unless ``optimizer.muon_router``. """ + muon_exempt = "router" + def __init__( self, dim: int, diff --git a/kempnerforge/model/router.py b/kempnerforge/model/router.py index 9e4bef4c3..9ccb4ca15 100644 --- a/kempnerforge/model/router.py +++ b/kempnerforge/model/router.py @@ -58,8 +58,12 @@ class SoftmaxTopKRouter(nn.Module): Stores ``aux_loss`` and ``expert_counts`` as side effects of each forward call for collection by the training loop and metrics, except in the recompute of an activation-checkpointed block (see ``Recomputing``). + + ``muon_exempt`` leaves the gate to Muon's AdamW fallback unless ``optimizer.muon_router``. """ + muon_exempt = "router" + def __init__(self, dim: int, num_experts: int, top_k: int) -> None: super().__init__() self.gate = nn.Linear(dim, num_experts, bias=False) @@ -123,7 +127,8 @@ class SigmoidTopKRouter(nn.Module): ``derived_buffers`` names the buffers a load derives from the other state when a checkpoint lacks them. - ``always_frozen`` names the parameters that ``freeze_params`` never unfreezes. + ``always_frozen`` names the parameters that ``freeze_params`` never unfreezes, and + ``muon_exempt`` leaves the gate to Muon's AdamW fallback unless ``optimizer.muon_router``. Optional enhancements (all disabled by default for backward compatibility): @@ -135,6 +140,7 @@ class SigmoidTopKRouter(nn.Module): """ always_frozen = ("expert_bias",) + muon_exempt = "router" derived_buffers = ("fp32_ema_bits", "fp32_bias_bits") expert_ema: torch.Tensor pending_counts: torch.Tensor diff --git a/kempnerforge/training/optimizer.py b/kempnerforge/training/optimizer.py index 7f8169ec1..de9b20a09 100644 --- a/kempnerforge/training/optimizer.py +++ b/kempnerforge/training/optimizer.py @@ -23,12 +23,14 @@ import fnmatch import functools import logging -from collections.abc import Iterable, Iterator, Mapping, Sequence +from collections import Counter +from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence from typing import Any, ClassVar import torch from torch.distributed._composable.fsdp import FSDPModule +from kempnerforge.checkpoint.expert_layout import state_dict_name from kempnerforge.config.optimizer import ( MUON_ADJUST_LR_MODES, MUON_NS_DTYPES, @@ -36,10 +38,8 @@ ) from kempnerforge.config.registry import registry from kempnerforge.config.schema import OptimizerConfig -from kempnerforge.model.embedding import OutputHead from kempnerforge.model.moe import MoEMLP -from kempnerforge.model.moma import ExpertChoiceMoE -from kempnerforge.training.orthogonalize import orthogonalize_exact +from kempnerforge.training.orthogonalize import holds_whole_matrices, orthogonalize_exact logger = logging.getLogger(__name__) @@ -370,6 +370,16 @@ def _orthogonalize_matrix( return _newton_schulz(matrix.to(dtype), steps=steps).to(matrix.dtype) +def _orthogonalize_slices( + stack: torch.Tensor, newton_schulz: Callable[[torch.Tensor], torch.Tensor] +) -> torch.Tensor: + """``newton_schulz`` of each matrix ``stack[i]`` of a 3-D ``stack``, stacked alike.""" + out = torch.empty_like(stack) + for index, matrix in enumerate(stack): + out[index] = newton_schulz(matrix) + return out + + def _muon_update_scale(adjust_lr: str, rows: int, cols: int) -> float: """Factor on Muon's orthogonalized update for a ``rows`` x ``cols`` matrix.""" if adjust_lr == "match_rms_adamw": @@ -416,6 +426,14 @@ class Muon(torch.optim.Optimizer): three decades, the cosine similarity drops to 0.62 to 0.91, at 0.97 to 1.21 times the RMS. ``orthogonalize="exact"`` gives the full-matrix update. + A param group with ``batched`` set holds 3-D weights, each a stack of ``(in, out)`` + matrices along its first dim, as a packed MoE layer stores its experts. Newton-Schulz runs + on each matrix, and the update scale takes it as ``out`` rows by ``in`` columns, the shape + of the ``nn.Linear`` weight it stands for. FSDP2 and expert parallelism split such a + weight along its first dim, so every rank holds whole matrices and the update is the + full-matrix one under either ``orthogonalize``; ``"exact"`` refuses a layout that splits a + matrix. + The AdamW fallback follows Muon's schedule: each step sets every AdamW group's rate to its base rate, its own ``lr`` or else ``adam_lr``, times the ratio of Muon's first group's current rate to that group's base rate. @@ -425,7 +443,8 @@ class Muon(torch.optim.Optimizer): load that restores a schedule saved under another ``lr`` keeps ``adam_lr``. Args: - muon_params: Parameter groups for Muon (the hidden ``nn.Linear`` weights). + muon_params: Parameter groups for Muon (the hidden ``nn.Linear`` weights, and in + groups with ``batched`` set, packed expert weights). adam_params: Parameter groups for AdamW fallback (every other parameter). lr: Learning rate for Muon. momentum: Momentum coefficient (default 0.95). @@ -446,6 +465,10 @@ class Muon(torch.optim.Optimizer): it is scaled and applied. adam_fused: Whether the AdamW fallback runs PyTorch's fused kernel; False runs its single-tensor loop. None fuses it when CUDA is available. + + Raises: + ValueError: A setting is not one of its values, or a ``batched`` group holds a weight + that is not 3-D. """ LEGACY_GROUP_DEFAULTS: ClassVar[dict[str, Any]] = { @@ -511,6 +534,18 @@ def __init__( ns_dtype=ns_dtype, ) super().__init__(muon_params, defaults) + unstacked = [ + tuple(p.shape) + for group in self.param_groups + if group.get("batched", False) + for p in group["params"] + if p.ndim != 3 + ] + if unstacked: + raise ValueError( + f"a batched param group holds 3-D stacks of matrices, not weights of shapes " + f"{unstacked}" + ) @property def inner_optimizers(self) -> tuple[torch.optim.Optimizer, ...]: @@ -589,6 +624,7 @@ def step(self, closure=None): adjust_lr = group["adjust_lr"] orthogonalize = group["orthogonalize"] ns_dtype = _NS_DTYPES[group["ns_dtype"]] + batched = group.get("batched", False) params = [p for p in group["params"] if p.grad is not None] inputs = [] @@ -602,11 +638,21 @@ def step(self, closure=None): buf_local.mul_(momentum).add_(g_local) inputs.append(g_local.add(buf_local, alpha=momentum) if nesterov else buf_local) - matrices = [x.flatten(1) for x in inputs] + matrices = inputs if batched else [x.flatten(1) for x in inputs] if ns_dtype != torch.float32: matrices = [matrix.to(ns_dtype) for matrix in matrices] newton_schulz = functools.partial(_orthogonalize_matrix, steps=ns_steps, dtype=ns_dtype) - if orthogonalize == "exact": + if batched: + if orthogonalize == "exact": + split = [tuple(p.shape) for p in params if not holds_whole_matrices(p)] + if split: + raise RuntimeError( + "orthogonalize='exact' runs Newton-Schulz on the matrices of batched " + f"weights that each rank holds whole, but the weights of shapes " + f"{split} are split other than along their first dim" + ) + orthos = [_orthogonalize_slices(stack, newton_schulz) for stack in matrices] + elif orthogonalize == "exact": orthos = orthogonalize_exact(params, matrices, newton_schulz) else: orthos = [newton_schulz(matrix) for matrix in matrices] @@ -615,7 +661,9 @@ def step(self, closure=None): p_local = _get_local_tensor(p) update = ortho.view(x.shape).to(x.dtype) - if orthogonalize == "exact": + if batched: + m, n = x.shape[2], x.shape[1] + elif orthogonalize == "exact": m, n = p.shape[0], p.shape[1:].numel() else: m, n = ortho.shape @@ -653,22 +701,63 @@ def _fallback_lrs(self) -> list[float]: ] -def _muon_matrices(model: torch.nn.Module, *, routers: bool) -> set[torch.Tensor]: - """Return the ``nn.Linear`` weights Muon orthogonalizes. +MUON_EXEMPT = ("always", "router") + + +def _muon_matrices( + model: torch.nn.Module, *, routers: bool +) -> tuple[set[torch.Tensor], set[torch.Tensor]]: + """Return the weights Muon orthogonalizes whole, and those it can take one expert at a time. - The output head's go to AdamW, and so do the MoE routers' unless ``routers``. + The first set holds the ``nn.Linear`` weights. The second holds the packed + ``(E, in, out)`` expert weights of every ``MoEMLP`` that packs its experts, which Muon + takes with ``optimizer.muon_packed_experts``. A module that sets ``muon_exempt``, on its + class or on itself, leaves every parameter it holds, its submodules' included, to the + AdamW fallback: ``"always"``, as ``OutputHead`` sets, does so always, and ``"router"``, + as the MoE routers set, unless ``routers``. ``None`` exempts nothing. + + Raises: + ValueError: A module sets ``muon_exempt`` to another value. """ adamw: set[torch.Tensor] = set() - for module in model.modules(): - if isinstance(module, OutputHead): + for name, module in model.named_modules(): + exempt = getattr(module, "muon_exempt", None) + if exempt is not None and exempt not in MUON_EXEMPT: + raise ValueError( + f"{name or type(module).__name__} sets muon_exempt = {exempt!r}; Muon takes " + f"{' or '.join(map(repr, MUON_EXEMPT))}, or None to exempt nothing" + ) + if exempt == "always" or (exempt == "router" and not routers): adamw.update(module.parameters()) - elif not routers and isinstance(module, MoEMLP | ExpertChoiceMoE): - adamw.update(module.router.parameters()) - return { + matrices = { module.weight for module in model.modules() if isinstance(module, torch.nn.Linear) and module.weight not in adamw } + stacks: set[torch.Tensor] = { + param + for module in model.modules() + if isinstance(module, MoEMLP) and module.packed_experts + for param in module._expert_params() + if param not in adamw + } + return matrices, stacks + + +def _name_patterns(model: torch.nn.Module, params: Iterable[torch.Tensor]) -> str: + """The names of ``params`` in ``model`` with each index as ``*``, and each pattern's count. + + ``layers.0.attention.q_proj.weight`` and ``layers.1.attention.q_proj.weight`` read + ``layers.*.attention.q_proj.weight (2)``. The names leave out the activation-checkpoint and + ``torch.compile`` wrappers, as state-dict names do (see ``state_dict_name``). + """ + wanted = set(params) + counts = Counter( + ".".join("*" if part.isdigit() else part for part in state_dict_name(name).split(".")) + for name, param in model.named_parameters() + if param in wanted + ) + return ", ".join(f"{pattern} ({count})" for pattern, count in sorted(counts.items())) @registry.register_optimizer("muon") @@ -677,22 +766,29 @@ def _build_muon( config: OptimizerConfig, model: torch.nn.Module, ) -> torch.optim.Optimizer: - on_muon = _muon_matrices(model, routers=config.muon_router) + on_muon, stacks = _muon_matrices(model, routers=config.muon_router) muon_groups = [] + batched_groups = [] adam_groups = [] for group in param_groups: muon_params = [] + batched_params = [] adam_params = [] for p in group["params"]: if p in on_muon: muon_params.append(p) + elif p in stacks and config.muon_packed_experts: + batched_params.append(p) else: adam_params.append(p) if muon_params: muon_groups.append({**group, "params": muon_params}) + if batched_params: + batched_groups.append({**group, "params": batched_params, "batched": True}) if adam_params: adam_groups.append({**group, "params": adam_params}) + muon_groups += batched_groups if not adam_groups: adam_groups = [{"params": [], "weight_decay": 0.0}] @@ -705,6 +801,20 @@ def _build_muon( n_muon = sum(p.numel() for g in muon_groups for p in g["params"]) n_adam = sum(p.numel() for g in adam_groups for p in g["params"]) logger.info(f"Muon: {n_muon:,} params (NS-orthogonalized), {n_adam:,} params (AdamW fallback)") + n_stacked = sum(p.numel() for g in adam_groups for p in g["params"] if p in stacks) + if n_stacked: + logger.info( + f"Muon leaves {n_stacked:,} params of packed expert weights to AdamW; " + "optimizer.muon_packed_experts = true orthogonalizes them one expert at a time, " + "as Muon does unpacked experts" + ) + if logger.isEnabledFor(logging.DEBUG): + whole = [p for g in muon_groups if not g.get("batched") for p in g["params"]] + sliced = [p for g in batched_groups for p in g["params"]] + parts = [_name_patterns(model, whole)] if whole else [] + if sliced: + parts.append(f"one expert at a time, {_name_patterns(model, sliced)}") + logger.debug(f"Muon orthogonalizes {'; '.join(parts)}") return Muon( muon_groups, diff --git a/kempnerforge/training/orthogonalize.py b/kempnerforge/training/orthogonalize.py index e68df0d07..5cf03ad60 100644 --- a/kempnerforge/training/orthogonalize.py +++ b/kempnerforge/training/orthogonalize.py @@ -38,6 +38,22 @@ def orthogonalize_exact( return cast("list[torch.Tensor]", results) +def holds_whole_matrices(param: torch.Tensor) -> bool: + """Whether every rank holds whole ``param[i]`` matrices of a 3-D stack ``param``. + + So it does unless ``param`` is a DTensor that a mesh dim of size above one splits along + another dim than its first, the dim FSDP2's ``Shard(0)`` splits. + """ + if not isinstance(param, DTensor): + return True + mesh = param.device_mesh + return all( + isinstance(placement, Replicate) or (isinstance(placement, Shard) and placement.dim == 0) + for dim, placement in enumerate(param.placements) + if mesh.size(dim) > 1 + ) + + def _matrix_shape(param: torch.Tensor) -> tuple[int, int]: """Rows and columns of ``param`` viewed as a 2D matrix.""" return param.shape[0], param.shape[1:].numel() diff --git a/plugins/kempnerforge/skills/add-optimizer/SKILL.md b/plugins/kempnerforge/skills/add-optimizer/SKILL.md index bfa8270f2..ed9082d9f 100644 --- a/plugins/kempnerforge/skills/add-optimizer/SKILL.md +++ b/plugins/kempnerforge/skills/add-optimizer/SKILL.md @@ -22,7 +22,7 @@ Optimizer builders live in: kempnerforge/training/optimizer.py Top-level builder: kempnerforge/training/optimizer.py::build_optimizer(model, config) — creates decay/no-decay param groups, looks up builder from registry, calls it Builder signature: fn(param_groups: list[dict], config: OptimizerConfig, model: torch.nn.Module) -> torch.optim.Optimizer Config dataclass: kempnerforge/config/optimizer.py::OptimizerConfig -Existing fields: name, lr, weight_decay, betas, eps, fused, muon_momentum, muon_ns_steps, muon_adam_lr, muon_nesterov, muon_adjust_lr, muon_orthogonalize, muon_router, schedule_free_warmup_steps +Existing fields: name, lr, weight_decay, betas, eps, fused, muon_momentum, muon_ns_steps, muon_adam_lr, muon_nesterov, muon_adjust_lr, muon_orthogonalize, muon_ns_dtype, muon_router, muon_packed_experts, schedule_free_warmup_steps, weight_decay_scope, lr_multipliers Existing tests: tests/unit/test_optimizer.py, tests/unit/test_additional_optimizers.py diff --git a/tests/unit/test_checkpoint.py b/tests/unit/test_checkpoint.py index f773f5dc4..1b7727409 100644 --- a/tests/unit/test_checkpoint.py +++ b/tests/unit/test_checkpoint.py @@ -3,6 +3,7 @@ from __future__ import annotations import copy +import dataclasses import json import os import random @@ -4348,6 +4349,7 @@ class TestMuonResume: DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu") MODEL_CONFIG = ModelConfig(dim=64, n_layers=2, n_heads=2, vocab_size=4096, max_seq_len=64) + PACKED_MOE = dataclasses.replace(MODEL_CONFIG, num_experts=4, moe_packed_experts=True) def _build(self, seed, **overrides): torch.manual_seed(seed) @@ -4549,6 +4551,74 @@ def test_resume_with_muon_router_flipped_fails_naming_the_gate(self, tmp_path): with pytest.raises(RuntimeError, match=re.escape("['layers.0.mlp.router.gate.weight']")): manager.load() + @pytest.mark.parametrize( + ("saved_with", "resumed_with"), + [(False, None), (True, False)], + ids=["off_then_default", "on_then_off"], + ) + def test_resume_with_muon_packed_experts_flipped_fails_naming_them( + self, tmp_path, saved_with, resumed_with + ): + """Flipping muon_packed_experts across a resume, as the default does for a checkpoint + saved with the packed experts on AdamW, fails naming them, the setting that resumes + such a checkpoint, and the warm start.""" + from kempnerforge.checkpoint.manager import CheckpointManager + + def build(flag: bool | None) -> tuple[Transformer, torch.optim.Optimizer]: + model = Transformer(self.PACKED_MOE).to(self.DEVICE) + options = {} if flag is None else {"muon_packed_experts": flag} + config = OptimizerConfig(name="muon", lr=1e-3, fused=False, **options) + return model, build_optimizer(model, config) + + self._save_stepped(*build(saved_with), tmp_path) + model, optimizer = build(resumed_with) + manager = CheckpointManager(CheckpointConfig(dir=str(tmp_path)), model, optimizer) + weights = ("up_w", "down_w", "gate_w") + packed = sorted(f"layers.{i}.mlp.{w}" for i in range(2) for w in weights) + moved = f"holds another optimizer's state for 6 parameters: {packed}" + with pytest.raises(RuntimeError, match=re.escape(moved)) as raised: + manager.load() + assert "set optimizer.muon_packed_experts = false to resume it" in str(raised.value) + assert 'checkpoint.exclude_from_loading = ["optimizer"]' in str(raised.value) + + @pytest.mark.parametrize("muon_packed_experts", [True, False]) + def test_resume_with_packed_experts_matches_an_uninterrupted_run( + self, tmp_path, muon_packed_experts + ): + """The packed experts resume on the optimizer they were saved on, Muon's batched groups + or, with muon_packed_experts off, the inner AdamW, and the run continues bit for bit.""" + from kempnerforge.checkpoint.manager import CheckpointManager + + def build(seed: int) -> tuple[Transformer, Muon]: + torch.manual_seed(seed) + model = Transformer(self.PACKED_MOE).to(self.DEVICE) + options = OptimizerConfig( + name="muon", lr=1e-3, fused=False, muon_packed_experts=muon_packed_experts + ) + optimizer = build_optimizer(model, options) + assert isinstance(optimizer, Muon) + return model, optimizer + + batches = self._batches(5) + ref_model, ref_opt = build(seed=0) + self._train(ref_model, ref_opt, batches) + + model, opt = build(seed=0) + self._train(model, opt, batches[:2]) + CheckpointManager(CheckpointConfig(dir=str(tmp_path)), model, opt).save(step=2) + + model2, opt2 = build(seed=1) + CheckpointManager(CheckpointConfig(dir=str(tmp_path)), model2, opt2).load() + groups = [group.get("batched", False) for group in opt2.param_groups] + assert groups == [group.get("batched", False) for group in opt.param_groups] + assert (True in groups) is muon_packed_experts + self._assert_same_state(opt, opt2, "Muon") + self._assert_same_state(opt._adam, opt2._adam, "inner AdamW") + + self._train(model2, opt2, batches[2:]) + for (name, ref), p in zip(ref_model.named_parameters(), model2.parameters(), strict=True): + assert torch.equal(ref, p), f"{name} diverged from the uninterrupted run" + def test_checkpoint_saved_before_orthogonalize_resumes_as_local(self, tmp_path): """A checkpoint saved before ``orthogonalize`` existed resumes with "local" and matches.""" from kempnerforge.checkpoint.manager import CheckpointManager diff --git a/tests/unit/test_config.py b/tests/unit/test_config.py index d962e59ac..93086184f 100644 --- a/tests/unit/test_config.py +++ b/tests/unit/test_config.py @@ -395,6 +395,15 @@ def test_rejects_unknown_muon_orthogonalize(self): with pytest.raises(ValueError, match="muon_orthogonalize must be one of"): OptimizerConfig(muon_orthogonalize="global") + def test_muon_packed_experts_is_on_by_default_and_a_toml_or_cli_turns_it_off(self, tmp_path): + assert OptimizerConfig().muon_packed_experts is True + assert load_config(None, cli_args=[]).optimizer.muon_packed_experts is True + toml = tmp_path / "job.toml" + toml.write_text('[optimizer]\nname = "muon"\nmuon_packed_experts = false\n') + assert load_config(str(toml), cli_args=[]).optimizer.muon_packed_experts is False + args = ["--optimizer.muon_packed_experts=false"] + assert load_config(None, cli_args=args).optimizer.muon_packed_experts is False + def test_rejects_negative_schedule_free_warmup(self): with pytest.raises(ValueError, match="schedule_free_warmup_steps"): OptimizerConfig(schedule_free_warmup_steps=-1) diff --git a/tests/unit/test_ep_gradients.py b/tests/unit/test_ep_gradients.py index 61daddcd6..6a2e7e8e7 100644 --- a/tests/unit/test_ep_gradients.py +++ b/tests/unit/test_ep_gradients.py @@ -24,6 +24,7 @@ from torch.distributed.tensor import DTensor from kempnerforge.config.model import ModelConfig +from kempnerforge.config.optimizer import OptimizerConfig from kempnerforge.distributed.expert_parallel import ( apply_expert_parallel, average_non_expert_grads_, @@ -33,6 +34,7 @@ from kempnerforge.model.transformer import Transformer from kempnerforge.training.grad import maybe_no_sync from kempnerforge.training.loop import add_moe_losses, clip_grads +from kempnerforge.training.optimizer import build_optimizer from tests.gloo_ranks import gloo_group, spawn SEQ = 16 @@ -363,6 +365,49 @@ def test_moe_without_ep_matches_one_process(self): _spawn(_check_without_ep, ("dp_shard",), (2,), {}) +def _check_muon_packed_experts(rank, world, port, names, sizes, orthogonalize) -> None: + """A Muon step with ``muon_packed_experts`` leaves every weight Muon steps as one process's + step does, the packed experts moved well past the tolerance.""" + with _group(rank, world, port): + step = _step(names, sizes, {"moe_packed_experts": True}) + config = OptimizerConfig( + name="muon", + lr=0.02, + fused=False, + muon_packed_experts=True, + muon_orthogonalize=orthogonalize, + ) + start = {name: p.detach().clone() for name, p in step.reference.named_parameters()} + average_non_expert_grads_(step.model) + optimizers = [build_optimizer(model, config) for model in (step.model, step.reference)] + for optimizer in optimizers: + assert any(group.get("batched") for group in optimizer.param_groups) + optimizer.step() + on_muon = {p for group in optimizers[1].param_groups for p in group["params"]} + got = _unsharded(step.model, step.mesh, step.reference.config.num_experts, grads=False) + for name, p in step.reference.named_parameters(): + if p not in on_muon: + continue + if name.endswith(PACKED_EXPERT): + assert (p.detach() - start[name]).abs().max() > 1e-3, name + torch.testing.assert_close(got[name], p.detach(), msg=lambda m, n=name: f"{n}: {m}") + + +class TestMuonPackedExpertsUnderExpertParallelism: + @pytest.mark.parametrize( + ("sizes", "orthogonalize"), + [ + pytest.param((1, 2), "local", id="ep2_local"), + pytest.param((1, 2), "exact", id="ep2_exact"), + pytest.param((2, 2), "exact", id="dp_shard2_ep2_exact"), + ], + ) + def test_a_muon_step_matches_one_process(self, sizes, orthogonalize): + """Each EP rank, and each FSDP2 shard of its experts, holds whole experts, so Muon steps + them as one process does with no gather.""" + _spawn(_check_muon_packed_experts, ("dp_shard", "ep"), sizes, orthogonalize) + + FROZEN = "norm.weight" diff --git a/tests/unit/test_optimizer.py b/tests/unit/test_optimizer.py index aefdd308e..ce3bb31e3 100644 --- a/tests/unit/test_optimizer.py +++ b/tests/unit/test_optimizer.py @@ -2,6 +2,7 @@ from __future__ import annotations +import logging from collections.abc import Callable from typing import Any @@ -11,7 +12,11 @@ from torch.overrides import TorchFunctionMode from kempnerforge.config.schema import ModelConfig, OptimizerConfig -from kempnerforge.model.moma import ExpertChoiceMoE +from kempnerforge.distributed.parallel import apply_ac +from kempnerforge.model.mlp import build_mlp +from kempnerforge.model.moe import MoEMLP, build_moe +from kempnerforge.model.moma import ExpertChoiceMoE, ExpertChoiceSigmoidRouter +from kempnerforge.model.router import SigmoidTopKRouter, SoftmaxTopKRouter from kempnerforge.model.transformer import Transformer from kempnerforge.training.optimizer import ( Muon, @@ -64,6 +69,18 @@ def _spectrum_matrix(rows: int, cols: int, decades: int | None) -> torch.Tensor: return (left * torch.logspace(0, -decades, rank)) @ right.T +class _CustomMoEModel(nn.Module): + """A model of its own classes: an MoE block around an in-tree router, and a plain + ``nn.Linear`` head marked exempt.""" + + def __init__(self, router: nn.Module) -> None: + super().__init__() + self.router = router + self.experts = nn.ModuleList(nn.Linear(16, 16, bias=False) for _ in range(4)) + self.head = nn.Linear(16, 32, bias=False) + self.head.muon_exempt = "always" + + def _first_update(*grads: torch.Tensor) -> torch.Tensor: """Muon's first update of zero weights with these gradients, the weights stacked by rows.""" weights = [nn.Parameter(torch.zeros_like(grad)) for grad in grads] @@ -169,6 +186,42 @@ def test_steps_a_shard_with_no_rows(self, orthogonalize, shape): expected = -0.1 * _muon_update_scale("original", 4, 8) * _newton_schulz(weight.grad) torch.testing.assert_close(weight.data, expected) + @pytest.mark.parametrize("shape", [(3, 4, 16), (3, 16, 4)]) + @pytest.mark.parametrize("adjust_lr", ["original", "match_rms_adamw", "spectral_unclamped"]) + def test_batched_group_steps_each_matrix_as_its_linear_weight(self, adjust_lr, shape): + """Each (in, out) matrix of a batched weight steps by NS of its own update, scaled as + the out x in Linear weight it stands for.""" + torch.manual_seed(0) + weight = nn.Parameter(torch.zeros(shape)) + weight.grad = torch.randn(shape) + groups = [{"params": [weight], "batched": True}] + Muon(groups, [{"params": []}], lr=0.1, adjust_lr=adjust_lr).step() + _, n_in, n_out = shape + for matrix, grad in zip(weight.data, weight.grad, strict=True): + expected = -0.1 * _muon_update_scale(adjust_lr, n_out, n_in) * _newton_schulz(grad) + torch.testing.assert_close(matrix, expected) + + @pytest.mark.parametrize("orthogonalize", ["local", "exact"]) + def test_batched_group_steps_a_shard_with_no_matrices(self, orthogonalize): + """A rank holds no experts of a packed weight with fewer experts than FSDP2 shards. It + steps that weight and the rest of its group, the rest as it would without that weight.""" + torch.manual_seed(0) + empty = nn.Parameter(torch.zeros(0, 4, 8)) + weight = nn.Parameter(torch.zeros(2, 4, 8)) + empty.grad = torch.zeros(0, 4, 8) + weight.grad = torch.randn(2, 4, 8) + groups = [{"params": [empty, weight], "batched": True}] + Muon(groups, [{"params": []}], lr=0.1, orthogonalize=orthogonalize).step() + assert empty.shape == (0, 4, 8) + for matrix, grad in zip(weight.data, weight.grad, strict=True): + expected = -0.1 * _muon_update_scale("original", 8, 4) * _newton_schulz(grad) + torch.testing.assert_close(matrix, expected) + + def test_batched_group_refuses_a_weight_that_is_not_3d(self): + groups = [{"params": [nn.Parameter(torch.zeros(4, 4))], "batched": True}] + with pytest.raises(ValueError, match=r"3-D stacks of matrices, not weights of shapes"): + Muon(groups, [{"params": []}]) + def test_nesterov_orthogonalizes_the_lookahead(self): """With nesterov, Newton-Schulz sees grad + momentum * buffer.""" torch.manual_seed(0) @@ -680,7 +733,8 @@ def test_state_saved_before_nesterov_and_adjust_lr_loads_the_old_update(self): class TestMuonRouting: - """Muon takes the hidden ``nn.Linear`` weights; its inner AdamW takes the rest.""" + """Muon takes the hidden ``nn.Linear`` weights, and unless ``muon_packed_experts`` is off + the packed expert weights; its inner AdamW takes the rest.""" @staticmethod def _model(**overrides: Any) -> Transformer: @@ -721,7 +775,8 @@ def test_narrow_and_tall_linear_weights_use_muon(self): @pytest.mark.parametrize("muon_router", [None, False, True]) def test_moe_router_gate_follows_muon_router(self, muon_router): - """The router gate goes to Muon only with muon_router; the experts go to Muon always.""" + """The router gate goes to Muon only with muon_router; the experts go to Muon always, + and the output head never.""" model = self._model(num_experts=4, moe_top_k=2, moe_router="sigmoid_topk") moe = model.layers["0"].mlp options = {} if muon_router is None else {"muon_router": muon_router} @@ -731,6 +786,7 @@ def test_moe_router_gate_follows_muon_router(self, muon_router): assert (moe.router.gate.weight in adam) is not on_muon assert moe.router.expert_bias not in adam | muon assert {expert.up_proj.weight for expert in moe.experts} <= muon + assert model.output_head is not None and model.output_head.proj.weight in adam @pytest.mark.parametrize("muon_router", [False, True]) def test_moma_router_gate_follows_muon_router(self, muon_router): @@ -741,12 +797,203 @@ def test_moma_router_gate_follows_muon_router(self, muon_router): assert (moe.router.gate.weight in muon) is muon_router assert (moe.router.gate.weight in adam) is not muon_router - def test_packed_experts_use_adam(self): - """Packed 3-D expert weights go to AdamW.""" + @pytest.mark.parametrize("muon_router", [False, True]) + def test_a_custom_models_plain_linear_head_marked_always_uses_adam(self, muon_router): + """A head that is a plain Linear, marked "always", goes to AdamW as OutputHead does.""" + model = _CustomMoEModel(SoftmaxTopKRouter(16, 4, 2)) + config = OptimizerConfig(name="muon", muon_router=muon_router) + muon, adam = _split(build_optimizer(model, config)) + assert model.head.weight in adam + assert model.head.weight not in muon + + @pytest.mark.parametrize( + "router", + [ + lambda: SoftmaxTopKRouter(16, 4, 2), + lambda: SigmoidTopKRouter(16, 4, 2), + lambda: ExpertChoiceSigmoidRouter(16, 4, capacity_factor=0.5), + ], + ids=["softmax_topk", "sigmoid_topk", "expert_choice"], + ) + @pytest.mark.parametrize("muon_router", [False, True]) + def test_an_in_tree_router_in_a_custom_block_follows_muon_router(self, router, muon_router): + """Each in-tree router's gate follows muon_router in a model's own MoE block too.""" + model = _CustomMoEModel(router()) + config = OptimizerConfig(name="muon", muon_router=muon_router) + muon, adam = _split(build_optimizer(model, config)) + assert (model.router.gate.weight in muon) is muon_router + assert (model.router.gate.weight in adam) is not muon_router + assert {expert.weight for expert in model.experts} <= muon + + @pytest.mark.parametrize("muon_router", [False, True]) + def test_moe_router_that_declares_nothing_follows_muon_router(self, muon_router): + """A router that sets no muon_exempt, as a registered one may not, follows muon_router + inside MoEMLP, as every router there did before modules declared it.""" + router = nn.Module() + router.gate = nn.Linear(16, 4, bias=False) + moe = MoEMLP(router, nn.ModuleList(build_mlp(16, 32) for _ in range(4))) + config = OptimizerConfig(name="muon", muon_router=muon_router) + muon, adam = _split(build_optimizer(moe, config)) + assert (router.gate.weight in muon) is muon_router + assert (router.gate.weight in adam) is not muon_router + + @pytest.mark.parametrize( + ("declared", "muon_router", "on_muon"), [(None, False, True), ("always", True, False)] + ) + def test_moe_keeps_the_muon_exempt_a_router_declares(self, declared, muon_router, on_muon): + """MoEMLP marks only a router that declares nothing; a router's own value stands.""" + router = nn.Module() + router.gate = nn.Linear(16, 4, bias=False) + router.muon_exempt = declared + moe = MoEMLP(router, nn.ModuleList(build_mlp(16, 32) for _ in range(4))) + config = OptimizerConfig(name="muon", muon_router=muon_router) + muon, adam = _split(build_optimizer(moe, config)) + assert (router.gate.weight in muon) is on_muon + assert (router.gate.weight in adam) is not on_muon + + def test_an_unknown_muon_exempt_is_refused(self): + model = _CustomMoEModel(SoftmaxTopKRouter(16, 4, 2)) + model.head.muon_exempt = True + with pytest.raises(ValueError, match=r"head sets muon_exempt = True; Muon takes 'always'"): + build_optimizer(model, OptimizerConfig(name="muon")) + + @pytest.mark.parametrize("wrapper", [None, "compile", "checkpoint"]) + def test_build_logs_the_orthogonalized_names(self, caplog, monkeypatch, wrapper): + """At debug level, each orthogonalized name with its indices as *, and its count, named + without the torch.compile and activation-checkpoint wrappers.""" + monkeypatch.setattr(logging.getLogger("kempnerforge"), "propagate", True) + model = self._model(n_layers=2, num_experts=4, moe_top_k=2) + if wrapper == "compile": + model = torch.compile(model) + elif wrapper == "checkpoint": + assert apply_ac(model, "full") == 2 + with caplog.at_level(logging.DEBUG, logger="kempnerforge.training.optimizer"): + build_optimizer(model, OptimizerConfig(name="muon")) + [logged] = [ + r.getMessage() + for r in caplog.records + if r.name == "kempnerforge.training.optimizer" and r.levelno == logging.DEBUG + ] + assert logged.startswith("Muon orthogonalizes layers.*.attention.k_proj.weight (2), ") + assert "layers.*.mlp.experts.*.up_proj.weight (8)" in logged + assert "router" not in logged + assert "output_head" not in logged + + def test_build_skips_the_names_without_debug_logging(self, caplog, monkeypatch): + """Above debug level, the build neither computes nor logs the names it orthogonalizes, + whole or one expert at a time.""" + monkeypatch.setattr(logging.getLogger("kempnerforge"), "propagate", True) + looked_up = [] + + def name_patterns(model: nn.Module, params: list[torch.Tensor]) -> str: + looked_up.append(params) + return "" + + monkeypatch.setattr("kempnerforge.training.optimizer._name_patterns", name_patterns) + model = self._model(num_experts=4, moe_top_k=2, moe_packed_experts=True) + with caplog.at_level(logging.INFO, logger="kempnerforge.training.optimizer"): + build_optimizer(model, OptimizerConfig(name="muon")) + levels = [r.levelno for r in caplog.records if r.name == "kempnerforge.training.optimizer"] + assert levels and logging.DEBUG not in levels + assert looked_up == [] + + @pytest.mark.parametrize("muon_packed_experts", [None, False, True]) + def test_packed_experts_follow_muon_packed_experts(self, muon_packed_experts): + """Packed 3-D expert weights go to Muon in batched groups after the others, by default + and with muon_packed_experts, and to AdamW with it off.""" model = self._model(num_experts=4, moe_top_k=2, moe_packed_experts=True) moe = model.layers["0"].mlp - _, adam = _split(build_optimizer(model, OptimizerConfig(name="muon"))) + packed = {moe.up_w, moe.down_w, moe.gate_w} + options = {"muon_packed_experts": muon_packed_experts} + if muon_packed_experts is None: + options = {} + optimizer = build_optimizer(model, OptimizerConfig(name="muon", **options)) + muon, adam = _split(optimizer) + batched = [bool(group.get("batched")) for group in optimizer.param_groups] + if muon_packed_experts is not False: + stacks = {p for g in optimizer.param_groups if g.get("batched") for p in g["params"]} + assert stacks == packed + assert not packed & adam + assert batched == sorted(batched) and batched[0] is False + else: + assert packed <= adam + assert not packed & muon + assert not any(batched) + + def test_packed_experts_keep_their_modules_rate(self): + """Under lr_multipliers, a batched group keeps the module, rate and decay of the group + it came from.""" + model = self._model(num_experts=4, moe_top_k=2, moe_packed_experts=True) + moe = model.layers["0"].mlp + config = OptimizerConfig( + name="muon", lr=0.02, muon_packed_experts=True, lr_multipliers={"experts": 0.5} + ) + optimizer = build_optimizer(model, config, module_patterns={"experts": ["layers.*.mlp.*"]}) + [batched] = [group for group in optimizer.param_groups if group.get("batched")] + assert set(batched["params"]) == {moe.up_w, moe.down_w, moe.gate_w} + assert batched["module"] == "experts" + assert batched["lr"] == pytest.approx(0.01) + assert batched["weight_decay"] == config.weight_decay + + def test_packed_experts_in_a_module_marked_always_use_adam(self): + """A module marked "always" leaves its packed expert weights to AdamW under + muon_packed_experts too.""" + moe = build_moe(dim=16, hidden_dim=48, num_experts=4, top_k=2, packed_experts=True) + moe.muon_exempt = "always" + holder = nn.ModuleDict({"moe": moe, "proj": nn.Linear(16, 16, bias=False)}) + config = OptimizerConfig(name="muon", muon_packed_experts=True) + muon, adam = _split(build_optimizer(holder, config)) assert {moe.up_w, moe.down_w, moe.gate_w} <= adam + assert muon == {holder["proj"].weight} + + @pytest.mark.parametrize("adjust_lr", ["original", "match_rms_adamw", "spectral_unclamped"]) + def test_packed_experts_step_as_the_same_experts_unpacked(self, adjust_lr): + """From the same seed, two steps with muon_packed_experts move each packed expert as + they move it unpacked, up to rounding.""" + tokens = torch.randn(2, 16, 16, generator=torch.Generator().manual_seed(1)) + layers = [] + for packed in (False, True): + torch.manual_seed(0) + moe = build_moe(dim=16, hidden_dim=48, num_experts=4, top_k=2, packed_experts=packed) + config = OptimizerConfig( + name="muon", lr=0.02, muon_packed_experts=True, muon_adjust_lr=adjust_lr + ) + optimizer = build_optimizer(moe, config) + start = {name: p.detach().clone() for name, p in moe.named_parameters()} + for _ in range(2): + moe(tokens).square().mean().backward() + optimizer.step() + optimizer.zero_grad() + moved = {name: (p - start[name]).abs().max() for name, p in moe.named_parameters()} + assert min(moved.values()) > 1e-3, moved + layers.append(moe) + unpacked, packed_moe = layers + for index, expert in enumerate(unpacked.experts): + for name in ("up", "down", "gate"): + weight = getattr(expert, f"{name}_proj").weight + torch.testing.assert_close(getattr(packed_moe, f"{name}_w")[index], weight.T) + torch.testing.assert_close(packed_moe.router.gate.weight, unpacked.router.gate.weight) + + @pytest.mark.parametrize("muon_packed_experts", [False, True]) + def test_build_says_where_packed_experts_go(self, caplog, monkeypatch, muon_packed_experts): + """Left to AdamW, the build says which flag gives them to Muon; on Muon, its debug list + names them apart from the matrices it orthogonalizes whole.""" + monkeypatch.setattr(logging.getLogger("kempnerforge"), "propagate", True) + model = self._model(num_experts=4, moe_top_k=2, moe_packed_experts=True) + config = OptimizerConfig(name="muon", muon_packed_experts=muon_packed_experts) + with caplog.at_level(logging.DEBUG, logger="kempnerforge.training.optimizer"): + build_optimizer(model, config) + records = [r for r in caplog.records if r.name == "kempnerforge.training.optimizer"] + info = " ".join(r.getMessage() for r in records if r.levelno == logging.INFO) + [debug] = [r.getMessage() for r in records if r.levelno == logging.DEBUG] + each = ( + "; one expert at a time, layers.*.mlp.down_w (1), layers.*.mlp.gate_w (1), " + "layers.*.mlp.up_w (1)" + ) + assert ("optimizer.muon_packed_experts = true orthogonalizes them" in info) is not ( + muon_packed_experts + ) + assert debug.endswith(each) is muon_packed_experts class TestAdamW: diff --git a/tests/unit/test_orthogonalize.py b/tests/unit/test_orthogonalize.py index 4b4224e5d..ba4895f42 100644 --- a/tests/unit/test_orthogonalize.py +++ b/tests/unit/test_orthogonalize.py @@ -6,10 +6,17 @@ import torch import torch.nn as nn from torch.distributed.device_mesh import DeviceMesh, init_device_mesh -from torch.distributed.tensor import Replicate, Shard, distribute_tensor - -from kempnerforge.training.optimizer import Muon, _newton_schulz -from kempnerforge.training.orthogonalize import _row_chunks, orthogonalize_exact +from torch.distributed.fsdp import fully_shard +from torch.distributed.tensor import DTensor, Replicate, Shard, distribute_tensor + +from kempnerforge.config.schema import OptimizerConfig +from kempnerforge.model.moe import MoEMLP, build_moe +from kempnerforge.training.optimizer import Muon, _newton_schulz, build_optimizer +from kempnerforge.training.orthogonalize import ( + _row_chunks, + holds_whole_matrices, + orthogonalize_exact, +) from tests.gloo_ranks import gloo_group, spawn @@ -103,6 +110,78 @@ def _check_muon_rank(rank: int, world: int, port: int, orthogonalize: str, optio assert torch.equal(sharded.to_local(), expected) +def _check_packed_experts_rank(rank: int, world: int, port: int, orthogonalize: str) -> None: + """Train a packed MoE layer under FSDP2 for two Muon steps and compare with one process. + + Every rank sees the same tokens, so the gradient FSDP2 reduce-scatters is the one + process's, and FSDP2's ``Shard(0)`` leaves each rank two whole experts of the four. + """ + with gloo_group(rank, world, port): + mesh = init_device_mesh("cpu", (world,), mesh_dim_names=("dp_shard",)) + tokens = torch.randn(2, 16, 16, generator=torch.Generator().manual_seed(1)) + config = OptimizerConfig( + name="muon", + lr=0.02, + fused=False, + muon_packed_experts=True, + muon_orthogonalize=orthogonalize, + ) + + def train(shard: bool) -> MoEMLP: + torch.manual_seed(0) + moe = build_moe(dim=16, hidden_dim=48, num_experts=4, top_k=2, packed_experts=True) + if shard: + fully_shard(moe, mesh=mesh) + optimizer = build_optimizer(moe, config) + for _ in range(2): + moe(tokens).square().mean().backward() + optimizer.step() + optimizer.zero_grad() + return moe + + sharded, single = train(shard=True), train(shard=False) + for name in ("up_w", "down_w", "gate_w"): + weight = getattr(sharded, name) + assert isinstance(weight, DTensor) and weight.placements == (Shard(0),) + rows = slice(2 * rank, 2 * rank + 2) + assert torch.equal(weight.to_local(), getattr(single, name).detach()[rows]), name + + +def _check_split_matrices_rank(rank: int, world: int, port: int) -> None: + """A stack split along its first dim holds whole matrices; one split inside them does not, + and exact Muon refuses it, while local Muon steps each rank's part of each matrix.""" + with gloo_group(rank, world, port): + mesh = init_device_mesh("cpu", (world,)) + full = torch.randn(2, 4, 8, generator=torch.Generator().manual_seed(0)) + assert holds_whole_matrices(full) + for placement, whole in ((Shard(0), True), (Replicate(), True), (Shard(1), False)): + assert holds_whole_matrices(distribute_tensor(full, mesh, [placement])) is whole + for orthogonalize in ("exact", "local"): + weight = nn.Parameter(distribute_tensor(torch.zeros(2, 4, 8), mesh, [Shard(2)])) + weight.grad = distribute_tensor(full, mesh, [Shard(2)]) + groups = [{"params": [weight], "batched": True}] + optimizer = Muon(groups, [{"params": []}], lr=0.1, orthogonalize=orthogonalize) + if orthogonalize == "exact": + split = r"weights of shapes \[\(2, 4, 8\)\] are split other than along" + with pytest.raises(RuntimeError, match=split): + optimizer.step() + continue + optimizer.step() + for matrix, grad in zip(weight.to_local(), weight.grad.to_local(), strict=True): + expected = -0.1 * _newton_schulz(grad) + torch.testing.assert_close(matrix, expected) + + +def _check_size_one_dim_rank(rank: int, world: int, port: int) -> None: + """A mesh dim of size one splits nothing, whatever dim its placement names; the dim of + size ``world`` splits the matrices when it shards inside them.""" + with gloo_group(rank, world, port): + mesh = init_device_mesh("cpu", (1, world)) + full = torch.randn(2, 4, 8, generator=torch.Generator().manual_seed(0)) + assert holds_whole_matrices(distribute_tensor(full, mesh, [Shard(1), Shard(0)])) + assert not holds_whole_matrices(distribute_tensor(full, mesh, [Shard(0), Shard(1)])) + + class TestRowChunks: @pytest.mark.parametrize(("rows", "world"), [(10, 4), (3, 4), (8, 2), (7, 3)]) def test_matches_torch_chunk(self, rows, world): @@ -140,3 +219,16 @@ def test_a_rank_without_rows_of_a_weight_steps_with_the_others(self, orthogonali def test_step_matches_unsharded_muon(self, orthogonalize, options): """Exact steps a shard as rows of the full matrix; local steps it as its own matrix.""" spawn(_check_muon_rank, 2, orthogonalize, options) + + +class TestMuonOnPackedExperts: + @pytest.mark.parametrize("orthogonalize", ["local", "exact"]) + def test_fsdp2_packed_experts_match_one_process(self, orthogonalize): + """Each rank holds whole experts, so both modes step them as one process does.""" + spawn(_check_packed_experts_rank, 2, orthogonalize) + + def test_exact_refuses_a_stack_split_inside_its_matrices(self): + spawn(_check_split_matrices_rank, 2) + + def test_a_mesh_dim_of_size_one_splits_no_matrix(self): + spawn(_check_size_one_dim_rank, 2)