Repository navigation
Keep the buffers a model names for fp32 in fp32 under ZeRO-3 - #8699
Conversation
Signed-off-by: pengdurice <[email protected]>
Signed-off-by: Masahiro Tanaka <[email protected]>
Signed-off-by: Masahiro Tanaka <[email protected]>
tohtana
left a comment
There was a problem hiding this comment.
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.
Suggested fix for DeepSpeed#8699
@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
left a comment
There was a problem hiding this comment.
Thank you for the update! Looks good to me.
…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]>
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_modulesfor 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_biasofDeepSeek-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 thelisted 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
deepspeed.zero.Initconverts 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).(
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.
buffer_dtypeis 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):
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):
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
deepspeed/runtime/keep_in_fp32.py(new)deepspeed/runtime/config.py,constants.pydata_types.keep_in_fp32_modules:"auto"(default), a list of name patterns, or[]; validateddeepspeed/runtime/zero/partition_parameters.pyzero.Initconverts the listed buffers back to fp32 when a module's__init__finishes, i.e. before a checkpoint is loaded into them; also forzero.Init(module=...)deepspeed/runtime/engine.pybuffer_dtypeis set, and upcasts a listed buffer that arrives in a lower precisiondocs/_pages/config-json.mdName matching follows transformers (
core_model_loading.build_glob_alternationthenre.search):*stands forany characters and a pattern may match anywhere in the full name. With
"auto", the lists are read from eachmodule that carries them; for a transformers model that is the
PreTrainedModel, whosepost_inithas mergedits submodels' lists by the time
zero.Initsees 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:"auto"under bf16 and fp16, explicit patterns with*,[]and fp32 training select nothing,invalid settings are rejected;
zero.Init(2 ranks): a value loaded after the build is kept exactly in fp32; with[]it is rounded asbefore; other buffers are unchanged; the buffer stays exact through
deepspeed.initializeand training steps;zero.Init, ZeRO stages 0 and 3:buffer_dtypedoes not cast listed buffers; a listed bufferthat 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/unit/v1/half_precision/test_keep_in_fp32_modules.pytests/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