Repository navigation
Mixed-precision: per-policy param/buffer dtype cast (preserve fp32 buffers) - #8066
Merged
Merged
Conversation
…ffers) Add data_types.param_dtype / buffer_dtype mirroring FSDP MixedPrecisionPolicy. Replace blanket module.half()/bfloat16() with a targeted cast so floating buffers (e.g. the rotary inv_freq) keep their loaded dtype unless buffer_dtype is explicitly set, matching HF/FSDP2 and avoiding RoPE precision drift. Signed-off-by: Olatunji Ruwase <[email protected]> Co-authored-by: Cursor <[email protected]> Signed-off-by: Olatunji Ruwase <[email protected]> Co-authored-by: Cursor <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 9aee8a9b8d
ℹ️ 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".
CPU unit tests cover dtype resolution and the targeted cast helper (params cast, fp32 buffers preserved unless buffer_dtype is set, zero-init param guard). A bf16 end-to-end test verifies the keys flow through DeepSpeedConfig and that the fp32 inv_freq buffer survives deepspeed.initialize. Signed-off-by: Olatunji Ruwase <[email protected]>
stas00
approved these changes
Jun 15, 2026
A data_types.param_dtype that disagrees with the fp16/bf16 enabled flag would cast params to a dtype the optimizer/master-weight/reduction paths (which derive the model dtype from those flags) do not expect. Validate config-only in _do_sanity_check so the run fails before any module cast or optimizer setup. Signed-off-by: Olatunji Ruwase <[email protected]> Co-authored-by: Cursor <[email protected]>
stas00
reviewed
Jun 15, 2026
stas00
left a comment
Collaborator
There was a problem hiding this comment.
probably should add these to the config md in the docs, no?
Co-authored-by: Stas Bekman <[email protected]>
Signed-off-by: Olatunji Ruwase <[email protected]>
PKUWZP
self-requested a review
June 16, 2026 16:57
Collaborator
|
@sfc-gh-truwase Can you check the formatting by running "pre-commit" and fix any formatting issues? Thanks for the PR! |
Signed-off-by: Stas Bekman <[email protected]>
stas00
reviewed
Jun 16, 2026
PKUWZP
approved these changes
Jun 16, 2026
This was referenced Jun 17, 2026
banxingmjj
pushed a commit
to openanolis/DeepSpeed
that referenced
this pull request
Jun 23, 2026
…ms_coalesced (deepspeedai#8073) This PR fixes the `_allgather_params_coalesced` method in `partition_parameters.py`. The change ensures that each `flat_tensor` is created with the correct data type by referencing the corresponding parameter in `param_list`, rather than always using the first parameter's data type. Fix deepspeedai#8072. ### Problem `_allgather_params_coalesced` allocates all output buffers using the dtype of the first parameter in param_list: ```python # before for psize in partition_sizes: flat_tensor = torch.empty(tensor_size, dtype=param_list[0].ds_tensor.dtype, ...) ``` This assumed every persistent parameter shares the same dtype. The assumption was incidentally maintained before 0.19.2 because `_configure_distributed_model` called `module.bfloat16()` unconditionally, normalising all persistent parameters (including PEFT LoRA adapters) to a uniform dtype. PR deepspeedai#8066 "Mixed-precision: per-policy param/buffer dtype cast (preserve fp32 buffers)" (commit b919284) correctly stopped casting ZeRO-Init model params, but exposed the latent bug: PEFT's default `autocast_adapter_dtype=True` keeps LoRA adapters in fp32 even when the base model is bf16. `persistent_parameters` therefore ends up with mixed dtypes (bf16 base-model params + fp32 LoRA params), and the mismatch between a bf16 output buffer and a fp32 input tensor raises: > TypeError: output tensor must have the same type as input tensor - Reported in: deepspeedai#8072 - Downstream tracking: huggingface/trl#6089 ### Solution Allocate each output buffer with the dtype of its own parameter: ```python # after for i, psize in enumerate(partition_sizes): flat_tensor = torch.empty(tensor_size, dtype=param_list[i].ds_tensor.dtype, ...) ``` This removes the shared-dtype assumption at the source rather than relying on upstream callers to normalise dtypes before calling `_allgather_params_coalesced`. ### Changes - Corrected tensor data type selection in `_allgather_params_coalesced` to use the data type of each parameter in `param_list`, ensuring proper handling of mixed data types. Signed-off-by: Albert Villanova del Moral <[email protected]>
xylian86
pushed a commit
to xylian86/DeepSpeed
that referenced
this pull request
Jun 25, 2026
…ffers) (deepspeedai#8066) ## Summary - Add `data_types.param_dtype` and `data_types.buffer_dtype` (both default `None`), mirroring FSDP `MixedPrecisionPolicy`. - Replace the blanket `module.half()` / `module.bfloat16()` in `_configure_distributed_model` with a targeted cast: parameters go to `param_dtype`; floating buffers keep their loaded dtype unless `buffer_dtype` is explicitly set. ## Motivation The blanket cast downcasts every floating buffer, including the rotary `inv_freq` buffer that HF/FSDP2 keep in fp32. On long contexts the bf16 `inv_freq` loses precision, RoPE angles drift, and logits/grads diverge from the FSDP2 reference. Preserving fp32 buffers by default fixes this; `buffer_dtype` is the escape hatch to reproduce the legacy behavior. ## Behavior - `param_dtype` unset -> derived from the fp16/bf16 enabled flag (legacy param behavior). - `buffer_dtype` unset -> buffers keep their loaded dtype (e.g. fp32 `inv_freq`). - `buffer_dtype` set -> buffers force-cast (legacy blanket-cast parity). ## Test plan - [ ] `param_dtype=bf16`, `buffer_dtype` unset -> params bf16, `inv_freq` stays fp32. - [ ] `buffer_dtype=bf16` -> buffers downcast (legacy parity). - [ ] bf16/fp16 run with neither key set behaves as before except fp32 buffers preserved. - [ ] 8B / 32B ZeRO-3 long-context run -> grad_norm tracks the FSDP2 reference. Made with [Cursor](https://cursor.com) --------- Signed-off-by: Olatunji Ruwase <[email protected]> Signed-off-by: Stas Bekman <[email protected]> Co-authored-by: Cursor <[email protected]> Co-authored-by: Olatunji Ruwase <[email protected]> Co-authored-by: Stas Bekman <[email protected]> Co-authored-by: Stas Bekman <[email protected]>
nathon-lee
pushed a commit
to nathon-lee/DeepSpeed_woo
that referenced
this pull request
Jul 1, 2026
…ffers) (deepspeedai#8066) ## Summary - Add `data_types.param_dtype` and `data_types.buffer_dtype` (both default `None`), mirroring FSDP `MixedPrecisionPolicy`. - Replace the blanket `module.half()` / `module.bfloat16()` in `_configure_distributed_model` with a targeted cast: parameters go to `param_dtype`; floating buffers keep their loaded dtype unless `buffer_dtype` is explicitly set. ## Motivation The blanket cast downcasts every floating buffer, including the rotary `inv_freq` buffer that HF/FSDP2 keep in fp32. On long contexts the bf16 `inv_freq` loses precision, RoPE angles drift, and logits/grads diverge from the FSDP2 reference. Preserving fp32 buffers by default fixes this; `buffer_dtype` is the escape hatch to reproduce the legacy behavior. ## Behavior - `param_dtype` unset -> derived from the fp16/bf16 enabled flag (legacy param behavior). - `buffer_dtype` unset -> buffers keep their loaded dtype (e.g. fp32 `inv_freq`). - `buffer_dtype` set -> buffers force-cast (legacy blanket-cast parity). ## Test plan - [ ] `param_dtype=bf16`, `buffer_dtype` unset -> params bf16, `inv_freq` stays fp32. - [ ] `buffer_dtype=bf16` -> buffers downcast (legacy parity). - [ ] bf16/fp16 run with neither key set behaves as before except fp32 buffers preserved. - [ ] 8B / 32B ZeRO-3 long-context run -> grad_norm tracks the FSDP2 reference. Made with [Cursor](https://cursor.com) --------- Signed-off-by: Olatunji Ruwase <[email protected]> Signed-off-by: Stas Bekman <[email protected]> Co-authored-by: Cursor <[email protected]> Co-authored-by: Olatunji Ruwase <[email protected]> Co-authored-by: Stas Bekman <[email protected]> Co-authored-by: Stas Bekman <[email protected]> Signed-off-by: nathon-lee <[email protected]>
nathon-lee
pushed a commit
to nathon-lee/DeepSpeed_woo
that referenced
this pull request
Jul 1, 2026
…ms_coalesced (deepspeedai#8073) This PR fixes the `_allgather_params_coalesced` method in `partition_parameters.py`. The change ensures that each `flat_tensor` is created with the correct data type by referencing the corresponding parameter in `param_list`, rather than always using the first parameter's data type. Fix deepspeedai#8072. ### Problem `_allgather_params_coalesced` allocates all output buffers using the dtype of the first parameter in param_list: ```python # before for psize in partition_sizes: flat_tensor = torch.empty(tensor_size, dtype=param_list[0].ds_tensor.dtype, ...) ``` This assumed every persistent parameter shares the same dtype. The assumption was incidentally maintained before 0.19.2 because `_configure_distributed_model` called `module.bfloat16()` unconditionally, normalising all persistent parameters (including PEFT LoRA adapters) to a uniform dtype. PR deepspeedai#8066 "Mixed-precision: per-policy param/buffer dtype cast (preserve fp32 buffers)" (commit b919284) correctly stopped casting ZeRO-Init model params, but exposed the latent bug: PEFT's default `autocast_adapter_dtype=True` keeps LoRA adapters in fp32 even when the base model is bf16. `persistent_parameters` therefore ends up with mixed dtypes (bf16 base-model params + fp32 LoRA params), and the mismatch between a bf16 output buffer and a fp32 input tensor raises: > TypeError: output tensor must have the same type as input tensor - Reported in: deepspeedai#8072 - Downstream tracking: huggingface/trl#6089 ### Solution Allocate each output buffer with the dtype of its own parameter: ```python # after for i, psize in enumerate(partition_sizes): flat_tensor = torch.empty(tensor_size, dtype=param_list[i].ds_tensor.dtype, ...) ``` This removes the shared-dtype assumption at the source rather than relying on upstream callers to normalise dtypes before calling `_allgather_params_coalesced`. ### Changes - Corrected tensor data type selection in `_allgather_params_coalesced` to use the data type of each parameter in `param_list`, ensuring proper handling of mixed data types. Signed-off-by: Albert Villanova del Moral <[email protected]> Signed-off-by: nathon-lee <[email protected]>
nathon-lee
pushed a commit
to nathon-lee/DeepSpeed_woo
that referenced
this pull request
Jul 1, 2026
…ffers) (deepspeedai#8066) ## Summary - Add `data_types.param_dtype` and `data_types.buffer_dtype` (both default `None`), mirroring FSDP `MixedPrecisionPolicy`. - Replace the blanket `module.half()` / `module.bfloat16()` in `_configure_distributed_model` with a targeted cast: parameters go to `param_dtype`; floating buffers keep their loaded dtype unless `buffer_dtype` is explicitly set. ## Motivation The blanket cast downcasts every floating buffer, including the rotary `inv_freq` buffer that HF/FSDP2 keep in fp32. On long contexts the bf16 `inv_freq` loses precision, RoPE angles drift, and logits/grads diverge from the FSDP2 reference. Preserving fp32 buffers by default fixes this; `buffer_dtype` is the escape hatch to reproduce the legacy behavior. ## Behavior - `param_dtype` unset -> derived from the fp16/bf16 enabled flag (legacy param behavior). - `buffer_dtype` unset -> buffers keep their loaded dtype (e.g. fp32 `inv_freq`). - `buffer_dtype` set -> buffers force-cast (legacy blanket-cast parity). ## Test plan - [ ] `param_dtype=bf16`, `buffer_dtype` unset -> params bf16, `inv_freq` stays fp32. - [ ] `buffer_dtype=bf16` -> buffers downcast (legacy parity). - [ ] bf16/fp16 run with neither key set behaves as before except fp32 buffers preserved. - [ ] 8B / 32B ZeRO-3 long-context run -> grad_norm tracks the FSDP2 reference. Made with [Cursor](https://cursor.com) --------- Signed-off-by: Olatunji Ruwase <[email protected]> Signed-off-by: Stas Bekman <[email protected]> Co-authored-by: Cursor <[email protected]> Co-authored-by: Olatunji Ruwase <[email protected]> Co-authored-by: Stas Bekman <[email protected]> Co-authored-by: Stas Bekman <[email protected]>
nathon-lee
pushed a commit
to nathon-lee/DeepSpeed_woo
that referenced
this pull request
Jul 1, 2026
…ms_coalesced (deepspeedai#8073) This PR fixes the `_allgather_params_coalesced` method in `partition_parameters.py`. The change ensures that each `flat_tensor` is created with the correct data type by referencing the corresponding parameter in `param_list`, rather than always using the first parameter's data type. Fix deepspeedai#8072. ### Problem `_allgather_params_coalesced` allocates all output buffers using the dtype of the first parameter in param_list: ```python # before for psize in partition_sizes: flat_tensor = torch.empty(tensor_size, dtype=param_list[0].ds_tensor.dtype, ...) ``` This assumed every persistent parameter shares the same dtype. The assumption was incidentally maintained before 0.19.2 because `_configure_distributed_model` called `module.bfloat16()` unconditionally, normalising all persistent parameters (including PEFT LoRA adapters) to a uniform dtype. PR deepspeedai#8066 "Mixed-precision: per-policy param/buffer dtype cast (preserve fp32 buffers)" (commit b919284) correctly stopped casting ZeRO-Init model params, but exposed the latent bug: PEFT's default `autocast_adapter_dtype=True` keeps LoRA adapters in fp32 even when the base model is bf16. `persistent_parameters` therefore ends up with mixed dtypes (bf16 base-model params + fp32 LoRA params), and the mismatch between a bf16 output buffer and a fp32 input tensor raises: > TypeError: output tensor must have the same type as input tensor - Reported in: deepspeedai#8072 - Downstream tracking: huggingface/trl#6089 ### Solution Allocate each output buffer with the dtype of its own parameter: ```python # after for i, psize in enumerate(partition_sizes): flat_tensor = torch.empty(tensor_size, dtype=param_list[i].ds_tensor.dtype, ...) ``` This removes the shared-dtype assumption at the source rather than relying on upstream callers to normalise dtypes before calling `_allgather_params_coalesced`. ### Changes - Corrected tensor data type selection in `_allgather_params_coalesced` to use the data type of each parameter in `param_list`, ensuring proper handling of mixed data types. Signed-off-by: Albert Villanova del Moral <[email protected]>
banxingmjj
pushed a commit
to openanolis/DeepSpeed
that referenced
this pull request
Oct 9, 2026
…edai#8699) # 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 (deepspeedai#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 | --------- Signed-off-by: pengdurice <[email protected]> Signed-off-by: Masahiro Tanaka <[email protected]> Co-authored-by: Masahiro Tanaka <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
data_types.param_dtypeanddata_types.buffer_dtype(both defaultNone), mirroring FSDPMixedPrecisionPolicy.module.half()/module.bfloat16()in_configure_distributed_modelwith a targeted cast: parameters go toparam_dtype; floating buffers keep their loaded dtype unlessbuffer_dtypeis explicitly set.Motivation
The blanket cast downcasts every floating buffer, including the rotary
inv_freqbuffer that HF/FSDP2 keep in fp32. On long contexts the bf16inv_freqloses precision, RoPE angles drift, and logits/grads diverge from the FSDP2 reference. Preserving fp32 buffers by default fixes this;buffer_dtypeis the escape hatch to reproduce the legacy behavior.Behavior
param_dtypeunset -> derived from the fp16/bf16 enabled flag (legacy param behavior).buffer_dtypeunset -> buffers keep their loaded dtype (e.g. fp32inv_freq).buffer_dtypeset -> buffers force-cast (legacy blanket-cast parity).Test plan
param_dtype=bf16,buffer_dtypeunset -> params bf16,inv_freqstays fp32.buffer_dtype=bf16-> buffers downcast (legacy parity).Made with Cursor