Skip to content

Return frozen parameters, as fp32, from ZeRO-1, 2 and 3 checkpoints - #8378

Open
vineethsaivs wants to merge 1 commit into
deepspeedai:masterfrom
vineethsaivs:fix/fp32-state-dict-frozen-params
Open

vineethsaivs wants to merge 1 commit into
deepspeedai:masterfrom
vineethsaivs:fix/fp32-state-dict-frozen-params

Conversation

@vineethsaivs

@vineethsaivs vineethsaivs commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

get_fp32_state_dict_from_zero_checkpoint documents itself as returning "a single fp32 consolidated state_dict", and its own usage example feeds the result straight to model.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):

stage 2: {'buf': float32, 'f_bf16': bfloat16, 'f_fp16': float16, 'trainable': float32}
stage 3: {'buf': float32, 'f_bf16': bfloat16, 'f_fp16': float16, 'trainable': float32}

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:

buffers = {k: v.float() for k, v in state_dict["module"].items() if k in buffer_names}

A frozen parameter has no fp32 master copy: DeepSpeedEngine._get_param_fragment_func saves param.detach().cpu() (or param.ds_tensor.detach().cpu() under ZeRO-3), so the fragment carries the model's dtype. _zero2_merge_frozen_params and _zero3_merge_frozen_params then place that tensor in the state dict unchanged, and the eager return path calls to_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.float32 in the eager branch, which is the boundary that carries the fp32 contract:

    if lazy_mode:
        return state_dict
    else:
        return to_torch_tensor(state_dict, dtype=torch.float32)

Lazy mode is deliberately left dtype-preserving. convert_zero_checkpoint_to_state_dict consumes 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.to returns 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 existing test_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_checkpoint and _save_moe_checkpoint only saved frozen_param_shapes and frozen_param_fragments when gradients were partitioned (stage 2 and up), but zero_to_fp32 reads stage 1 checkpoints through the same stage 2 path. So for ZeRO-1, get_fp32_state_dict_from_zero_checkpoint returned no frozen parameters, and the non-strict load_state_dict_from_zero_checkpoint silently 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.

TestZeroToFP32 now also runs stage 1, and test_1_param_group checks that the consolidated dict itself has every parameter. Stage 1 with frozen params fails on master (KeyError: 'll.0.weight'); with the change test_1_param_group and test_2_param_groups pass 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). DistributedTest skips without an accelerator here, so the test methods ran directly under 2 spawned gloo processes, with torch Adam and steps_per_print off to avoid a CPU-only hang in this setup. Not run: GPU CI.

@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: 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".

Comment thread deepspeed/utils/zero_to_fp32.py Resolved
Comment thread deepspeed/utils/zero_to_fp32.py Outdated
# 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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

@alanhuangyoo

Copy link
Copy Markdown
Contributor

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

@vineethsaivs

Copy link
Copy Markdown
Contributor Author

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.

@vineethsaivs

Copy link
Copy Markdown
Contributor Author

Rebased in 680d5fb: master no longer calls this function from DeepSpeedEngine._load_checkpoint, so the engine.py dtype=None line is dropped and the dtype=None opt-out stays on the public function.

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>
@vineethsaivs
vineethsaivs force-pushed the fix/fp32-state-dict-frozen-params branch from 680d5fb to d3b1b7c Compare November 20, 2026 06:39
@auto-pr-labeler-with-jev auto-pr-labeler-with-jev Bot added skip-gpu-test Requires positive evidence that every changed behavior can be validated without a GPU. and removed skip-gpu-test Requires positive evidence that every changed behavior can be validated without a GPU. labels Nov 20, 2026
@vineethsaivs vineethsaivs changed the title Return frozen parameters as fp32 from get_fp32_state_dict_from_zero_checkpoint Return frozen parameters, as fp32, from ZeRO-1, 2 and 3 checkpoints Nov 20, 2026
@auto-pr-labeler-with-jev auto-pr-labeler-with-jev Bot added skip-gpu-test Requires positive evidence that every changed behavior can be validated without a GPU. and removed skip-gpu-test Requires positive evidence that every changed behavior can be validated without a GPU. labels Nov 20, 2026

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.

Why not save frozen params unless: self.zero_optimization_stage() >= ZeroStageEnum.gradients?

4 participants