Repository navigation
Carry Muon's optimizer state through universal checkpoints - #8609
alanhuangyoo wants to merge 5 commits into
Conversation
cfd14b5 to
a9aead5
Compare
27ea17e to
9b15e2a
Compare
ghost
left a comment
There was a problem hiding this comment.
Independent validation of head 9b15e2a87cb638adcc61c484cc89841b68e53a14 on RTX 5090 (Python 3.12.13, PyTorch 2.13.0+cu130): all 19/19 cases in the new test_universal_optimizer_states.py suite passed.
| Checkpoint path | Topology / configurations | Result |
|---|---|---|
| Same-rank save → convert → resume | DP=2, ZeRO 1/2/3, CPU optimizer offload off/on | 6 passed |
| Resume with offload switched | DP=2, ZeRO 1/2/3, both switch directions | 6 passed |
| Resume on twice the ranks | DP=2 → DP=4, ZeRO 1/2/3, offload off/on | 6 passed |
| Missing whole-parameter momentum layout metadata | DP=2, ZeRO-2 | 1 passed; converter refused it as expected |
The positive cases train three steps, save and convert, reload, then compare two further steps with an uninterrupted reference. The fixtures feed the same input to each DP rank, so this does not cover different per-rank samples, TP/EP combinations, or a cross-ZeRO-stage restore.
For this run I overlaid the PR's exact changed files and same-head compatibility dependencies on installed DeepSpeed 0.19.7. The isolated tree also omitted an obsolete zeropp_loco_param constructor argument in the installed engine for the ZeRO-3 path. Thus this is a concrete validation of the tested paths, not a full exact-head checkout or an assertion about the untested configurations.
There was a problem hiding this comment.
Copilot review overview
🟡 Changes recommended
Padded ZeRO-1/2 states can fail conversion, group mismatches can silently corrupt ZeRO-3 settings, and one regression path can hang its distributed test.
Review effort: Balanced
Findings: 1
Open (3)
What changed in this PR
Adds universal-checkpoint support for Muon optimizer state across ZeRO stages and changing data-parallel sizes.
Changes:
- Discovers optimizer states dynamically instead of assuming Adam states.
- Records and restores ZeRO-1/2 whole-parameter momentum layouts.
- Restores ZeRO-3 group settings and adds tests/documentation.
| File | Description |
|---|---|
deepspeed/checkpoint/constants.py |
Defines whole-state metadata key. |
deepspeed/checkpoint/ds_to_universal.py |
Converts dynamic and whole-parameter states. |
deepspeed/checkpoint/universal_checkpoint.py |
Loads whole-parameter state slices. |
deepspeed/runtime/base_optimizer.py |
Passes whole-state metadata to loaders. |
deepspeed/runtime/zero/stage_1_and_2.py |
Saves and reconstructs Muon momentum. |
deepspeed/runtime/zero/stage3.py |
Discovers states and restores group settings. |
deepspeed/utils/tensor_fragment.py |
Stores loaded whole-parameter states. |
docs/_tutorials/universal-checkpointing.md |
Documents Muon checkpoint behavior. |
tests/unit/checkpoint/test_universal_optimizer_states.py |
Tests Muon conversion and resume. |
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
| if len(saved_groups) != len(self.optimizer.param_groups): | ||
| # No group to match each to, so fall back to copying the first, as before. | ||
| saved_groups = [saved_groups[0]] * len(self.optimizer.param_groups) |
There was a problem hiding this comment.
Kept this as a warning rather than an error. Copying the first group is what master already does on every load, so refusing would turn resumes that work today into ones that can't load at all. It now says so in the log instead of doing it silently (aaf6ebce). Matching groups per pipeline stage needs the converter to keep per-stage metadata, which I'd rather do separately.
| elif value.numel() == partition_numel: | ||
| flat_state[name] = value |
There was a problem hiding this comment.
Fixed on the current head (aaf6ebce). The trailing padding is stripped before the size check, and Muon's whole-parameter momentum is left alone because it isn't padded. test_a_padded_partition_converts uses an odd total size, so the last rank pads.
| if dist.get_rank() == 0: | ||
| for path in glob.glob(os.path.join(tmpdir, TAG, "*_optim_states.pt")): | ||
| checkpoint = torch.load(path, weights_only=False) | ||
| assert WHOLE_PARAM_OPTIMIZER_STATES in checkpoint[OPTIMIZER_STATE_DICT] | ||
| del checkpoint[OPTIMIZER_STATE_DICT][WHOLE_PARAM_OPTIMIZER_STATES] | ||
| torch.save(checkpoint, path) | ||
| with pytest.raises(ValueError, match=WHOLE_PARAM_OPTIMIZER_STATES): | ||
| _convert(tmpdir) | ||
| dist.barrier() |
There was a problem hiding this comment.
Fixed. Conversion runs on rank 0, and if it fails, every rank fails with it, so nothing is left waiting at the barrier.
Conversion read Adam's `exp_avg` and `exp_avg_sq` by name, so a checkpoint written by any other optimizer could not be converted: Muon keeps `momentum_buffer` and nothing else, and `ds_to_universal` raised `KeyError: 'exp_avg'` before writing anything. Extraction now takes the names from the param group's own state, the merge takes them from the fragment files, and the ZeRO-3 loader takes them per sub-group - per group rather than per checkpoint, because DeepSpeed splits a Muon run into two param groups and one checkpoint therefore holds `momentum_buffer` for the matrices and Adam's pair for the rest. The ZeRO-3 loader also takes the step from whichever group saved one, since the Muon half has none. A state that is not shaped like the ZeRO partition now stops the conversion with a message naming it. ZeRO-1/2 give Muon a momentum buffer the size of the whole group, replicated on every rank, because Newton-Schulz needs the whole matrix; slicing that by partition offsets would write fragments that are the right size and hold the wrong rows. Signed-off-by: alanhuangyoo <[email protected]>
Signed-off-by: alanhuangyoo <[email protected]>
ZeRO-1/2 keep Muon's momentum whole, per parameter, for every parameter a partition touches, because Newton-Schulz needs the whole matrix. A matrix that straddles two partitions is in both ranks' buffers, and the buffer is not shaped like the partition, so conversion refused it. The optimizer now records which of its states are laid out that way. The converter writes each parameter's whole state from every rank that holds it and checks the copies agree instead of concatenating them. The loader hands those states to the parameter whole, and ZeRO-1/2 rebuild each rank's buffer in the order of its own partition, which also makes a different data-parallel size work. ZeRO-3's universal load copied the first param group's hyperparameters onto every group. With Muon that ran the Adam half as a Muon group, so a resume diverged even though every state came back exactly. Each group now gets its own. A ZeRO-1/2 Muon checkpoint saved before the layout was recorded is refused rather than read by partition offsets. Signed-off-by: alanhuangyoo <[email protected]>
Signed-off-by: alanhuangyoo <[email protected]>
…ip, and warn on a param-group count mismatch Signed-off-by: alanhuangyoo <[email protected]>
9b15e2a to
aaf6ebc
Compare
ghost
left a comment
There was a problem hiding this comment.
Re-checked at aaf6ebce, following up on my validation run at 9b15e2a8.
The new commit looks right to me:
- The ZeRO-1/2 strip now skips the states recorded as whole-parameter.
test_a_padded_partition_convertscovers the odd-size last rank that the earlier head missed.
The branch conflicts with master now: #8891 added load_optimizer_states to load_hp_checkpoint_state, load_hp_checkpoint_state_from_checkpoint_dir and _load_universal_checkpoint. The three conflicts are mechanical. Keep both parameters.
- One semantic point for the rebase: in
_load_universal_checkpoint, call_restore_whole_param_optimizer_states()only whenload_optimizer_statesis true. As written it falls through to a no-op when nothing was loaded, because every piece isNone. An explicit check documents that a weights-only resume leaves Muon's momentum untouched. - I resolved it that way locally and ran
test_universal_optimizer_states.pyon CPU (gloo, up to 4 ranks), both at this head and merged onto master. Both trees give the same result.- 9 pass: ZeRO-1/2/3 resume on the same ranks and on twice the ranks without offload, the refusal of an unrecorded momentum layout, and the alignment-padding resume.
- The other 15 need DeepSpeed's CPU Adam or fused Adam op, which I can't build on my machine. That is every offload case, the padded conversion and the param-group warning. So those are not covered by my run.
On the ZeRO-3 param-group fallback (stage3.py:3605), I agree that refusing every count mismatch would break Adam resumes that work today. A narrower refusal would still catch the case this PR is about: refuse when either side has a group with use_muon.
- When the counts differ, there is no group to pair a Muon group with.
- Copying the first group's settings then silently runs the Adam half as Muon, or the reverse. That is the 3.2e-1 divergence in your description.
- Plain Adam mismatches would keep the warning.
Not for this PR, but related. Under ZeRO-1/2 Muon, the live-state accessors go through the tensor_fragment links, and those only link states shaped like the partition.
- On master with dp=2,
zero_optimizer_storage_shard(p, 'momentum_buffer')raisesmomentum_buffer not foundon the ranks that hold part ofp. A rank that holds none ofpgets an empty shard. - From reading
get_full_hp_param,safe_get_full_optimizer_statehas the same split: holders raise before the all-reduce, and a rank with no fragment goes straight into it.
The _whole_param_optimizer_states hook added here is the natural thing for those accessors to consult in a follow-up, so every rank refuses together.
|
|
||
| def _load_universal_checkpoint(self, checkpoint_folder, load_optimizer_states, load_from_fp32_weights): | ||
| self.load_hp_checkpoint_state_from_checkpoint_dir("bit16_groups", checkpoint_folder) | ||
| self._restore_whole_param_optimizer_states() |
There was a problem hiding this comment.
After rebasing onto #8891, call this only when load_optimizer_states is true, so a weights-only resume visibly leaves Muon's momentum alone.
| # settings, its own and the Adam half's, and copying the first onto both runs the Adam half | ||
| # as a Muon group. | ||
| saved_groups = optim_sd[OPTIMIZER_STATE_DICT]["param_groups"] | ||
| if len(saved_groups) != len(self.optimizer.param_groups): |
There was a problem hiding this comment.
A suggestion to refuse the count mismatch when either side has a use_muon group, and keep the warning for plain Adam. Same text as above.


Fixes #8608.
Universal checkpoints could not carry Muon's optimizer state at any ZeRO stage. With this they can at all three, including a resume on a different number of ranks.
#8633 is in now, so this is only its own four commits.
What was wrong
exp_avg/exp_avg_sqby name, so a Muon checkpoint failed withKeyError: 'exp_avg'.The change
whole_param_optimizer_statesin the optimizer checkpoint). The converter writes those per parameter from every rank that holds it and checks the copies agree. The loader rebuilds each rank's buffer in the order of its own partition, so a different dp size works.momentum_buffertakes scale power -1 for affine-mapped (TP) pieces, likeexp_avg. It is inSCALE_POWER_BY_STATEinaffine.py, the table conversion and restore share, rather than a second copy in the converter.Testing
2 and 4 H20s, fp32, the same batch on every rank, clipping off. Train 3 steps, save, convert, resume, take 2 more steps, and compare with the run that never stopped. Bit-identical in every case:
Also checked offload now that #8464 is in. With offload, ZeRO-1/2 keep
momentum_bufferper partition like Adam's moments, so it converts the same way. All optimizer states come back bit-identical after loading, for ZeRO-1/2/3 with dp 2→4, 4→2, 2→1 and 1→2, and also with offload switched on or off between save and resume.test_universal_optimizer_states.pycovers offload now too.The new
tests/unit/checkpoint/test_universal_optimizer_states.pycovers stages 1 to 3 at 2→2 and 2→4, the refusal, a Muon resume at ZeRO-1/2 on matrices whose total size is odd (so the last rank pads), and the param-group warning. Undoing each fix makes its test fail: the ZeRO-3 group copy, the ZeRO-1/2 rebuild, and the staging fix from #8633, where the conversion reports the disagreeing copies.After rebasing onto the current master and the changes above, the new test file (24 cases),
test_universal_checkpoint.py(144) andtest_autoep_affine_universal.py(20) pass on H20. On a 2-GPU run the six 4-rank resume cases in the new file skip; they passed in an earlier 4-GPU run of the file, before the param-group test was added. Before the rebase: existing checkpoint tests (test_universal_checkpoint.pyin fp32,test_zero_optimizer.py,test_muon_checkpoint.py,test_autotp_uc_checkpoint.py): 169 passed. The one failure,TestRealCheckpointUniversalConversionTPxPP, fails the same way on master here (a Gloo process-group attribute missing in this torch build). These need pytest < 8.4 as pinned inrequirements-dev.txt;DistributedFixturedoes not resolve under pytest 9.Not covered
round_robin_gradientsand loaded with it diverges, for Adam on master as well. Fixed separately in Link ZeRO-1/2 fragments at their round-robin offsets #8637.Environment
NVIDIA H20-3e, driver 580.105.08, Python 3.11.15, torch 2.9.1+cu128.