← Back to Pull requests

[UCP] Load universal checkpoints across ZeRO stages #9080

Open
unknown opened this pull request with 650 lines diff across 8 files
View on GitHub
unknown unknown commented on Nov 13, 2026 09:13 UTC
Author

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, run ds_to_universal, then load_checkpoint(..., load_optimizer_states=True) with checkpoint.load_universal: true under 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_names globs only the current stage's model-states name: zero_pp_rank_0_mp_rank__model_states.pt for ZeRO-3, mp_rank__model_states.pt for 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_stage3 writes the inner optimizer dict, but ZeRO-3 keeps ds_version beside it. DeepSpeedZeroOptimizer._load_global_state asserts 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_state indexes ckpt_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 in optimizer_state_dict.state. |
| 5 | 1/2 → 3 | KeyError: 'optimizer_state_dict' | The stage-3 loader reads the step and param_groups from optimizer_state_dict, which a ZeRO-1/2 source does not have (it has top-level param_groups and per-parameter step.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 optional partition_weights argument).

  • ds_to_universal._save_optimizer_state_stage3: copy ds_version into zero/optimizer_state.pt.

  • universal_checkpoint.py:

  • - load_hp_checkpoint_state views 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 a ValueError saying so, instead of an IndexError.
    - The same function returns the whole parameter when tp_world_size == 1, where chunk rejects a 0-D (scalar) parameter.
    - New load_universal_optimizer_step reads the step from either layout. It is used by the ZeRO-1/2 path (ZeROOptimizer.load_hp_checkpoint_state_from_checkpoint_dir, when no step.pt exists) 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 zip cannot 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_stage3 and _get_missing_sub_groups:

  • - take param_groups from 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_step returns 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 positional range(len(...)) that raised KeyError on 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_Optimizer shares load_hp_checkpoint_state_from_checkpoint_dir and its _load_global_state is a no-op, so it gets the same guards. stage_1_and_2 and stage3 are 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 TestUniversalCheckpointAcrossZeROStages in tests/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:

  • fp32 master, exp_avg and exp_avg_sq of every parameter are torch.equal to the source (the conversion only moves fp32 data, so the comparison is exact);

  • the step is 2;

  • one more training step runs.
  • 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 next optimizer.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 raised KeyError: 0 on 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's step.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 is torch.equal to 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 xe driver, compute runtime 26.27.39122.11, torch 2.14.0.dev20260804+xpu. Run from the repo root.

    pytest -q tests/unit/v1/checkpoint/test_universal_checkpoint_cross_stage.py::TestUniversalCheckpointAcrossZeROStages
    

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

    TestUniversalCheckpointPipelineToZeRO3 on 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:

    pytest -q tests/unit/v1/checkpoint/test_universal_checkpoint_cross_stage.py tests/unit/checkpoint/test_autotp_uc_checkpoint.py tests/unit/checkpoint/test_autoep_affine_universal.py
    

    | Tree | Result (219 tests) |
    |---|---|
    | master a75ab891b | 30 failed, 189 passed |
    | this PR | 25 failed, 194 passed |

  • The 4 extra failures on master are the new TestUniversalCheckpointAcrossZeROStages cases.

  • All other failures occur on both trees and are unrelated to this change:

  • - TestZeROUniversalCheckpointDP with ZeRO-1 and load_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 compare safe_get_full_fp32_param / safe_get_full_optimizer_state before 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

  • Validated cross-stage: ZeRO 1/2 ↔ 3 with fp32 (unit test, XPU and CUDA) and ZeRO 1 ↔ 3 with bf16 (Qwen3-0.6B on XPU); DP=2; no offload. TP2 × PP2 ZeRO-1 → ZeRO-3 DP4 (unit test, CUDA).

  • Real-model chain by @Achyuthan-S (Qwen3-0.6B, bf16, 4× A100, 200 steps per layout): TP2×DP2 ZeRO-1 → DP4 ZeRO-3 → DP2 ZeRO-2 → DP4 ZeRO-1 → DP2 ZeRO-3. At every change the fp32 master, exp_avg and exp_avg_sq of 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.

  • Same-stage universal loads: covered by the regression suite above (DP resizing, AutoTP, AutoEP).

  • Not validated cross-stage: fp16, CPU/NVMe offload, MoE, ZeRO-3 → a TP>1 or pipeline-parallel target. The change has no device-specific code.
  • Limitations

  • A checkpoint converted from ZeRO-3 before this PR lacks ds_version, so loading it into ZeRO-1/2 still fails the version assert; re-run ds_to_universal on the original checkpoint.

  • ZeRO-3 source → ZeRO-1/2 target with TP>1 is not supported (the ZeRO-3 converter records no TP layout); it now fails with a clear error.

  • A ZeRO-3 source saved before the first optimizer step still cannot be converted: extract_zero_shards indexes 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)

  • All TestUniversalCheckpointAcrossZeROStages, BeforeFirstStepToZeRO3, AcrossZeROStagesRejects, CrossStageScalarOwnGroup, CrossStageScalarReConvert and DivergentGroupSteps combinations pass; the cross-stage file now passes 20/22 (2 skips: world-size-4 pipeline), and master's tests/unit/checkpoint/test_universal_checkpoint.py content is untouched and green. The DivergentGroupSteps case 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.
  • Diff: 650 lines (+487 / -163) across 8 files Reviewer: jinyouzhi Review duration: 25374m
    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
    0.52
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.02 · 1 substantive comment(s)
    0.02
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    46%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    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
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 46.7% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 52% (MEDIUM) · Higher = larger blast radius
    52%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 46.7% · Lower = rushed or shallow review
    46.7%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 27.7% · Safe to merge
    27.7%