Repository navigation
Return frozen parameters, as fp32, from ZeRO-1, 2 and 3 checkpoints - #8378
vineethsaivs wants to merge 1 commit into
Conversation
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 13805fc9f7
ℹ️ 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".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| # Frozen parameters come out of the checkpoint in the dtype the model held them in, since | ||
| # the optimizer keeps no fp32 master copy of them. Cast here so the whole state_dict is | ||
| # fp32 as documented, the same way buffers are already upcast in parse_model_states. | ||
| return to_torch_tensor(state_dict, dtype=torch.float32) |
There was a problem hiding this comment.
I ran this against 13805fc in a clean container (torch 2.14.0+cpu). The fp32 contract argument holds for the export entry points, but this function has a third caller that is not an export path: deepspeed/runtime/engine.py:4561, inside DeepSpeedEngine._load_checkpoint.
if self.zero_optimization_partition_weights() and not load_optimizer_states and not self.has_moe_layers:
checkpoint['module'] = get_fp32_state_dict_from_zero_checkpoint(load_dir)One positional argument, so no lazy_mode and exclude_frozen_parameters stays False. A ZeRO-3 load with load_optimizer_states=False now materializes every frozen parameter as fp32 on every rank. Same call shape, one frozen bf16 base plus a small fp32 adapter:
master 80f19f30d base.weight bfloat16 8.00 MiB total 8.01 MiB
PR 13805fc9f base.weight float32 16.00 MiB total 16.01 MiB
Those tensors are cast again when they land in the model, so this is extra CPU memory rather than a wrong result, and it costs most on frozen-base runs, which are exactly the ones carrying the most frozen bytes.
The docstring does promise fp32, so the engine may be the caller in the wrong here. The smaller edit is to upcast where fp32 is actually promised, which after this change is load_state_dict_from_zero_checkpoint at :787; convert_zero_checkpoint_to_fp32_state_dict already gets there by passing dtype down the lazy path, so it needs nothing. That leaves the engine load reading what the checkpoint held.
I only exercised the synthesized state dict this function is handed, not a real ZeRO-3 checkpoint, and I did not measure the engine path end to end.
There was a problem hiding this comment.
You are right, fixed in 7360bb4.
get_fp32_state_dict_from_zero_checkpoint now takes dtype=torch.float32, and engine.py:4561 passes dtype=None, so the engine load reads what the checkpoint held, exactly as on master. The fp32 contract stays on the documented public path.
I kept the upcast as the default rather than moving it to load_state_dict_from_zero_checkpoint, because the docstring example calls this function directly and feeds the result to model.load_state_dict.
Test extended: test_fp32_state_dict_upcasts_frozen_params now also asserts dtype=None keeps the frozen bf16 and the trainable fp32. pytest tests/unit/checkpoint/test_convert_checkpoint.py: 5 passed, 1 skipped.
There was a problem hiding this comment.
Read 7360bb4: engine.py:4563 passes dtype=None, and to_torch_tensor returns the contiguous tensor untouched when dtype is falsy, so the engine load keeps the checkpoint dtype exactly as on master. Keeping the fp32 default here rather than moving it makes sense to me, the docstring example calls this function directly. I read the diff and did not rerun the memory measurement.
There was a problem hiding this comment.
Rebased onto master in 0ec936d. The branch had drifted into a conflict on engine.py: the DeepEP cleanup block it still carried has since landed upstream and been wrapped in a try/finally, so I took master's version there and this PR is back to just the dtype=None line. Converter tests are 5 passed, 1 skipped.
7360bb4 to
0ec936d
Compare
There was a problem hiding this comment.
Copilot review overview
🟢 Approval recommended
The implementation matches the documented FP32 contract and includes focused regression coverage without unresolved issues.
Review effort: Balanced
Findings: None
What changed in this PR
Ensures eager ZeRO checkpoint consolidation consistently returns FP32 tensors while preserving checkpoint dtypes for lazy and internal loading paths.
Changes:
- Adds configurable eager output dtype, defaulting to FP32.
- Avoids unnecessary upcasting during ZeRO-3 checkpoint loading.
- Adds regression coverage for frozen parameters and lazy behavior.
| File | Description |
|---|---|
deepspeed/utils/zero_to_fp32.py |
Applies the requested dtype during eager consolidation. |
deepspeed/runtime/engine.py |
Preserves stored dtypes during internal loading. |
tests/unit/checkpoint/test_convert_checkpoint.py |
Tests eager upcasting and dtype-preserving paths. |
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
|
The change itself reads fine to me. One thing in the diff: zero_to_fp32.py goes from mode 100755 to 100644, so the executable bit is dropped. Probably not intended, could you restore it (git update-index --chmod=+x)? |
|
Good catch, thanks. Restored the executable bit in 7db24fa; the same mode slip was on seven of my other DeepSpeed PRs, so I fixed those too. |
7db24fa to
680d5fb
Compare
|
Rebased in 680d5fb: master no longer calls this function from |
The optimizer keeps no fp32 master copy of a frozen parameter, so the checkpoint stores it in whatever dtype the model held it in. Both merge paths hand that tensor straight through, so a bf16 or fp16 run came back with a state_dict whose trainable parameters and buffers were fp32 while every frozen parameter was not, which is the common shape for LoRA-style training where the base model is frozen. Cast in the eager branch of get_fp32_state_dict_from_zero_checkpoint, which is the boundary that documents the fp32 contract. Lazy mode is left dtype-preserving on purpose: convert_zero_checkpoint_to_state_dict consumes it and applies its own --dtype, so upcasting there would both undo that option and cost a full fp32 copy of the frozen weights during conversion. Casting an already-fp32 tensor with Tensor.to returns the same object, so nothing is copied for the common case. Passing dtype=None keeps the checkpoint dtypes for callers that do not want the upcast. ZeRO-1 checkpoints also left frozen parameters out entirely: the engine only saved frozen_param_shapes and frozen_param_fragments when gradients were partitioned (stage 2 and up), while zero_to_fp32 reads stage 1 checkpoints through the same stage 2 path. get_fp32_state_dict_from_zero_checkpoint then returned no frozen parameters, and the non-strict load_state_dict_from_zero_checkpoint left them at whatever the target model held. Save them for every ZeRO stage. Fixes deepspeedai#5439. Signed-off-by: Vineeth Sai <vineethsai4444@gmail.com>
680d5fb to
d3b1b7c
Compare
get_fp32_state_dict_from_zero_checkpointdocuments itself as returning "a single fp32 consolidated state_dict", and its own usage example feeds the result straight tomodel.load_state_dict. For a bf16 or fp16 run it returns a mixed-dtype dict instead: trainable parameters and buffers are fp32, every frozen parameter is not.Reproduced against synthesized ZeRO-2 and ZeRO-3 checkpoints (world size 2, one trainable parameter, two frozen ones, one buffer):
Root cause
Trainable parameters come from the optimizer's fp32 master weights, so they are fp32 by construction. Buffers are upcast explicitly in
parse_model_states:A frozen parameter has no fp32 master copy:
DeepSpeedEngine._get_param_fragment_funcsavesparam.detach().cpu()(orparam.ds_tensor.detach().cpu()under ZeRO-3), so the fragment carries the model's dtype._zero2_merge_frozen_paramsand_zero3_merge_frozen_paramsthen place that tensor in the state dict unchanged, and the eager return path callsto_torch_tensor(state_dict)with no dtype, so nothing casts it.This is the usual shape for LoRA-style training, where the base model is frozen and only the adapter is trained, so most of the returned dict is the un-upcast half.
Fix
Pass
dtype=torch.float32in the eager branch, which is the boundary that carries the fp32 contract:Lazy mode is deliberately left dtype-preserving.
convert_zero_checkpoint_to_state_dictconsumes it and applies its own--dtype, so upcasting there would both undo that option and force a full fp32 copy of the frozen weights during conversion, which is exactly the memory that lazy mode exists to avoid.Tensor.toreturns the same object when the dtype already matches, so the trainable parameters and buffers are not copied.Test
tests/unit/checkpoint/test_convert_checkpoint.py::test_fp32_state_dict_upcasts_frozen_params, a CPU test in the same monkeypatched style as the existingtest_checkpoint_file_output_dtype. It asserts the eager path upcasts a bf16 frozen parameter and, in the same test, that lazy mode still hands it back as bf16 so the split above does not regress silently.1 failed before the change, 5 passed after; the 4 existing CPU tests in the file pass on both sides.
The wider check was a round-trip harness over synthesized ZeRO-2 and ZeRO-3 checkpoints (world sizes 1 to 4, odd numels, several parameter groups, frozen parameters, buffers, tied parameters, sharded and unsharded output, eager and lazy) comparing the reconstruction against the weights the checkpoint was built from. Values and shapes already round-trip in every case; dtype was the only thing that did not match the documented contract.
ZeRO-1 checkpoints drop frozen parameters (fixes #5439)
_save_checkpointand_save_moe_checkpointonly savedfrozen_param_shapesandfrozen_param_fragmentswhen gradients were partitioned (stage 2 and up), butzero_to_fp32reads stage 1 checkpoints through the same stage 2 path. So for ZeRO-1,get_fp32_state_dict_from_zero_checkpointreturned no frozen parameters, and the non-strictload_state_dict_from_zero_checkpointsilently left them at whatever the target model held. With 2 ranks, bf16 and a frozen middle layer, stage 1 returned 4 of 6 keys and a fresh model's frozen weight stayed off by 0.3506; stage 2 returned 6 of 6. The engine now saves them for every ZeRO stage.TestZeroToFP32now also runs stage 1, andtest_1_param_groupchecks that the consolidated dict itself has every parameter. Stage 1 with frozen params fails on master (KeyError: 'll.0.weight'); with the changetest_1_param_groupandtest_2_param_groupspass for stages 1, 2 and 3, frozen and not.test_convert_checkpoint.py: 11 passed, 7 skipped.Hardware: CPU only (macOS, torch 2.11, gloo, world size 2).
DistributedTestskips without an accelerator here, so the test methods ran directly under 2 spawned gloo processes, with torch Adam andsteps_per_printoff to avoid a CPU-only hang in this setup. Not run: GPU CI.