Skip to content

Carry Muon's optimizer state through universal checkpoints - #8609

Closed
alanhuangyoo wants to merge 5 commits into
deepspeedai:masterfrom
alanhuangyoo:fix/ucp-optimizer-state-keys
Closed

alanhuangyoo wants to merge 5 commits into
deepspeedai:masterfrom
alanhuangyoo:fix/ucp-optimizer-state-keys

Conversation

@alanhuangyoo

@alanhuangyoo alanhuangyoo commented Sep 20, 2026 •

Copy link
Copy Markdown
Contributor

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

  1. The converter and the ZeRO-3 loader read Adam's exp_avg / exp_avg_sq by name, so a Muon checkpoint failed with KeyError: 'exp_avg'.
  2. ZeRO-1/2 keep Muon's momentum whole per parameter, for every parameter a partition touches, because Newton-Schulz needs the whole matrix. That buffer is not shaped like the partition, and a matrix that straddles two partitions is in both ranks' buffers.
  3. ZeRO-3's universal load copied the first param group's hyperparameters onto every group. With Muon that runs the Adam half as a Muon group, so every state came back exactly and the resume still diverged (3.2e-1 on the norm's bias after two steps).

The change

  • The converter and both loaders take the state names from what the optimizer saved, per param group for ZeRO-1/2 and per sub-group for ZeRO-3.
  • ZeRO-1/2 record which states hold each parameter whole (whole_param_optimizer_states in 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.
  • ZeRO-3 gives each param group back its own hyperparameters.
  • A ZeRO-1/2 Muon checkpoint saved before the layout was recorded is refused. By size alone its buffer can look partition-shaped, and reading it that way writes the wrong rows without failing.
  • momentum_buffer takes scale power -1 for affine-mapped (TP) pieces, like exp_avg. It is in SCALE_POWER_BY_STATE in affine.py, the table conversion and restore share, rather than a second copy in the converter.
  • When the checkpoint and the optimizer have different numbers of param groups, ZeRO-3 still has nothing to match each saved group to and keeps applying the first one, but it now logs a warning saying so instead of doing it quietly.
  • Reading a ZeRO-1/2 checkpoint strips the alignment padding off every tensor state. That is right for Adam's moments, but Muon's momentum is whole per parameter and its padding is not at the end, so the strip cut the last parameter's momentum short and conversion failed on the last rank whenever the group size was not a multiple of the world size. The strip now leaves the states recorded as whole-parameter alone.

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:

  • ZeRO-1, 2 and 3 on the same ranks
  • dp 2→1, 1→2, 2→4 and 4→2 for ZeRO-1/2; 2→4 and 4→1 for ZeRO-3
  • ZeRO-1 ↔ ZeRO-2
  • bf16: ZeRO-2 2→2 and 2→4, ZeRO-1 on 4 → ZeRO-2 on 2

Also checked offload now that #8464 is in. With offload, ZeRO-1/2 keep momentum_buffer per 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.py covers offload now too.

The new tests/unit/checkpoint/test_universal_optimizer_states.py covers 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) and test_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.py in 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 in requirements-dev.txt; DistributedFixture does not resolve under pytest 9.

Not covered

  • Converting between ZeRO-1/2 and ZeRO-3. The engine looks for stage-specific model-state files, so this fails for Adam on master too.
  • AutoEP's converter still hard-codes Adam's state names.
  • A universal checkpoint saved without round_robin_gradients and 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.

@alanhuangyoo
alanhuangyoo force-pushed the fix/ucp-optimizer-state-keys branch 2 times, most recently from cfd14b5 to a9aead5 Compare September 23, 2026 04:41
@alanhuangyoo alanhuangyoo changed the title Follow the optimizer's own state names in universal checkpoints Carry Muon's optimizer state through universal checkpoints Sep 23, 2026
@alanhuangyoo
alanhuangyoo force-pushed the fix/ucp-optimizer-state-keys branch 2 times, most recently from 27ea17e to 9b15e2a Compare September 25, 2026 00:51

@ghost ghost left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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 High severity · 2 Medium severity

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.

Comment on lines +3583 to +3585
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)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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.

Comment on lines +150 to +151
elif value.numel() == partition_numel:
flat_state[name] = value

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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.

Comment on lines +189 to +197
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()

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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]>
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]>
…ip, and warn on a param-group count mismatch

Signed-off-by: alanhuangyoo <[email protected]>

@ghost ghost left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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_converts covers 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 when load_optimizer_states is true. As written it falls through to a no-op when nothing was loaded, because every piece is None. 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.py on 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') raises momentum_buffer not found on the ranks that hold part of p. A rank that holds none of p gets an empty shard.
  • From reading get_full_hp_param, safe_get_full_optimizer_state has 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()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

@auto-pr-labeler-with-jev auto-pr-labeler-with-jev Bot added the skip-gpu-test Requires positive evidence that every changed behavior can be validated without a GPU. label Nov 14, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

skip-gpu-test Requires positive evidence that every changed behavior can be validated without a GPU.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Universal checkpoint conversion only knows Adam's state keys, so a Muon checkpoint cannot be converted

2 participants