diff --git a/deepspeed/runtime/engine.py b/deepspeed/runtime/engine.py
index 063c8bb752cf..b022675f2b2f 100644
--- a/deepspeed/runtime/engine.py
+++ b/deepspeed/runtime/engine.py
@@ -2729,6 +2729,27 @@ def _configure_bf16_optimizer(self, optimizer):
return optimizer
+ def _zero_gradient_reduction_dtype(self, zero_stage, model_dtype, gradient_accumulation_dtype):
+ """Resolve the dtype the ZeRO stage 1/2 optimizer reduces gradients in.
+
+ ZeRO-1 sums a whole accumulation window into an fp32 `grad_accum` buffer and reduces that
+ buffer once. Rounding it to an inferred 16-bit communication dtype discards exactly the
+ precision `grad_accum_dtype: fp32` was requested for (#9047). ZeRO-2 reduces every
+ micro-step in the model dtype and only accumulates afterwards, so its reduction input is
+ already 16-bit and promoting it would cost bandwidth without buying accuracy.
+
+ An explicitly configured `communication_data_type` is always honored: that setting is a
+ deliberate bandwidth choice, and it is also how to ask for the previous rounding behavior.
+ """
+ comm_dtype = self.communication_data_type
+ if self._config.communication_data_type is not None:
+ return comm_dtype
+ reduces_whole_window = zero_stage == ZeroStageEnum.optimizer_states
+ accumulates_in_fp32 = model_dtype != torch.float32 and gradient_accumulation_dtype == torch.float32
+ if reduces_whole_window and accumulates_in_fp32:
+ return gradient_accumulation_dtype
+ return comm_dtype
+
def _configure_zero_optimizer(self, optimizer):
zero_stage = self.zero_optimization_stage()
@@ -2800,7 +2821,8 @@ def _configure_zero_optimizer(self, optimizer):
bf16_master_weights_and_gradients=self.bf16_master_weights_and_gradients(),
bf16_optimizer_states=self.bf16_optimizer_states(),
gradient_accumulation_dtype=gradient_accumulation_dtype,
- communication_data_type=self.communication_data_type,
+ communication_data_type=self._zero_gradient_reduction_dtype(zero_stage, model_dtype,
+ gradient_accumulation_dtype),
elastic_checkpoint=self.zero_elastic_checkpoint(),
check_grad_overflow=check_grad_overflow,
compute_grad_norm=self.zero_compute_grad_norm(),
diff --git a/docs/_pages/config-json.md b/docs/_pages/config-json.md
index f8c6f4b08f79..fcbfd575e23d 100644
--- a/docs/_pages/config-json.md
+++ b/docs/_pages/config-json.md
@@ -213,7 +213,7 @@ Example of **scheduler**
| Description | Default |
| ----------------------------------------------------------------------------------------------------------------------------- | ------- |
-| During gradient averaging perform communication with selected data type. By default it will be determined by selected regime | None |
+| During gradient averaging perform communication with selected data type. By default it will be determined by selected regime, except that ZeRO stage 1 with `data_types.grad_accum_dtype: "fp32"` on a 16-bit model communicates in fp32 so its accumulated window is not rounded. Set this explicitly to keep a narrower reduction | None |
**gradient_allreduce_op**: [string]
diff --git a/tests/unit/v1/zero/test_zero_offload_accum_precision.py b/tests/unit/v1/zero/test_zero_offload_accum_precision.py
index f54ace64343d..4644384ac094 100644
--- a/tests/unit/v1/zero/test_zero_offload_accum_precision.py
+++ b/tests/unit/v1/zero/test_zero_offload_accum_precision.py
@@ -1,7 +1,7 @@
# SPDX-License-Identifier: Apache-2.0
# DeepSpeed Team
"""
-Accumulation precision of ZeRO-1/2 CPU offload across one optimizer window.
+Accumulation precision of ZeRO-1/2 across one optimizer window, with and without CPU offload.
Each micro-step's gradient is exactly representable in bf16 (values (128 + k) / 128), so the
exact window sum is known. The only rounding comes from the accumulation dtype and the host
@@ -104,9 +104,9 @@ def test_window_sum(self, stage, low_precision_master, accumulation_dtype):
with open(out, "a") as f:
f.write(f"stage={stage} master={'bf16' if low_precision_master else 'fp32'} "
f"accum={accumulation_dtype or 'bf16'} rel_max_err={error:.3e}\n")
- if stage == 2 and not low_precision_master and accumulation_dtype == "fp32":
- # The supported case: the window sum is exact. Stage 1 rounds its window sum to the
- # 16-bit reduction dtype once (same error on the base commit); it is characterized, not required.
+ if not low_precision_master and accumulation_dtype == "fp32":
+ # Both stages must keep the window sum exact. Stage 1 used to round it once to the
+ # 16-bit communication dtype on the way into the reduction (#9047).
assert error == 0.0, f"fp32 accumulation with fp32 masters lost precision: {error:.3e}"
@@ -209,3 +209,79 @@ def test_release_option_controls_residency_without_changing_results(self):
assert err_kept == 0.0, f"resident path lost precision: {err_kept:.3e}"
assert err_released == 0.0, f"released path lost precision: {err_released:.3e}"
assert torch.equal(w_released, w_kept), "release option changed the optimizer result"
+
+
+def _dense_config(stage, accumulation_dtype, communication_data_type):
+ """ZeRO without offload, fp16 params, static loss scale so the window sum is the plain gradient sum."""
+ config = {
+ "train_batch_size": 1,
+ "gradient_accumulation_steps": 1,
+ "train_micro_batch_size_per_gpu": 1,
+ "gradient_clipping": 0,
+ "optimizer": {
+ "type": "Adam",
+ "params": {
+ "lr": 1e-3,
+ "torch_adam": True
+ }
+ },
+ "zero_optimization": {
+ "stage": stage
+ },
+ "fp16": {
+ "enabled": True,
+ "loss_scale": 1.0
+ },
+ }
+ if accumulation_dtype is not None:
+ config["data_types"] = {"grad_accum_dtype": accumulation_dtype}
+ if communication_data_type is not None:
+ config["communication_data_type"] = communication_data_type
+ return config
+
+
+def _dense_window_error(stage, accumulation_dtype, communication_data_type=None):
+ """Relative max error of the window's gradient sum against the exact sum, read before step()."""
+ torch.manual_seed(0)
+ model = Weighted(NUMEL)
+ engine, _, _, _ = deepspeed.initialize(model=model,
+ model_parameters=model.parameters(),
+ config=_dense_config(stage, accumulation_dtype, communication_data_type))
+ try:
+ generator = torch.Generator().manual_seed(1234)
+ exact = torch.zeros(NUMEL, dtype=torch.float64)
+ for step in range(MICRO_STEPS):
+ k = torch.randint(0, 128, (NUMEL, ), generator=generator)
+ c = ((128 + k).float() / 128).to(device=engine.device, dtype=torch.float16)
+ exact += c.double().cpu()
+ engine.set_gradient_accumulation_boundary(step == MICRO_STEPS - 1)
+ engine.backward(engine(c))
+ grad = safe_get_full_grad(engine.module.w).detach().float().cpu().double()
+ # Take the step as well, so a reduction dtype the optimizer cannot consume shows up here.
+ engine.step()
+ return ((grad - exact).abs().max() / exact.abs().max()).item()
+ finally:
+ engine.destroy()
+
+
+class TestZeroDenseAccumReductionDtype(DistributedTest):
+ """`grad_accum_dtype: fp32` must survive the reduction, and an explicit comm dtype must still win.
+
+ Each micro-step gradient is (128 + k) / 128 with integer k, which is exact in fp16, so the exact
+ window sum is known independently of how DeepSpeed computes it. Without the fix, ZeRO-1 rounds its
+ fp32 window sum to the inferred fp16 communication dtype before the reduction and the sum read
+ before step() is wrong by ~3e-4 instead of being exact.
+ """
+
+ world_size = 1
+
+ @pytest.mark.parametrize("stage", [1, 2])
+ def test_fp32_accumulation_window_sum_is_exact(self, stage):
+ error = _dense_window_error(stage, "fp32")
+ assert error == 0.0, f"stage {stage} fp32 accumulation lost precision: {error:.3e}"
+
+ def test_explicit_communication_data_type_is_respected(self):
+ # The documented way back to the old behavior: an explicit 16-bit comm dtype keeps its
+ # bandwidth, so the fp32 window sum is still rounded into the reduction.
+ error = _dense_window_error(1, "fp32", communication_data_type="fp16")
+ assert error > 0.0, "an explicit 16-bit communication_data_type was silently promoted to fp32"