Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 23 additions & 1 deletion deepspeed/runtime/engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand Down Expand Up @@ -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(),
Expand Down
2 changes: 1 addition & 1 deletion docs/_pages/config-json.md
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,7 @@ Example of <i>**scheduler**</i>

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

<i>**gradient_allreduce_op**</i>: [string]

Expand Down
84 changes: 80 additions & 4 deletions tests/unit/v1/zero/test_zero_offload_accum_precision.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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}"


Expand Down Expand Up @@ -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"