Skip to content

Keep the buffers a model names for fp32 in fp32 under ZeRO-3 - #8699

Merged
sfc-gh-truwase merged 7 commits into
deepspeedai:masterfrom
pengdurice:peng-keep-fp32-buffers-v1
Oct 9, 2026
Merged

sfc-gh-truwase merged 7 commits into
deepspeedai:masterfrom
pengdurice:peng-keep-fp32-buffers-v1

Conversation

@pengdurice

Copy link
Copy Markdown
Contributor

Keep the buffers a model names for fp32 in fp32 under ZeRO-3 (data_types.keep_in_fp32_modules)

Summary

Hugging Face transformers models list the tensors that must stay in fp32 in _keep_in_fp32_modules_strict
(and _keep_in_fp32_modules for fp16). transformers honors these lists when it loads a model by itself.
Under ZeRO-3 the lists are lost, so, for example, the MoE routing bias e_score_correction_bias of
DeepSeek-V3, GLM-4.5 and GLM-5 trains in bf16. bf16 cannot tell its values apart, so tokens are routed to
different experts than the model was trained with.

This PR adds data_types.keep_in_fp32_modules (default "auto": use the model's own lists) and keeps the
listed buffers in fp32. Listed parameters are left to a follow-up PR, because ZeRO-3 needs to hold
partitions of two dtypes for them.

Why the lists are lost

  1. deepspeed.zero.Init converts every floating tensor created inside the context to the training dtype,
    buffers included, even ones created with an explicit dtype=torch.float32
    (deepspeed/runtime/zero/partition_parameters.py:262-270, zero_wrapper_for_fp_tensor_constructor).
  2. transformers' ZeRO-3 loader then copies the checkpoint into those tensors in place
    (transformers/integrations/deepspeed.py, _load_state_dict_into_zero3_model: buf.copy_(state_dict[k])).
    It never reads the dtype plan it built from the lists, so the fp32 values are rounded to bf16.
  3. Without ZeRO-3 the engine already keeps buffers in their loaded dtype (Mixed-precision: per-policy param/buffer dtype cast (preserve fp32 buffers) #8066), unless buffer_dtype is set,
    in which case it casts the listed buffers as well.

How much it matters

The routing bias values sit close together at a large magnitude, where bf16 values are far apart
(checkpoint values, bf16 rounding computed per layer):

model experts distinct bias values per layer, fp32 -> bf16 (median layer) expert pairs whose order flips or ties
GLM-5.2 256 214 -> 7 45.9%
GLM-4.7-Flash 64 32 -> 4 64.0%
DeepSeek-V4-Flash 256 254 -> 6 64.8%
DeepSeek-V3.2 256 50 -> 50 0% (values near 0, rounding is small)

13 transformers models list e_score_correction_bias: axk1, axk2, deepseek_v3, deepseek_v32, dots1, exaone_moe,
glm4_moe, glm4v_moe, glm4_moe_lite, glm_moe_dsa, hy_v3, mimo_v2_flash, solar_open.

Measured on GLM-4.7-Flash (47 layers, real weights, book text, 1 node x 8 H200, ZeRO-3, bf16):

bias as ZeRO-3 leaves it (bf16) bias in fp32 (this PR)
distinct values, layer 1 3 23 (all of the checkpoint's)
loss at step 1, before any update, mean over 8 ranks 7.1479 6.5999
tokens routed to a different expert set (mean over 46 MoE layers) 34.7% 0

The same forward comparison without DeepSpeed (one GPU, transformers only, 320 sequences of 4096 tokens) gives
+0.52 to +0.60 nats from rounding the bias. After training starts, the difference in our 40-step runs was within
run-to-run noise; we did not test longer runs.

What this PR changes

file change
deepspeed/runtime/keep_in_fp32.py (new) read the model's lists (or the configured patterns), match names the way transformers does, convert buffers
deepspeed/runtime/config.py, constants.py data_types.keep_in_fp32_modules: "auto" (default), a list of name patterns, or []; validated
deepspeed/runtime/zero/partition_parameters.py zero.Init converts the listed buffers back to fp32 when a module's __init__ finishes, i.e. before a checkpoint is loaded into them; also for zero.Init(module=...)
deepspeed/runtime/engine.py the mixed-precision cast skips listed buffers when buffer_dtype is set, and upcasts a listed buffer that arrives in a lower precision
docs/_pages/config-json.md documents the key

Name matching follows transformers (core_model_loading.build_glob_alternation then re.search): * stands for
any characters and a pattern may match anywhere in the full name. With "auto", the lists are read from each
module that carries them; for a transformers model that is the PreTrainedModel, whose post_init has merged
its submodels' lists by the time zero.Init sees it.

Behavior change: with the default "auto", listed buffers are now fp32 under ZeRO-3. The cost is the buffers'
size, a few hundred floats per layer for the routing bias. "keep_in_fp32_modules": [] restores the old behavior.

Tests

New tests/unit/v1/half_precision/test_keep_in_fp32_modules.py:

  • name matching: "auto" under bf16 and fp16, explicit patterns with *, [] and fp32 training select nothing,
    invalid settings are rejected;
  • ZeRO-3 zero.Init (2 ranks): a value loaded after the build is kept exactly in fp32; with [] it is rounded as
    before; other buffers are unchanged; the buffer stays exact through deepspeed.initialize and training steps;
  • engine without zero.Init, ZeRO stages 0 and 3: buffer_dtype does not cast listed buffers; a listed buffer
    that arrives in bf16 is upcast; [] keeps the old behavior.

Run on 1 node x 8 NVIDIA H200, torch 2.8.0+cu126, transformers 5.15.1, on this branch (master c9e1b4d + this PR):

tests result
tests/unit/v1/half_precision/test_keep_in_fp32_modules.py 17 passed
tests/unit/v1/half_precision/test_mixed_precision_dtype.py, tests/unit/runtime/zero/test_zero_autocast_mixed_dtype.py, tests/unit/runtime/zero/test_zero_allreduce_fetch_params.py 39 passed

@pengdurice
pengdurice marked this pull request as ready for review September 29, 2026 17:17

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

Hi @pengdurice,
Thank you for fixing this critical issue! The overall change looks good, but I found an issue we should address before merging.

In "auto" mode, keep_in_fp32_pattern() reads the FP32 declarations only from the module passed to it. If that module is a wrapper and only its child model defines those declarations, the function misses them and returns None. As a result, the child model’s listed buffers can remain in BF16 instead of being kept in FP32.

I opened to a PR with a possible fix in case it's helpful. Feel free to use it directly or just as a reference for your own fix—whatever works best for you.

@pengdurice

Copy link
Copy Markdown
Contributor Author

Hi @pengdurice, Thank you for fixing this critical issue! The overall change looks good, but I found an issue we should address before merging.

In "auto" mode, keep_in_fp32_pattern() reads the FP32 declarations only from the module passed to it. If that module is a wrapper and only its child model defines those declarations, the function misses them and returns None. As a result, the child model’s listed buffers can remain in BF16 instead of being kept in FP32.

I opened to a PR with a possible fix in case it's helpful. Feel free to use it directly or just as a reference for your own fix—whatever works best for you.

@tohtana , thank you for the fix! the child module issue is bitting us more than once;-) Let me do a code scan and identify opportunities to fix it for all potential places;-)

@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 update! Looks good to me.

@pengdurice
pengdurice enabled auto-merge October 8, 2026 14:58
@pengdurice
pengdurice added this pull request to the merge queue Oct 8, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Oct 8, 2026
@sfc-gh-truwase
sfc-gh-truwase added this pull request to the merge queue Oct 9, 2026
Merged via the queue into deepspeedai:master with commit 7b91115 Oct 9, 2026
13 checks passed
banxingmjj pushed a commit to openanolis/DeepSpeed that referenced this pull request Nov 12, 2026
…speedai#8843)

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

<!-- r3 2026-10-15, new PR (follow-up to deepspeedai#8699). Branch
peng-keep-fp32-params-v2 (worktree
/fsx/peng/workspace/ds-keep-fp32-params-v2) on master 5f266e2. The
fork has an older peng-keep-fp32-params-v1
(3326216, never opened as a PR); this branch replaces it. Evidence:
memory note keep-in-fp32-modules-zero3; job IDs: SOURCES.md. -->

**Follows:** deepspeedai#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). deepspeedai#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 deepspeedai#8699
(merged, buffers). deepspeedai#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 1c862f7 + this change: 47 passed
                                                               # master 5f266e2 + 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).

---------

Signed-off-by: pengdurice <[email protected]>
@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 14, 2026
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.

3 participants