Skip to content

Restore frozen parameters and buffers on a universal checkpoint load - #9139

Open
varun-projects wants to merge 1 commit into
deepspeedai:masterfrom
varun-projects:fix/uc-frozen-params
Open

varun-projects wants to merge 1 commit into
deepspeedai:masterfrom
varun-projects:fix/uc-frozen-params

Conversation

@varun-projects

Copy link
Copy Markdown

Fixes #9134.

Loading a universal checkpoint never restored any tensor the optimizer does not own. Frozen parameters, BatchNorm running statistics and every other registered buffer silently kept the values of the freshly constructed model, with no warning. Trainable weights were restored correctly, so a resumed run looked healthy and was quietly wrong.

Root cause

_load_checkpoint skipped load_module_state_dict entirely on the universal path (deepspeed/runtime/engine.py:4780 before this change), because trainable weights come from zero/<param>/fp32.pt instead. That reasoning is sound for trainable weights, and under ZeRO-3 re-applying checkpoint['module'] would be actively wrong, since it holds a (0,) placeholder per parameter.

But ds_to_universal only writes zero/<param>/fp32.pt for optimizer-owned parameters, and the universal readers are keyed off optimizer ownership too: enable_universal_checkpoint() attaches load_hp_checkpoint_state only to lp_param_group members (deepspeed/runtime/zero/stage_1_and_2.py, deepspeed/runtime/bf16_optimizer.py), and the ZeRO-3 loader iterates fp16_groups (deepspeed/runtime/zero/stage3.py). Frozen parameters and buffers are in none of those groups, and load_module_state_dict is the only code that calls module.load_state_dict() or applies frozen_param_fragments. So those tensors fell through every branch. The model-state files that ds_to_universal copies into the universal folder still carry them.

Related, and left alone here: for stage <= 2 the converter's fallback loop already emits a zero/<name>/fp32.pt for leftover module keys including buffers, but nothing ever reads those files, and it casts with tensor.float(), which would corrupt the int64 num_batches_tracked if it ever were read.

Change

The universal path now restores exactly the remainder that the zero/ layout does not carry:

  • Buffers, and for ZeRO stage 1/2 frozen parameters, come from the copied model-state dict, filtered to those tensors and applied with strict=False so optimizer-owned parameters are still restored from their shards.
  • Under ZeRO-3 the model-state files hold each frozen parameter as one padded fragment per saved rank, so the fragments of all saved ranks are concatenated back into the whole parameter and handed to load_module_state_dict, which repartitions it for the current world size. Frozen parameters therefore survive a DP resize, which is the point of a universal checkpoint. This reuses GatheredParameters rather than writing to param.ds_tensor directly, so partition size and padding offsets are not re-derived by hand.
  • A tensor the checkpoint cannot supply, or whose saved shape does not match the live model (what a TP reshard looks like), is named in a warning instead of being loaded wrongly or ignored in silence. The missing warning was as much the bug as the missing load.

Pipeline-parallel universal checkpoints are unchanged by design: ds_to_universal does not copy the per-layer weight files, so the folder carries no source for these tensors. The load now warns instead of continuing quietly. Fixing that needs a converter-side change and is out of scope here.

Why this is not a duplicate

No open PR references #9134 (re-checked immediately before opening this one), and no open PR in the universal-checkpoint area addresses this defect:

Sibling paths checked

Per AGENTS.md: ZeRO stage 1/2 and stage 3 are separate implementations here and both were exercised; the fp16 and bf16 optimizer paths share the lp_param_group mechanism and bf16 was tested directly; the non-universal load path is unchanged and was re-verified.

Validation

Hardware and software: 1x aarch64 CPU host, no GPU and no C++ compiler, torch 2.15.0+cpu, Python 3.13, DS_ACCELERATOR=cpu, gloo backend, world_size=2.

DS_ACCELERATOR=cpu LOCAL_SIZE=4 PYTHONPATH=. python3.13 -m pytest \
  tests/unit/checkpoint/test_universal_checkpoint.py -q -k "FrozenParamsAndBuffers"
  • With this change: 3 passed (ZeRO stages 1, 2, 3). With deepspeed/runtime/engine.py reverted to the base commit and the new test kept: 3 failed, AssertionError: frozen.weight was not restored, at all three stages.
  • The issue's own reproducer: 5 tensors differ before (running_mean 0.76, running_var 0.17, num_batches_tracked 2.0, frozen weight 0.35, frozen bias 0.24), 0 after, at every stage.
  • ZeRO-3 DP resize 2->1, 2->2, 2->3, 4->2, with a frozen parameter whose numel (992) is not divisible by the world size so the padding tail is exercised: all tensors match. ZeRO-1/2 resize 2->1, 2->3, 4->2: all match.
  • bf16 frozen parameters, stages 1/2/3: differ before, match after.
  • exclude_frozen_parameters=True at save: buffers still restore, and the deliberately omitted frozen weights are named in the warning instead of diverging silently.
  • Non-universal load round-trip, stages 1/2/3: unchanged, still exact.
  • Adjacent suite TestZeROUniversalCheckpointDP (fp32, sub_group_size=-1 slice, DP 2->2, 4->2, 2->4): 12 passed, 12 errors. Every error is Error building extension 'fused_adam' with code=127, i.e. the use_torch_adam=False cells failing because this host has no C++ compiler; all use_torch_adam=True cells pass.
  • pre-commit run --files deepspeed/runtime/engine.py tests/unit/checkpoint/test_universal_checkpoint.py: all hooks pass.

This change affects checkpoint correctness, not numerics, throughput or memory, so no convergence or performance numbers are reported. The one performance consideration: under ZeRO-3 each rank now reads all dp_world_size model-state files once per universal load to merge the frozen fragments. A converter-side merge in ds_to_universal would avoid that but would not help already-converted checkpoints; happy to switch if maintainers prefer it.

Compatibility matrix

Validated: ZeRO stages 1, 2, 3; fp32 and bf16; DP resize (including an uneven partition); no offload; TP=1; non-pipeline; torch Adam.

Not validated, stated explicitly rather than implied:

  • Any GPU or vendor-accelerator path. No CUDA, no NCCL, no device of any kind was available.
  • fp16 (the CPU accelerator reports it unsupported, so those cells skip).
  • DeepSpeed FusedAdam / DeepSpeedCPUAdam (no compiler on this host; adjacent suites needing them error identically on an unmodified tree).
  • Tensor parallelism: the shape-mismatch guard is the intended behaviour for a TP reshard but was never exercised against a real one.
  • Pipeline parallelism: not fixed by this change, as described above.
  • CPU/NVMe offload, and MoE/AutoEP.

AI assistance

AI assistance was used for this change. The investigation, the patch and the regression test were produced with an AI coding agent, and the validation above was executed in that environment on the hardware stated. I want to be explicit about that rather than imply otherwise, and equally explicit that the unvalidated matrix cells listed above are real gaps, not omissions - in particular that nothing here has been exercised on a GPU. Reviewers should weigh the on-device evidence accordingly, and I am glad to run whatever additional validation maintainers consider necessary.

🤖 Generated with Claude Code

Loading a universal checkpoint never restored any tensor the optimizer
does not own. Frozen parameters, BatchNorm running statistics and every
other registered buffer silently kept the values of the freshly
constructed model, with no warning.

_load_checkpoint skipped load_module_state_dict entirely on the universal
path, because trainable weights are restored from zero/<param>/fp32.pt
instead. But ds_to_universal only writes those files for optimizer-owned
parameters, and the universal readers are keyed off optimizer ownership,
so nothing restored the rest. The model-state files that ds_to_universal
copies into the universal folder still carry them.

The universal path now restores exactly that remainder:

- Buffers and, for ZeRO stage 1/2, frozen parameters come from the copied
  model-state dict, filtered to the tensors the zero/ layout does not
  carry and applied with strict=False so optimizer-owned parameters are
  still restored from their shards.
- Under ZeRO-3 the model-state files hold frozen parameters as one
  padded fragment per saved rank, so the fragments of all saved ranks are
  concatenated back into the whole parameter and handed to
  load_module_state_dict, which repartitions it for the current world
  size. This keeps frozen parameters correct across a DP resize.
- A tensor the checkpoint cannot supply, or whose saved shape does not
  match the live model, is named in a warning instead of being loaded
  wrongly or ignored in silence.

Pipeline-parallel universal checkpoints are unchanged: ds_to_universal
does not copy the per-layer weight files, so the folder carries no source
for these tensors and the load now warns rather than continuing quietly.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Signed-off-by: varun-projects <4797069+varun-projects@users.noreply.github.com>
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 21, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-21T02:55:35.905904Z 4c9edac PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@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 21, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 4c9edaca78

ℹ️ 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".

continue
# Every rank pads its fragment up to a common partition size, so the padding of the
# whole parameter sits at the tail of the concatenation.
merged_params[name] = torch.cat(flat_fragments[name])[:param.ds_numel].view(param.ds_shape)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Dequantize frozen fragments before treating them as weights

When ZeRO-3 uses zero_quantized_nontrainable_weights, each frozen ds_tensor fragment contains int8 codes whose required scale lives separately in ds_quant_scale; flattening and concatenating the fragments discards that metadata. Passing this merged tensor to module.load_state_dict() therefore treats the code integers as model values and silently corrupts frozen base weights (a common LoRA setup) when they are repartitioned. Preserve and apply the scales, or detect this storage mode and avoid loading it as an ordinary tensor.

AGENTS.md reference: AGENTS.md:L38-L38

Useful? React with 👍 / 👎.

continue
# Every rank pads its fragment up to a common partition size, so the padding of the
# whole parameter sits at the tail of the concatenation.
merged_params[name] = torch.cat(flat_fragments[name])[:param.ds_numel].view(param.ds_shape)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Load NVMe-offloaded frozen fragments before reshaping

With ZeRO-3 offload_param.device=nvme and a swappable frozen parameter, checkpointing can serialize the short swapper placeholder from ds_tensor.data rather than the offloaded partition. Concatenating those placeholders yields fewer than param.ds_numel elements, so this unconditional view(param.ds_shape) raises during every universal restore of such a checkpoint instead of restoring or warning. Swap the partitions into real buffers before rebuilding them, or validate the merged element count and skip unsupported fragments.

AGENTS.md reference: AGENTS.md:L38-L38

Useful? React with 👍 / 👎.

saved_module_state = checkpoint['module'] or {}

named_buffers = dict(self.module.named_buffers())
expected_shapes = {name: named_buffers[name].shape for name in self._get_buffer_names()}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve duplicate names when collecting buffer shapes

If two distinct submodules legally register the same tensor as a persistent buffer, _get_buffer_names() returns both qualified names because it walks each child separately, but Module.named_buffers() defaults to remove_duplicate=True and supplies only the first name. Indexing named_buffers[name] for the second alias then raises KeyError before the universal checkpoint can load; collect buffers with duplicates retained (or derive the live shapes from the state dict) instead.

Useful? React with 👍 / 👎.

This branch has not been deployed

No deployments
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.

[BUG] Universal checkpoint load never restores frozen parameters or buffers

1 participant