Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 42 additions & 14 deletions codebase-map.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": [
Expand Down Expand Up @@ -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)"
Expand Down Expand Up @@ -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"
Expand Down Expand Up @@ -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"
Expand All @@ -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",
Expand Down Expand Up @@ -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()",
Expand All @@ -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')",
Expand All @@ -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",
Expand Down Expand Up @@ -1965,7 +1984,7 @@
"classes": [
"TestModelConfig(23)",
"TestTrainConfig(24)",
"TestOptimizerConfig(6)",
"TestOptimizerConfig(7)",
"TestDistributedConfig(6)",
"TestCheckpointConfig(2)",
"TestSchedulerConfig(3)",
Expand All @@ -1984,7 +2003,7 @@
"TestChecksReadTheMergedLayers(7)",
"TestDerivedDefaultsFollowTheMergedLayers(3)"
],
"count": 173
"count": 174
},
"tests/unit/test_training.py": {
"classes": [
Expand Down Expand Up @@ -2082,7 +2101,7 @@
"TestCheckpointManagerLoad(3)",
"TestResumeWithUnsteppedParameters(18)",
"TestFreshIfUnheld(9)",
"TestMuonResume(26)",
"TestMuonResume(30)",
"TestSaveBeforeFirstStep(21)",
"TestResumeWithoutTrainState(10)",
"TestResumeWithoutTrainStateAcrossRanks(2)",
Expand All @@ -2096,7 +2115,7 @@
"TestTornStageAcrossRanks(1)",
"TestOptimizerTypeChangeOnResume(6)"
],
"count": 381
"count": 385
},
"tests/unit/test_checkpoint_publish.py": {
"classes": [
Expand Down Expand Up @@ -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",
Expand Down
17 changes: 11 additions & 6 deletions docs/checkpointing/dcp-model.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions docs/configuration/config-sections.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
29 changes: 29 additions & 0 deletions docs/how-to/build-a-model.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
13 changes: 8 additions & 5 deletions docs/how-to/compare-optimizers.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`:

Expand Down
6 changes: 5 additions & 1 deletion docs/how-to/moe-experiments.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
6 changes: 6 additions & 0 deletions docs/moe/capacity-and-dispatch.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading
Loading