[UCP] Load universal checkpoints across ZeRO stages #9080
All Vouch review confidence checks passed
Residual risk 0.28 = Change Risk (0.52) × (1 − Review Confidence (0.47)).
Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.52 · 650 lines diff across 8 files
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.02 · 1 substantive comment(s)
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 35%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size
diff_size
0.388
Shallow Review Depth
shallow_review_depth
0.344
Real PR Conversation Timeline
1 comments
"Review active on #9080"
general
weight: 0.35
jinyouzhi
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 a75ab891b each gap below surfaces once the previous one is worked around:| # | Direction | Error | Root cause |
|---|---|---|---|
| 1 | both |
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. || 2 | 3 → 1/2 |
AssertionError: Empty ds_version|_save_optimizer_state_stage3writes the inner optimizer dict, but ZeRO-3 keepsds_versionbeside it.DeepSpeedZeroOptimizer._load_global_stateasserts on it. || 3 | 3 → 1/2 |
IndexError: too many indices for tensor of dimension 1| The ZeRO-3 converter (merge_zero3_slices) writes each state as a bare flat tensor;load_hp_checkpoint_stateindexesckpt_dict[PARAM]. The stage-3 loader already accepts both forms. || 4 | 3 → 1/2 | step silently not restored | A ZeRO-3 source writes no per-parameter
step.pt; its step is inoptimizer_state_dict.state. || 5 | 1/2 → 3 |
KeyError: 'optimizer_state_dict'| The stage-3 loader reads the step andparam_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.- The same function returns the whole parameter when
tp_world_size == 1, wherechunkrejects a 0-D (scalar) parameter.- New
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.ZeROOptimizer.load_hp_checkpoint_state_from_checkpoint_dir(ZeRO-1/2 path):- rejects a checkpoint whose optimizer group count differs from the optimizer's, so
zipcannot pair a saved group with the wrong parameter group;- rejects a parameter directory that has exactly one of
exp_avg.pt/exp_avg_sq.pt, which would otherwise start one moment from zero;- restores each group's step from the per-parameter
step.pt, falling back to the global step when the source is ZeRO-3 (which writes no per-parameter step); a rank that holds no fragment for a group owns no local state for it, so no step is written there.stage3.load_hp_checkpoint_state_from_checkpoint_dir_stage3and_get_missing_sub_groups:- take
param_groupsfrom the top level when present (the ZeRO-3 converter writes it there too);- a sub-group with no moments at all starts without Adam state (a pre-first-step checkpoint); a group with only part of its moments, or a single parameter missing one of the two moment files, raises as a damaged checkpoint;
- every restored state gets its own step tensor.
load_universal_optimizer_stepreturns the per-group steps as a mapping (keyed by fp32 sub-group for a ZeRO-3 source, by parameter name for a ZeRO-1/2 source) instead of a single first-found step, and the ZeRO-3 target (stage3._seed_sub_group_step) and the ZeRO-1/2 target restore each sub-group from its own entry. A multi-task model can train its groups for different numbers of steps, so seeding every sub-group with one shared step would move the lagging group to the wrong counter.ds_to_universal.extract_zero_shards: iterate the group ids the rank actually saved (the saved state dict is keyed by those ids, and a rank that owns no fragment of a small group -- e.g. a scalar alone in group 0 -- omits it) instead of a positionalrange(len(...))that raisedKeyErroron the absent id when a checkpoint saved right after a cross-stage load was re-converted. Each rank still extracts exactly the fragments it owns, so the merged state is unchanged.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 the same guards.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/v1/checkpoint/test_universal_checkpoint_cross_stage.py(the v1 subtree the CI test fetcher scans) (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
TestUniversalCheckpointCrossStageScalarOwnGroup(world size 2): the cross-stage transitions with a trainable scalar in its own optimizer group, which leaves a ZeRO-1/2 rank without any fragment for that group. After the load, every state the rank owns keeps the source step and a rank with no fragment has no state for the group (a bare step with no moments would crash the nextoptimizer.step()in Adam's group init). After one more training step the owned steps advance by exactly one.New
TestUniversalCheckpointCrossStageScalarReConvert(world size 2): the scalar alone in group 0, saved immediately after a cross-stage load into ZeRO-1/2 (no optimizer step in between) and converted again -- the path that raisedKeyError: 0on a rank without the scalar's fragment. The re-converted checkpoint loads with the source step intact on every rank-owned group, and one more step advances it.New
TestUniversalCheckpointDivergentGroupSteps(world size 2): a shared trunk in one optimizer group and a trainable scalar in its own, the two groups' saved steps diverged by lowering only the scalar group'sstep.pt. After a ZeRO-1/2 → ZeRO-3 load, the scalar's sub-group carries its own (lowered) step while the trunk sub-groups carry the source step -- a loader that broadcast one shared step to every sub-group would restore the scalar to the trunk's counter.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.| Tree | B70 | NVIDIA L20 (driver 580.173.02, torch 2.14.1+cu130) |
|---|---|---|
| master a75ab891b | 4 failed (gap 1:
assert len(self.ckpt_list) > 0) | 4 failed, same assert || this PR | 4 passed | 4 passed |
TestUniversalCheckpointPipelineToZeRO3on 4× L20: fails on master a75ab891b at the same assert, passes with this PR.Regression on B70, master and this PR in the same environment:
| Tree | Result (219 tests) |
|---|---|
| master a75ab891b | 30 failed, 189 passed |
| this PR | 25 failed, 194 passed |
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:| Direction | Parameters | Mismatched (fp32, exp_avg, exp_avg_sq; exact) | Step after one more step |
|---|---|---|---|
| ZeRO-3 → ZeRO-1 | 310 | 0 | 3 |
| ZeRO-1 → ZeRO-3 | 310 | 0 | 3 |
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.extract_zero_shardsindexes the saved optimizer state by group, and a sub-group whose parameters never received a gradient has no entry. Loading such a target works (ZeRO-3 tolerates a missing moment pair), so the before-first-step coverage is one-directional (ZeRO-1/2 → ZeRO-3) for now.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.
Validation (2x H20, torch 2.13.0+cu130, fp32, torch.optim.Adam)
TestUniversalCheckpointAcrossZeROStages,BeforeFirstStepToZeRO3,AcrossZeROStagesRejects,CrossStageScalarOwnGroup,CrossStageScalarReConvertandDivergentGroupStepscombinations pass; the cross-stage file now passes 20/22 (2 skips: world-size-4 pipeline), and master'stests/unit/checkpoint/test_universal_checkpoint.pycontent is untouched and green. TheDivergentGroupStepscase fails on master (AssertionError: scalar group restored step 3, expected 2) and passes here, confirming it is the exact regression guard for the per-group step fix.