Repository navigation
Keep the parameters a model names for fp32 in fp32 under ZeRO-3 - #8843
Conversation
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 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".
| params_by_dtype = collections.defaultdict(list) | ||
| for param in params_group: | ||
| params_by_dtype[param.ds_tensor.dtype].append(param) |
There was a problem hiding this comment.
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 👍 / 👎.
| partition = getattr(tensor, "ds_tensor", None) | ||
| if partition is not None: | ||
| partition.data = partition.data.float() |
There was a problem hiding this comment.
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 👍 / 👎.
| 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]) |
There was a problem hiding this comment.
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 👍 / 👎.
| 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)) |
There was a problem hiding this comment.
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 👍 / 👎.
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
left a comment
There was a problem hiding this comment.
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.float32Can 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]>
Thanks for catching this. Fixed! |
tohtana
left a comment
There was a problem hiding this comment.
Looks good to me, thank you!
3fe2d95
…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]>
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_modulesfor fp16). #8699 addeddata_types.keep_in_fp32_modules(default"auto": the model's ownlists) 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
deepspeed/runtime/keep_in_fp32.pykeep_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 valuesdeepspeed/runtime/zero/partition_parameters.py__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 keptdeepspeed/runtime/zero/stage3.pydeepspeed/runtime/engine.pydocs/_pages/config-json.mddata_types.keep_in_fp32_modulesnow covers parameters (ZeRO-3) and bufferstests/unit/v1/half_precision/test_keep_in_fp32_modules.pyMeasured
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
TestZeroInitKeepsParamsFp32::test_loaded_values_survivezero.Init, listed parameters keep exact fp32 checkpoint values after loadingTestZero3TrainsKeptParamsInFp32::test_update_below_bf16_resolution_is_kept(zero.Init on/off, contiguous gradients on/off, optimizer offload on/off, gradient accumulation 1/2)TestZero3TrainsKeptParamsInFp32::test_all_reduce_fetchTestZero3TrainsKeptParamsInFp32::test_checkpoint_round_tripTestZero3TrainsKeptParamsInFp32::test_param_offload_keeps_only_buffersTestZero3Fp16KeptParams::test_fp16_trainsTestStagesBelowThreeKeptParamsHardware: 1 node of 8 H200 (driver 580.126.09), torch 2.8.0+cu126, pytest 9.1.1.
pre-commit run --filespasses on every changed file. Regression runs at the time of the first version: identical pass counts with and without the change ontest_zero,test_offload_statesandtests/unit/runtime/zero.Compatibility
AI assistance
This change, its tests and this description were prepared with AI assistance (Claude).