Skip to content

Keep the parameters a model names for fp32 in fp32 under ZeRO-3 - #8843

Merged
tohtana merged 10 commits into
deepspeedai:masterfrom
pengdurice:peng-keep-fp32-params-v2
Nov 12, 2026
Merged

tohtana merged 10 commits into
deepspeedai:masterfrom
pengdurice:peng-keep-fp32-params-v2

Conversation

@pengdurice

Copy link
Copy Markdown
Contributor

Keep the parameters a model names for fp32 in fp32 under ZeRO-3

Follows: #8699 (merged), which kept the listed buffers in fp32 and left the listed parameters to this PR.

Summary

Hugging Face transformers models name the tensors that must stay in fp32 (_keep_in_fp32_modules_strict, and
_keep_in_fp32_modules for fp16). #8699 added data_types.keep_in_fp32_modules (default "auto": the model's own
lists) and kept the listed buffers in fp32 under ZeRO-3. Listed parameters were still trained in bf16, because
ZeRO-3 flattens each sub-group into one buffer of one dtype. Examples of listed parameters: DeepSeek-V4's
hyper-connection weights, attention sinks and norms; gpt-oss's attention sinks.

This PR lets ZeRO-3 (without parameter offload) hold partitions of two dtypes, so listed parameters are stored,
gathered, updated and checkpointed in fp32 next to the bf16 or fp16 ones.

Duplicate check

Searched open and recent pull requests on 2026-10-15 ("keep_in_fp32", "fp32 modules", "mixed dtype"): only #8699
(merged, buffers). #8686 (reconstruction of shared-submodule parameters in ZeRO checkpoints) is unrelated.

The change

File What
deepspeed/runtime/keep_in_fp32.py keep_tensors_in_fp32(module, pattern, include_params=True) converts matching parameters too; a ZeRO-3 parameter is converted in its partition (ds_tensor), so later gathers return fp32 and a later checkpoint load writes exact fp32 values
deepspeed/runtime/zero/partition_parameters.py after a transformers model's own __init__ (when its fp32 list is complete), its already-partitioned parameters are converted in place, before any checkpoint is loaded; with parameter offload only buffers are kept
deepspeed/runtime/zero/stage3.py the training dtype is the first parameter that is not fp32; parameters kept in fp32 form sub-groups of their own (a sub-group is one flat buffer of one dtype), get their own flat gradient buffer (fp32 accumulation) and reduce their gradients in fp32; gradient buckets are sized per dtype
deepspeed/runtime/engine.py ZeRO-1/2 and no ZeRO: the engine's mixed-precision cast skips nothing new (those optimizers hold one dtype), keeps buffers, and warns that listed parameters are trained in the training dtype; an explicit parameter pattern below ZeRO-3 is refused
docs/_pages/config-json.md data_types.keep_in_fp32_modules now covers parameters (ZeRO-3) and buffers
tests/unit/v1/half_precision/test_keep_in_fp32_modules.py tests below

Measured

DeepSeek-V4-Flash, first 4 layers, ZeRO-3, bf16, 1 node: 54 listed parameters and 1 buffer are
fp32 and exact after loading (bf16 before); the run without a list is bitwise equal to master over 20 steps; with the
list the mean loss differs from master by -0.0063 (lower on 15 of 20 steps). Throughput and memory were not
measured separately; the listed parameters are norms, sinks and small mixing weights, a small share of each model.

Tests

Test Checks
TestZeroInitKeepsParamsFp32::test_loaded_values_survive under zero.Init, listed parameters keep exact fp32 checkpoint values after loading
TestZero3TrainsKeptParamsInFp32::test_update_below_bf16_resolution_is_kept (zero.Init on/off, contiguous gradients on/off, optimizer offload on/off, gradient accumulation 1/2) an update smaller than bf16's resolution survives in the fp32 parameter
TestZero3TrainsKeptParamsInFp32::test_all_reduce_fetch the fp32 and bf16 partitions are gathered with one all-reduce per dtype
TestZero3TrainsKeptParamsInFp32::test_checkpoint_round_trip save and load keep the fp32 parameters exact
TestZero3TrainsKeptParamsInFp32::test_param_offload_keeps_only_buffers with parameter offload only buffers are kept (one flat buffer of one dtype)
TestZero3Fp16KeptParams::test_fp16_trains fp16 with a loss scaler trains with fp32 listed parameters
TestStagesBelowThreeKeptParams ZeRO-0/1/2 cast listed parameters to the training dtype and keep buffers; an explicit parameter pattern is refused

Hardware: 1 node of 8 H200 (driver 580.126.09), torch 2.8.0+cu126, pytest 9.1.1.

pytest unit/v1/half_precision/test_keep_in_fp32_modules.py     # master 1c862f7df + this change: 47 passed
                                                               # master 5f266e26d + this change: 47 passed, exit 0

pre-commit run --files passes on every changed file. Regression runs at the time of the first version: identical pass counts with and without the change on test_zero, test_offload_states and
tests/unit/runtime/zero.

Compatibility

Cell Validated
ZeRO-3 bf16 and fp16, zero.Init on and off, optimizer offload on and off, gradient accumulation yes (tests)
ZeRO-3 with parameter offload buffers only, by design (tested)
ZeRO-0/1/2 listed parameters in the training dtype with a warning (tested)
Universal checkpoint conversion of fp32 listed parameters not run
Accelerators other than CUDA not run

AI assistance

This change, its tests and this description were prepared with AI assistance (Claude).

@pengdurice
pengdurice marked this pull request as ready for review October 29, 2026 22:03
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 29, 2026 •

Copy link
Copy Markdown

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-29T22:12:09.871194Z 1b64dab Draft marked ready
ℹ️ 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.

@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: 1b64dabf17

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

Comment on lines +1237 to +1239
params_by_dtype = collections.defaultdict(list)
for param in params_group:
params_by_dtype[param.ds_tensor.dtype].append(param)

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 Split SuperOffload subgroups by dtype

When offload_optimizer.super_offload=true and an optimizer group contains both a listed FP32 parameter and BF16/FP16 parameters, dynamic dispatch uses SuperOffloadOptimizer_Stage3._create_fp16_sub_groups, whose default-size branch still returns the mixed group. The new _set_fp16_partitioned_groups_flat then chooses the first parameter's dtype buffer and narrows it by the entire mixed-group size, which exceeds that per-dtype buffer and fails during initialization; the override needs to apply the same dtype split while maintaining its bookkeeping.

AGENTS.md reference: AGENTS.md:L19-L19

Useful? React with 👍 / 👎.

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.

fixed.

Comment thread deepspeed/runtime/keep_in_fp32.py Outdated
Comment on lines +96 to +98
partition = getattr(tensor, "ds_tensor", None)
if partition is not None:
partition.data = partition.data.float()

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 Convert hpZeRO secondary partitions to FP32

When a model is built under zero.Init with zero_hpz_partition_size > 1, _partition_param_sec has already created ds_secondary_tensor before this runs, but only ds_tensor is upcast here. hpZeRO all-gather explicitly selects the secondary tensor whenever it exists, so checkpoint-loaded values and the first forwards are reconstructed from the rounded BF16/FP16 copy despite the primary partition being FP32; upcast or invalidate the secondary partition as well.

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

Useful? React with 👍 / 👎.

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.

fixed.

Comment thread deepspeed/runtime/zero/stage3.py Outdated
Comment on lines +240 to +241
param_dtypes = [p.dtype for group in self.optimizer.param_groups for p in group['params']]
self.dtype = next((d for d in param_dtypes if d != torch.float32), param_dtypes[0])

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 Preserve the model dtype when all optimizer params are kept

When the caller optimizes only listed FP32 parameters—for example, a frozen BF16 backbone with only attention-sink parameters passed to the optimizer—param_dtypes has no non-FP32 entry and this sets self.dtype to FP32. _is_kept_in_fp32 consequently returns false for every parameter, so their gradients are reduced and accumulated using the configured BF16/FP16 defaults rather than FP32, silently defeating this option for parameter-only fine-tuning; derive the training dtype from the engine configuration or track matched parameters explicitly.

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

Useful? React with 👍 / 👎.

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.

fixed.

grad_buffer = grad_buffer.to(grad_partition.device, non_blocking=True)
elif get_accelerator().on_accelerator(grad_buffer):
grad_buffer.add_(grad_partition.to(self.gradient_accumulation_dtype).view(grad_buffer.shape))
grad_buffer.add_(grad_partition.to(grad_buffer.dtype).view(grad_buffer.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 Update overridden accumulation paths to use the buffer dtype

With gradient_accumulation_steps > 1, both SuperOffloadOptimizer_Stage3.partition_grads and ZenFlow's overlap_step replacement still cast later gradient partitions to the global gradient_accumulation_dtype instead of the destination buffer dtype. For a kept FP32 parameter under BF16/FP16 this rounds every microbatch after the first before addition, so the new FP32 accumulation guarantee only works on the base Stage3 path; mirror this dtype-aware conversion in both overrides.

AGENTS.md reference: AGENTS.md:L19-L19

Useful? React with 👍 / 👎.

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.

fixed.

A backward that raises leaves its gradients in the bucket until step(), so a retried backward adds those parameters again. A bucket sized to its parameters then reduces early with a parameter in it twice (test_zero_activation_checkpoint_lifecycle.py). Other buckets keep reduce_bucket_size, as before this PR. Also set optimizer.dtype in the AutoEP contiguous-gradient unit test, which builds the optimizer with object.__new__.

Signed-off-by: pengdurice <[email protected]>
…32, training dtype from the engine

SuperOffload now splits a parameter group by dtype before making sub groups. Converting a ZeRO-3 parameter to fp32 also converts its hpZ secondary partition, which the forward's all-gathers read until the first step. The engine passes its model dtype to the ZeRO-3 optimizer, so a run that optimizes only kept parameters still reduces and accumulates them in fp32. The SuperOffload and ZenFlow partition_grads overrides add in the buffer's dtype, as the base path does.

Signed-off-by: pengdurice <[email protected]>

@tohtana tohtana left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thank you for the important fix!

I see one blocking issue: keep_tensors_in_fp32() converts a primary partition carrying ds_quant_scale from INT8 storage to FP32 zero_quantized_nontrainable_weights=true, while leaving the quantization marker attached.

After deepspeed.zero.Init, you can check it with

partition = model.weight.ds_tensor
assert hasattr(partition, "ds_quant_scale")  # passed
assert partition.dtype == torch.int8         # failed: actual dtype was torch.float32

Can you address this before we merge?

With zero_quantized_nontrainable_weights, a frozen parameter's partition holds int8 codes and their scales (ds_quant_scale). keep_tensors_in_fp32 converted the codes to fp32 and kept the scales, so later gathers treated fp32 data as int8 codes. A listed parameter stored quantized now stays quantized, with a one-time warning, as listed parameters under parameter offload already stay in the training dtype.

Signed-off-by: pengdurice <[email protected]>
@pengdurice

Copy link
Copy Markdown
Contributor Author

Thank you for the important fix!

I see one blocking issue: keep_tensors_in_fp32() converts a primary partition carrying ds_quant_scale from INT8 storage to FP32 zero_quantized_nontrainable_weights=true, while leaving the quantization marker attached.

After deepspeed.zero.Init, you can check it with

partition = model.weight.ds_tensor
assert hasattr(partition, "ds_quant_scale")  # passed
assert partition.dtype == torch.int8         # failed: actual dtype was torch.float32

Can you address this before we merge?

Thanks for catching this. Fixed!

@tohtana tohtana added the needs-gpu-test GPU testing is recommended to validate the changes in this PR. label Nov 10, 2026

@tohtana tohtana left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Looks good to me, thank you!

@tohtana
tohtana added this pull request to the merge queue Nov 12, 2026
Merged via the queue into deepspeedai:master with commit 3fe2d95 Nov 12, 2026
24 of 28 checks passed
@tohtana tohtana removed the needs-gpu-test GPU testing is recommended to validate the changes in this PR. label Nov 14, 2026
banxingmjj pushed a commit to openanolis/DeepSpeed that referenced this pull request Nov 17, 2026
…dtype (deepspeedai#9099)

Fixes deepspeedai#9095. Since deepspeedai#8843, ZeRO-3 with NVMe parameter offload fails in
`deepspeed.initialize` for bf16 and fp32 models:

```
NotImplementedError: ZeRO-3 parameter offload keeps parameter partitions in one dtype; found [torch.bfloat16, torch.float16]
```

A partition swapped out to NVMe keeps a 1-element placeholder as
`ds_tensor`, and the swapper made that placeholder fp16 for every model
dtype. deepspeedai#8843 reads `ds_tensor.dtype` at init. The partitions on NVMe
then report fp16 while the small ones kept in CPU memory report bf16, so
they look like two dtypes. Now the placeholder takes the swapper's
dtype, which every swap buffer already has. fp16 models are unchanged.
The PR also adds an fp32 variant of `test_param_and_optimizer`, since
the existing tests use bf16 only.

---------

Signed-off-by: Xinyu Lian <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants