Repository navigation
Restore frozen parameters and buffers on a universal checkpoint load - #9139
varun-projects wants to merge 1 commit into
Conversation
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>
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: 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) |
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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()} |
There was a problem hiding this comment.
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 👍 / 👎.
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_checkpointskippedload_module_state_dictentirely on the universal path (deepspeed/runtime/engine.py:4780before this change), because trainable weights come fromzero/<param>/fp32.ptinstead. That reasoning is sound for trainable weights, and under ZeRO-3 re-applyingcheckpoint['module']would be actively wrong, since it holds a(0,)placeholder per parameter.But
ds_to_universalonly writeszero/<param>/fp32.ptfor optimizer-owned parameters, and the universal readers are keyed off optimizer ownership too:enable_universal_checkpoint()attachesload_hp_checkpoint_stateonly tolp_param_groupmembers (deepspeed/runtime/zero/stage_1_and_2.py,deepspeed/runtime/bf16_optimizer.py), and the ZeRO-3 loader iteratesfp16_groups(deepspeed/runtime/zero/stage3.py). Frozen parameters and buffers are in none of those groups, andload_module_state_dictis the only code that callsmodule.load_state_dict()or appliesfrozen_param_fragments. So those tensors fell through every branch. The model-state files thatds_to_universalcopies 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.ptfor leftovermodulekeys including buffers, but nothing ever reads those files, and it casts withtensor.float(), which would corrupt the int64num_batches_trackedif it ever were read.Change
The universal path now restores exactly the remainder that the
zero/layout does not carry:strict=Falseso optimizer-owned parameters are still restored from their shards.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 reusesGatheredParametersrather than writing toparam.ds_tensordirectly, so partition size and padding offsets are not re-derived by hand.Pipeline-parallel universal checkpoints are unchanged by design:
ds_to_universaldoes 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:
[UCP] Load universal checkpoints across ZeRO stagestouches the same files but fixes cross-stage loading.Return frozen parameters, as fp32, from ZeRO-1, 2 and 3 checkpointsconcerns the dtype of frozen parameters inget_fp32_state_dict_from_zero_checkpoint, a different code path.offload_states()with frozen parameters.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 thelp_param_groupmechanism 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"deepspeed/runtime/engine.pyreverted to the base commit and the new test kept: 3 failed,AssertionError: frozen.weight was not restored, at all three stages.running_mean0.76,running_var0.17,num_batches_tracked2.0, frozenweight0.35, frozenbias0.24), 0 after, at every stage.exclude_frozen_parameters=Trueat save: buffers still restore, and the deliberately omitted frozen weights are named in the warning instead of diverging silently.TestZeROUniversalCheckpointDP(fp32,sub_group_size=-1slice, DP 2->2, 4->2, 2->4): 12 passed, 12 errors. Every error isError building extension 'fused_adam'withcode=127, i.e. theuse_torch_adam=Falsecells failing because this host has no C++ compiler; alluse_torch_adam=Truecells 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_sizemodel-state files once per universal load to merge the frozen fragments. A converter-side merge inds_to_universalwould 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:
FusedAdam/DeepSpeedCPUAdam(no compiler on this host; adjacent suites needing them error identically on an unmodified tree).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