Repository navigation
Conversation
A universal checkpoint converted from ZeRO-3 could not be loaded into ZeRO-1/2, and one converted from ZeRO-1/2 could not be loaded into ZeRO-3: - the engine looked only for the model-states file named by its own stage; - the ZeRO-3 converter dropped ds_version, which the ZeRO-1/2 loader asserts on; - the ZeRO-1/2 loader expected dict-wrapped states, but the ZeRO-3 converter writes bare flat tensors; - the step was read from where the target's own stage keeps it. Fall back to the other stage's file name on universal loads, copy ds_version in the converter, accept flat tensors when they fill the whole parameter, and read the step and param_groups from either layout. Signed-off-by: Jin, Youzhi <[email protected]>
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 2bec47662e
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
The ZeRO-3 universal loader applied the first saved parameter group to every optimizer group; it now restores each group from the saved group with the same index and raises if the counts differ. Both universal loaders gave every group or sub-group the same step tensor, which the optimizer advances in place once per group; each state now gets its own copy. The cross-stage test uses two parameter groups with different settings and a sub_group_size that splits ZeRO-3's groups, checks the restored settings, and checks that one step after the load advances every state's step once. Signed-off-by: Jin, Youzhi <[email protected]>
|
@jinyouzhi, as offered: a data point for the TP/PP cell of "Not validated cross-stage". A tensor- and pipeline-parallel ZeRO-1 source, loaded into ZeRO-3 through a universal checkpoint. Setup
Results
The pipeline engine writes one model-states file per stage and TP rank ( To check that the comparison can fail:
Script (run from the repository root:
|
The pipeline engine runs at most ZeRO-1, so a pipeline-parallel run reaches ZeRO-3 only through a universal checkpoint loaded across stages. The new test trains Megatron-style column- and row-parallel layers with TP=2 and PP=2 under ZeRO-1, converts the checkpoint, and loads it as ZeRO-3 over 4 data-parallel ranks. It checks that every weight and Adam moment matches the source's reassembled tensors bit for bit, that the settings and step are restored, and that the target keeps training. On master the load fails to find the model states file. Signed-off-by: Jin, Youzhi <[email protected]>
After the save, the TP2 x PP2 source keeps training for 3 steps. The ZeRO-3 target follows on the same micro-batches, each data-parallel rank taking one of the source's pair, and must match the source's loss, weights and both Adam moments after every step within fp32 tolerance. Rank 0 now shares the outcome of the conversion, so a converter failure fails every rank instead of leaving the others waiting at a barrier. Signed-off-by: Jin, Youzhi <[email protected]>
|
Thanks for the data point, and for checking that the comparison can fail. It covers more than the test I added. After your comment I added A 4-rank test from your script would be welcome. To keep it from overlapping, it could focus on what's new:
Feel free to push it to |
A source can describe how its TP shards split each parameter with the Megatron name patterns or with affine maps, as AutoTP does. Run the TP2 x PP2 ZeRO-1 to ZeRO-3 test both ways: the same column- and row-parallel layouts written as contiguous_split_map and replicated_map, checked against the same tensors put back together from the source. Signed-off-by: Achyuthan Sivasankar <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 234e007729
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| state_step = load_universal_optimizer_step(optim_sd, checkpoint_dir, self.param_names.values()) | ||
| for key in ["fp32", "exp_avg", "exp_avg_sq"]: |
There was a problem hiding this comment.
Handle optimizer groups with no saved Adam state
When a ZeRO-1/2 checkpoint is converted before a parameter group has ever received a gradient (for example, a checkpoint at step 0), ds_to_universal.main intentionally emits its fallback fp32.pt but no exp_avg.pt or exp_avg_sq.pt. After this new cross-stage step lookup, the ZeRO-3 loader still iterates those moment keys unconditionally, so load_hp_checkpoint_state() raises on the missing file instead of preserving the group's fresh optimizer state as the ZeRO-1/2 loader does; detect absent source state and leave or initialize that subgroup lazily.
AGENTS.md reference: AGENTS.md:L19-L19
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed: a ZeRO-1/2 checkpoint saved before the first step has no Adam state, ds_to_universal writes only fp32.pt, and the ZeRO-3 loader failed on the missing exp_avg.pt.
Fixed in e488d7a. A ZeRO-3 sub-group with no saved moments now loads only its fp32 master and starts without Adam state, as a fresh engine does; a sub-group with moments for only some of its parameters is refused. TestUniversalCheckpointBeforeFirstStepToZeRO3 covers ZeRO-1 and ZeRO-2 sources; it failed on the missing file before the fix.
There was a problem hiding this comment.
I confirmed that e488d7a handles a checkpoint saved before the first step. I also tried a trained ZeRO-2 checkpoint saved at step 2. I removed only exp_avg_sq.pt for every parameter in one target subgroup, leaving exp_avg.pt in place. ZeRO-3 loaded it, but after one update that subgroup was at step 1 while the intact subgroup was at step 3. In the reverse direction, ZeRO-1/2 loaded the incomplete pair and raised KeyError: 'exp_avg_sq' on the next step. Could you add a test that expects the load itself to reject an incomplete pair in both directions?
…has none Signed-off-by: Jin, Youzhi <[email protected]>
|
@jinyouzhi, here are the ZeRO-stage switches I said I'd run on a real model: one chain through the universal checkpoint, changing the ZeRO stage at every step and DP or TP along with it. Setup
Results (TP2×DP2 ZeRO-1 → DP4 ZeRO-3 → DP2 ZeRO-2 → DP4 ZeRO-1 → DP2 ZeRO-3)
One side note, which I haven't reproduced. In a first attempt with the converter's default worker pools (4 extract, 2 merge), converting the second checkpoint hung in "Extracting ZeRO fragments" until the job's time limit. That's the ZeRO-3 checkpoint saved after the load from ZeRO-1. The first checkpoint had converted fine with the same pools, and with one worker each the whole chain ran. It may well be unrelated to this PR, so I'm only noting it. |
|
Thank you @Achyuthan-S for the real-model chain. I added it to "Validated matrix cells" in the description: TP2 ZeRO-1 → ZeRO-3, ZeRO-2 ↔ ZeRO-3, and stage changes combined with a DP change, all bit-exact on Qwen3-0.6B. On the converter hang, I couldn't reproduce it. I ran the same sequence on 4× H20 (torch 2.13): ZeRO-1 save → This PR doesn't change the extraction step. Its only converter change copies |
tohtana
left a comment
There was a problem hiding this comment.
Thank you @jinyouzhi! With matching optimizer groups, I verified that all four cross-stage restores preserve the FP32 master weights and both Adam moments. Before merge, could you reject incomplete moment pairs and mismatched group counts at load time, and cover the scalar parameter case below?
| global_step = None | ||
|
|
||
| for i, (param_group, | ||
| loaded_param_group) in enumerate(zip(self.optimizer.param_groups, optim_sd['param_groups'])): |
There was a problem hiding this comment.
I saved a ZeRO-3 model with one optimizer group and loaded the same two layers into ZeRO-2 with one group per layer. The load succeeded, but the second layer kept its initial weights. Could you check the group counts before zipping them?
| f"layout, but the parameter loading it has shape {tuple(param.shape)}. A universal " | ||
| "checkpoint converted from ZeRO-3 can be loaded into ZeRO-1/2 only without tensor " | ||
| "parallelism.") | ||
| return tensor.view(param.shape) |
There was a problem hiding this comment.
With a trainable scalar such as nn.Parameter(torch.tensor(0.9)), an intact ZeRO-3 checkpoint fails to load into ZeRO-2 even at TP=1. The reshape produces a 0-D tensor, and the later chunk raises chunk expects at least a 1-dimensional tensor. Could you handle this case and check that the scalar and its Adam moments round-trip?
| state_step = load_universal_optimizer_step(optim_sd, checkpoint_dir, self.param_names.values()) | ||
| for key in ["fp32", "exp_avg", "exp_avg_sq"]: |
There was a problem hiding this comment.
I confirmed that e488d7a handles a checkpoint saved before the first step. I also tried a trained ZeRO-2 checkpoint saved at step 2. I removed only exp_avg_sq.pt for every parameter in one target subgroup, leaving exp_avg.pt in place. ZeRO-3 loaded it, but after one update that subgroup was at step 1 while the intact subgroup was at step 3. In the reverse direction, ZeRO-1/2 loaded the incomplete pair and raised KeyError: 'exp_avg_sq' on the next step. Could you add a test that expects the load itself to reject an incomplete pair in both directions?
A universal checkpoint converted from a ZeRO-3 run cannot be loaded into ZeRO-1/2, and one converted from a ZeRO-1/2 run cannot be loaded into ZeRO-3. This PR makes both directions load, with the fp32 master weights, Adam states and step restored exactly.
Reproduction
Train under one stage,
save_checkpoint, runds_to_universal, thenload_checkpoint(..., load_optimizer_states=True)withcheckpoint.load_universal: trueunder the other stage. On master a75ab89 each gap below surfaces once the previous one is worked around:assert len(self.ckpt_list) > 0_get_all_ckpt_namesglobs only the current stage's model-states name:zero_pp_rank_0_mp_rank_*_model_states.ptfor ZeRO-3,mp_rank_*_model_states.ptfor ZeRO-1/2. A universal load reads only metadata from this file, so either name works.AssertionError: Empty ds_version_save_optimizer_state_stage3writes the inner optimizer dict, but ZeRO-3 keepsds_versionbeside it.DeepSpeedZeroOptimizer._load_global_stateasserts on it.IndexError: too many indices for tensor of dimension 1merge_zero3_slices) writes each state as a bare flat tensor;load_hp_checkpoint_stateindexesckpt_dict[PARAM]. The stage-3 loader already accepts both forms.step.pt; its step is inoptimizer_state_dict.state.KeyError: 'optimizer_state_dict'param_groupsfromoptimizer_state_dict, which a ZeRO-1/2 source does not have (it has top-levelparam_groupsand per-parameterstep.pt).Changes
engine._get_all_ckpt_names: on a universal load with no match, glob the other stage's name, built by_get_ckpt_name(new optionalpartition_weightsargument).ds_to_universal._save_optimizer_state_stage3: copyds_versionintozero/optimizer_state.pt.universal_checkpoint.py:load_hp_checkpoint_stateviews a bare flat tensor as the parameter's shape. A flat tensor carries no TP layout, so if it does not fill the whole parameter (ZeRO-3 source → ZeRO-1/2 with TP>1) it raises aValueErrorsaying so, instead of anIndexError.load_universal_optimizer_stepreads the step from either layout. It is used by the ZeRO-1/2 path (ZeROOptimizer.load_hp_checkpoint_state_from_checkpoint_dir, when nostep.ptexists) and by the ZeRO-3 path.stage3.load_hp_checkpoint_state_from_checkpoint_dir_stage3: takeparam_groupsfrom the top level when present (the ZeRO-3 converter has always written it there too).Same-stage loads take the same paths as before: every new branch is reached only when the old lookup finds nothing.
Sibling paths checked:
BF16_Optimizersharesload_hp_checkpoint_state_from_checkpoint_dirand its_load_global_stateis a no-op, so it gets fixes 3 and 4 and is unaffected by 2.stage_1_and_2andstage3are both patched.Not a duplicate
No existing issue or PR covers cross-stage universal loading. #9069 also touches bare flat tensors but fixes the ZeRO-3 + AutoTP load path, not ZeRO-1/2 targets. #7546, #8848 and #8898 are different bugs.
Tests
New
TestUniversalCheckpointAcrossZeROStagesintests/unit/checkpoint/test_universal_checkpoint.py(world size 2, fp32,torch.optim.Adam), parametrized over (1→3), (2→3), (3→1), (3→2). It trains 2 steps, saves, converts, loads into the other stage, then checks:exp_avgandexp_avg_sqof every parameter aretorch.equalto the source (the conversion only moves fp32 data, so the comparison is exact);New
TestUniversalCheckpointPipelineToZeRO3(world size 4): the pipeline engine runs at most ZeRO-1, so a pipeline-parallel run reaches ZeRO-3 only this way. It trains Megatron-style column- and row-parallel layers with TP=2 × PP=2 under ZeRO-1, converts, and loads as ZeRO-3 over 4 data-parallel ranks. It checks that every weight and Adam moment istorch.equalto the source's TP blocks put back together and that the learning rate and step are restored. It then trains the target 3 more steps on the micro-batches the source used after its save, and after every step compares the loss, weights and both moments with the source run that never stopped (assert_close, fp32 tolerance: the TP all-reduces sum in a different order).Hardware: Intel Arc Pro B70 (XPU), Linux 6.19.10 in-tree
xedriver, compute runtime 26.27.39122.11, torch 2.14.0.dev20260804+xpu. Run from the repo root.assert len(self.ckpt_list) > 0)TestUniversalCheckpointPipelineToZeRO3on 4× L20: fails on master a75ab89 at the same assert, passes with this PR.Regression on B70, master and this PR in the same environment:
TestUniversalCheckpointAcrossZeROStagescases.TestZeROUniversalCheckpointDPwith ZeRO-1 andload_optim=True: the bit-exact optimizer-state check fails intermittently on this XPU setup. Which cases fail changes from run to run; re-running 7 of them gave 5/7 failures with this PR and 4/7 and 5/7 on master.TestRealCheckpointUniversalConversionTPxPP:No backend type associated with device type xpu.End to end on B70 (2 ranks): Qwen3-0.6B, bf16,
torch.optim.AdamW. Train 2 steps under one stage, save,ds_to_universal, load under the other stage, and comparesafe_get_full_fp32_param/safe_get_full_optimizer_statebefore and after:Validated matrix cells
exp_avgandexp_avg_sqof all 310 parameters (930 tensors) match bit for bit, both in the converted checkpoint and after the load; master stops at the first change. This adds TP2 ZeRO-1 → ZeRO-3, ZeRO-2 ↔ ZeRO-3, and stage changes combined with a DP change.Limitations
ds_version, so loading it into ZeRO-1/2 still fails the version assert; re-runds_to_universalon the original checkpoint.AI assistance
This PR was prepared with AI assistance (GitHub Copilot CLI), covering the root-cause analysis, the code, the tests and this description. I reviewed the changes and ran the tests reported above on the hardware listed.