From 00bcc411a5d807d0b425e5824ab7c317ab97d37c Mon Sep 17 00:00:00 2001 From: Olatunji Ruwase Date: Mon, 9 Nov 2026 04:10:39 +0000 Subject: [PATCH 01/12] ZeRO-2 CPU offload: accumulate in the compact partition between requests With stage-2 CPU offload, the running gradient sum now lives in one partition-sized buffer in grad_accum_dtype during each request, and is published to the host FP32 partition at the request boundary. The GPU partition is freed between requests when the host copy can restore the sum exactly (same dtype, or FP32 host holding bf16/fp16 values), and is restored by the next backward in the same optimizer window. The compact path is limited to stage-2 CPU offload. Stage 1 (cumulative unreduced grad_accum across reentrant phases), Muon, and ZenFlow keep their existing gating. Config now rejects data_types.grad_accum_dtype="fp32" combined with fp16/bf16 master weights and grads, since the optimizer step runs in the master dtype and would discard the extra accumulation precision. Tests: update the stubs in the gradient-safety tests to the legacy path, read the running partition sum for grad-accum assertions, skip the fp32-accum overflow case under low-precision masters, and add config tests for the new rejection rule. Signed-off-by: Olatunji Ruwase Co-authored-by: Cursor --- deepspeed/runtime/config.py | 7 + deepspeed/runtime/zero/stage_1_and_2.py | 135 +++++++++++++++--- tests/unit/runtime/test_ds_config_dict.py | 35 +++++ .../v1/zero/test_zero2_gradient_safety.py | 6 + .../zero/test_zero2_offload_multi_backward.py | 11 +- .../zero/test_zero_cpu_offload_grad_accum.py | 23 +-- 6 files changed, 189 insertions(+), 28 deletions(-) diff --git a/deepspeed/runtime/config.py b/deepspeed/runtime/config.py index 9972bd1bf828..5b62896a63eb 100755 --- a/deepspeed/runtime/config.py +++ b/deepspeed/runtime/config.py @@ -716,6 +716,13 @@ def _do_error_check(self): ZeroStageEnum.optimizer_states, ZeroStageEnum.gradients, ZeroStageEnum.weights), "bf16_optimizer_states is only supported with ZeRO Stage 1, 2, or 3." assert self.bfloat16_config.bf16_master_weights_and_grads, "bf16_optimizer_states requires bf16_master_weights_and_grads to be enabled." + if (self.grad_accum_dtype is not None and DtypeEnum(self.grad_accum_dtype).value == torch.float32 + and (self.float16_config.fp16_master_weights_and_grads + or self.bfloat16_config.bf16_master_weights_and_grads)): + raise ValueError("data_types.grad_accum_dtype='fp32' is incompatible with " + "fp16/bf16_master_weights_and_grads: the optimizer step runs in the master dtype, " + "so the extra accumulation precision is discarded. Use an fp32 master, or omit " + "grad_accum_dtype so it matches the master.") def _do_warning_check(self): vocabulary_size = self._param_dict.get(VOCABULARY_SIZE, VOCABULARY_SIZE_DEFAULT) diff --git a/deepspeed/runtime/zero/stage_1_and_2.py b/deepspeed/runtime/zero/stage_1_and_2.py index 83ff54b44e6e..494b35a26443 100644 --- a/deepspeed/runtime/zero/stage_1_and_2.py +++ b/deepspeed/runtime/zero/stage_1_and_2.py @@ -653,6 +653,10 @@ def _enforce_cpu_offload(): self._offload_accumulated_param_ids = set() # FP32-master gradients first seen at a boundary stay in the partition until another backward. self._offload_partition_only_param_ids = set() + # Host sums updated by a non-boundary backward since they were last published to the FP32 partition. + self._offload_unpublished_param_ids = set() + # Compact FP32 partitions freed at a boundary; the host gradient holds their running sum. + self._host_owned_compact_partitions = set() self.temp_grad_buffer_for_cpu_offload = torch.zeros(largest_param_numel, device=self.device, dtype=self.dtype) @@ -1063,6 +1067,9 @@ def independent_gradient_partition_epilogue(self): # sum until step(): more request boundaries may precede the update. if self.use_grad_accum_attribute: self.all_grad_tensors[i] = None + elif self.is_gradient_accumulation_boundary(): + self._publish_unpublished_offload_grads() + self._offload_compact_grad_partitions() self._release_ipg_buffers() @@ -1110,10 +1117,34 @@ def _finalize_cpu_offload_gradient_accumulation(self): if self._use_compact_grad_partition_buffer(group_idx): self.copy_grads_in_partition(param, group_idx) continue - self._restore_cpu_offload_grad_to_gpu(param) - self.set_norm_for_param_grad_in_gpu(param) - self.update_offload_overflow_tracker_for_param_grad(param) - self.async_inplace_copy_grad_to_fp32_buffer_from_gpu(param) + self._publish_host_accumulated_grad(param) + self._offload_unpublished_param_ids.clear() + self._offload_compact_grad_partitions() + + def _publish_host_accumulated_grad(self, param): + """Read this parameter's host sum back to the device, then into the FP32 partition. + + The device pass lets the shared norm and overflow helpers see the full accumulated gradient. + """ + self._restore_cpu_offload_grad_to_gpu(param) + self.set_norm_for_param_grad_in_gpu(param) + self.update_offload_overflow_tracker_for_param_grad(param) + self.async_inplace_copy_grad_to_fp32_buffer_from_gpu(param) + + def _publish_unpublished_offload_grads(self): + """Bring every host sum a non-boundary backward left behind into the FP32 partition. + + A boundary backward publishes only the parameters it reduced. A parameter whose last + contribution this window came from a non-boundary backward would otherwise reach step(), + safe_get_full_grad() and the grad norm as zero. + """ + for group_idx, group in enumerate(self.params_in_partition): + if self._use_compact_grad_partition_buffer(group_idx): + continue + for param in group: + if self.get_param_id(param) in self._offload_unpublished_param_ids: + self._publish_host_accumulated_grad(param) + self._offload_unpublished_param_ids.clear() def _restore_cpu_offload_grad_to_gpu(self, param): # Last non-boundary epilogue cleared param.grad; reload accumulated CPU grads for boundary helpers. @@ -1264,14 +1295,28 @@ def get_param_gradient_attribute(self, param): return param.grad_accum if self.use_grad_accum_attribute else param.grad def _use_compact_grad_partition_buffer(self, group_idx): - gradient_accumulation_dtype = getattr(self, "gradient_accumulation_dtype", None) - if gradient_accumulation_dtype != torch.float32 or gradient_accumulation_dtype == self.dtype: - return False params_in_partition = self.params_in_partition[group_idx] if len(params_in_partition) > 0 and self._is_muon_group(params_in_partition): return False + # Stage-2 CPU offload keeps the running sum in one partition buffer in gradient_accumulation_dtype + # for every dtype, so the host publish is the only dtype conversion. Stage 1 (its unreduced + # grad_accum is cumulative across reentrant phases) and ZenFlow keep their existing gate. + if (getattr(self, "cpu_offload", False) and getattr(self, "partition_gradients", False) + and not getattr(self, "zenflow", False)): + return True + gradient_accumulation_dtype = getattr(self, "gradient_accumulation_dtype", None) + if gradient_accumulation_dtype != torch.float32 or gradient_accumulation_dtype == self.dtype: + return False return True + @staticmethod + def _host_grad_holds_accum_exactly(host_dtype, accum_dtype): + # The host gradient may be restored into the device buffer only if no bits are lost: + # same dtype, or an fp32 host holding bf16/fp16 values that were widened from it. + if host_dtype == accum_dtype: + return True + return host_dtype == torch.float32 and accum_dtype in (torch.bfloat16, torch.float16) + def _build_compact_grad_partition_buffer(self, group_idx): partition_size = int(self.partition_size[group_idx]) flat_partition = torch.zeros(partition_size, @@ -1313,9 +1358,63 @@ def _get_compact_grad_partition_buffer(self, group_idx): return grad_group grad_group = self._build_compact_grad_partition_buffer(group_idx) + if self.cpu_offload and group_idx in self._host_owned_compact_partitions: + self._restore_compact_grad_partition(group_idx, grad_group) self.averaged_gradients[group_idx] = grad_group return grad_group + def _offload_compact_grad_partitions(self): + """Copy each compact FP32 partition's running sum to the host gradient at a boundary. + + Every parameter accumulated in this window is copied, including one that missed the + boundary backward. Once the host holds the exact sum, the GPU partition is freed so it + does not occupy HBM between requests; a later backward in the window restores it. + """ + stream = get_accelerator().current_stream() + if self.overlap_comm and self.reduction_stream is not None: + stream.wait_stream(self.reduction_stream) + for group_idx in range(len(self.bit16_groups)): + grad_group = self.averaged_gradients.get(group_idx) + if grad_group is None or not self._use_compact_grad_partition_buffer(group_idx): + continue + partition_id = dist.get_rank(group=self.real_dp_process_group[group_idx]) + host_grad = self.single_partition_of_fp32_groups[group_idx].grad.view(-1) + for param in self.params_in_partition[group_idx]: + param_id = self.get_param_id(param) + if param_id not in self._offload_accumulated_param_ids: + continue + [_, _, dest_offset, num_elements] = self.grad_position[param_id] + source = self._get_compact_grad_partition_slice(group_idx, partition_id, param_id, num_elements) + self.norm_for_param_grads[param_id] = source.data.to(get_norm_dtype()).norm(2) + self.update_offload_overflow_tracker(source) + host_grad.narrow(0, dest_offset, num_elements).copy_(source.to(host_grad.dtype), non_blocking=True) + self._record_offload_copy() + + # Free only when the host copy can restore the device sum bit for bit. Otherwise the + # device buffer stays resident until step(), and ZenFlow orders its own copies. + if not self._host_grad_holds_accum_exactly(host_grad.dtype, grad_group.flat_partition.dtype): + continue + if not self._offload_gradient_safety_enabled: + continue + self._record_gradient_stream(grad_group.flat_partition, stream) + self.averaged_gradients[group_idx] = None + self._host_owned_compact_partitions.add(group_idx) + + def _restore_compact_grad_partition(self, group_idx, grad_group): + self._host_owned_compact_partitions.discard(group_idx) + # The restore may run on another stream than the boundary copy that filled the host gradient. + self._wait_for_offload_copies() + partition_id = dist.get_rank(group=self.real_dp_process_group[group_idx]) + host_grad = self.single_partition_of_fp32_groups[group_idx].grad.view(-1) + for param in self.params_in_partition[group_idx]: + param_id = self.get_param_id(param) + if param_id not in self._offload_accumulated_param_ids: + continue + [_, _, dest_offset, num_elements] = self.grad_position[param_id] + insertion_offset = int(self.grad_partition_insertion_offset[group_idx][partition_id][param_id]) + destination = grad_group.flat_partition.narrow(0, insertion_offset, num_elements) + destination.copy_(host_grad.narrow(0, dest_offset, num_elements), non_blocking=True) + def _get_compact_grad_partition_slice(self, group_idx, partition_id, param_id, num_elements): if not self._use_compact_grad_partition_buffer(group_idx): return None @@ -2131,19 +2230,9 @@ def copy_grads_in_partition(self, param, group_idx=None): if group_idx is None: group_idx = self._get_param_group_idx(param) if self.cpu_offload and self._use_compact_grad_partition_buffer(group_idx): - param_id = self.get_param_id(param) - self._offload_accumulated_param_ids.add(param_id) + # The boundary copy to the host runs per group, in _offload_compact_grad_partitions(). + self._offload_accumulated_param_ids.add(self.get_param_id(param)) if self.is_gradient_accumulation_boundary(): - [_, _, dest_offset, num_elements] = self.grad_position[param_id] - partition_id = dist.get_rank(group=self.real_dp_process_group[group_idx]) - source = self._get_compact_grad_partition_slice(group_idx, partition_id, param_id, num_elements) - self.norm_for_param_grads[param_id] = source.data.to(get_norm_dtype()).norm(2) - self.update_offload_overflow_tracker(source) - destination = self.single_partition_of_fp32_groups[group_idx].grad.view(-1).narrow( - 0, dest_offset, num_elements) - destination.copy_(source.to(destination.dtype), non_blocking=True) - self._record_gradient_stream(source, get_accelerator().current_stream()) - self._record_offload_copy() self.clear_grad_attribute(param) return if self.cpu_offload: @@ -2163,6 +2252,9 @@ def copy_grads_in_partition(self, param, group_idx=None): self.update_offload_overflow_tracker_for_param_grad(param) self.async_inplace_copy_grad_to_fp32_buffer_from_gpu(param) + self._offload_unpublished_param_ids.discard(param_id) + else: + self._offload_unpublished_param_ids.add(param_id) # Include the shared-buffer fast path in subsequent accumulation and finalization. self._offload_accumulated_param_ids.add(param_id) @@ -2926,6 +3018,7 @@ def reset_cpu_buffers(self): self._wait_for_offload_copies() self.norm_for_param_grads = {} self.local_overflow = False + self._host_owned_compact_partitions.clear() # Adam consumes the partition gradient; a parameter idle in the next window must not reuse it. for fp32_partition in self.single_partition_of_fp32_groups: if fp32_partition.grad is not None: @@ -3038,6 +3131,7 @@ def step(self, closure=None): if self.cpu_offload: self._offload_accumulated_param_ids = set() self._offload_partition_only_param_ids = set() + self._offload_unpublished_param_ids = set() if not self.compute_grad_norm: self._global_grad_norm = None @@ -3075,6 +3169,9 @@ def step(self, closure=None): self._release_preflattened_grad_buffers() if self.cpu_offload: self.reset_cpu_buffers() + # A resident compact partition still holds the skipped window's inf/NaN sum. + for k in self.averaged_gradients.keys(): + self.averaged_gradients[k] = None else: for k in self.averaged_gradients.keys(): self.averaged_gradients[k] = None diff --git a/tests/unit/runtime/test_ds_config_dict.py b/tests/unit/runtime/test_ds_config_dict.py index 9837907fac23..fb389837ca26 100644 --- a/tests/unit/runtime/test_ds_config_dict.py +++ b/tests/unit/runtime/test_ds_config_dict.py @@ -209,6 +209,41 @@ def test_sum_gradient_allreduce_rejects_deepcompile(zero_stage): }) +@pytest.mark.parametrize("master_key", ["bf16", "fp16"]) +def test_fp32_grad_accum_rejects_low_precision_master(master_key): + with pytest.raises(ValueError, match="grad_accum_dtype"): + DeepSpeedConfig({ + "train_batch_size": 1, + master_key: { + "enabled": True, + f"{master_key}_master_weights_and_grads": True, + }, + "data_types": { + "grad_accum_dtype": "fp32", + }, + "zero_optimization": { + "stage": 2, + }, + }) + + +def test_fp32_grad_accum_with_fp32_master_is_allowed(): + config = DeepSpeedConfig({ + "train_batch_size": 1, + "bf16": { + "enabled": True, + }, + "data_types": { + "grad_accum_dtype": "fp32", + }, + "zero_optimization": { + "stage": 2, + }, + }) + assert config.grad_accum_dtype == "fp32" + assert not config.bfloat16_config.bf16_master_weights_and_grads + + @pytest.mark.parametrize("gather_weights_key", ["stage3_gather_16bit_weights_on_model_save", "stage3_gather_fp16_weights_on_model_save"]) def test_gather_16bit_params_on_model_save(gather_weights_key): diff --git a/tests/unit/v1/zero/test_zero2_gradient_safety.py b/tests/unit/v1/zero/test_zero2_gradient_safety.py index 2089022539f4..9665c91e0b39 100644 --- a/tests/unit/v1/zero/test_zero2_gradient_safety.py +++ b/tests/unit/v1/zero/test_zero2_gradient_safety.py @@ -30,6 +30,8 @@ def make_optimizer(dtype=torch.bfloat16, device=None, low_precision=False, cpu_o opt = zero.DeepSpeedZeroOptimizer.__new__(zero.DeepSpeedZeroOptimizer) opt.cpu_offload = cpu_offload opt._offload_gradient_safety_enabled = cpu_offload + opt._host_owned_compact_partitions = set() + opt._offload_unpublished_param_ids = set() opt.cpu_offload_pin_memory = False opt.device = "cpu" opt.dtype = dtype @@ -40,6 +42,10 @@ def make_optimizer(dtype=torch.bfloat16, device=None, low_precision=False, cpu_o opt.contiguous_gradients = True opt.overlap_comm = False opt.zenflow = False + # These stubs drive copy_grads_in_partition directly and skip the reduction that fills the + # compact partition buffer. Pin them to the host accumulator path, which Muon and ZenFlow still + # use; the compact layout is covered by the engine tests in test_zero2_offload_multi_backward.py. + opt._use_compact_grad_partition_buffer = lambda group_idx: False opt.has_moe_layers = False opt.autoep_folding_tp_group = None opt.gradient_accumulation_steps = 1 diff --git a/tests/unit/v1/zero/test_zero2_offload_multi_backward.py b/tests/unit/v1/zero/test_zero2_offload_multi_backward.py index 0f513e5587fc..b46e64cf0ac8 100644 --- a/tests/unit/v1/zero/test_zero2_offload_multi_backward.py +++ b/tests/unit/v1/zero/test_zero2_offload_multi_backward.py @@ -222,6 +222,10 @@ def _run_request_boundaries(rank, rendezvous, zero_stage, cpu_offload, accumulat # Each projection first joins a later backward after contributing to the preceding update. for early, late in [(0, 1), (1, 0)]: windows.append(([["c0"], ["c1", "c2"], ["c3"]], {"c0": (early, ), "c1": (late, ), "c2": (late, )})) + # A projection can contribute to a request without joining its boundary backward. + for early, late in [(0, 1), (1, 0)]: + windows.append(([["c0", "c1"], ["c2"]], {"c0": (early, ), "c1": (late, )})) + windows.append(([["c0", "c1"]], {"c0": (early, ), "c1": (late, )})) reference_names = list(references) for step, (requests, selections) in enumerate(windows): expected = {name: torch.zeros_like(reference) for name, reference in references.items()} @@ -283,13 +287,16 @@ class TestZero2OffloadOverflowRecovery(DistributedTest): @pytest.mark.parametrize("precision", ["bf16", "fp16"]) @pytest.mark.parametrize("low_precision_master", [True, False]) - def test_finite_step_after_overflow(self, precision, low_precision_master): + @pytest.mark.parametrize("accumulation_dtype", [None, "fp32"]) + def test_finite_step_after_overflow(self, precision, low_precision_master, accumulation_dtype): if not deepspeed.ops.__compatible_ops__[CPUAdamBuilder.NAME]: pytest.skip("CPUAdam is required for low-precision offloaded master weights") if precision == "bf16" and not get_accelerator().is_bf16_supported(): pytest.skip("BF16 is not supported") if precision == "fp16" and not get_accelerator().is_fp16_supported(): pytest.skip("FP16 is not supported") + if low_precision_master and accumulation_dtype == "fp32": + pytest.skip("fp32 accumulation with a low-precision master is rejected at config time") class TwoGroups(torch.nn.Module): @@ -307,6 +314,8 @@ def forward(self, overflow): config[precision] = {"enabled": True, f"{precision}_master_weights_and_grads": low_precision_master} if precision == "fp16": config[precision]["loss_scale"] = 1.0 + if accumulation_dtype is not None: + config["data_types"] = {"grad_accum_dtype": accumulation_dtype} config["train_batch_size"] = 2 config["managed_gradient_accumulation"] = False config["optimizer"]["params"]["lr"] = 0.1 diff --git a/tests/unit/v1/zero/test_zero_cpu_offload_grad_accum.py b/tests/unit/v1/zero/test_zero_cpu_offload_grad_accum.py index aa27396fda81..e00dd94d0e64 100644 --- a/tests/unit/v1/zero/test_zero_cpu_offload_grad_accum.py +++ b/tests/unit/v1/zero/test_zero_cpu_offload_grad_accum.py @@ -19,11 +19,18 @@ from deepspeed.accelerator import get_accelerator -def _cpu_grad_norm(engine): +def _running_grad_norm(engine): + # The running sum lives in the device partition buffer until a boundary publishes it. Fall back + # to the host accumulator for groups that use it (Muon, ZenFlow). + optimizer = engine.optimizer total_norm_sq = 0.0 - for grad in engine.optimizer.accumulated_grads_in_cpu: - if grad is not None: - total_norm_sq += grad.float().norm(2).item()**2 + for group_idx in range(len(optimizer.bit16_groups)): + grad_group = optimizer.averaged_gradients.get(group_idx) + flat_partition = getattr(grad_group, "flat_partition", None) + if flat_partition is not None: + total_norm_sq += flat_partition.float().norm(2).item()**2 + elif optimizer.accumulated_grads_in_cpu[group_idx] is not None: + total_norm_sq += optimizer.accumulated_grads_in_cpu[group_idx].float().norm(2).item()**2 return total_norm_sq**0.5 @@ -79,12 +86,12 @@ def test(self): for batch in data_loader: loss = model(batch[0], batch[1]) model.backward(loss) - norms.append(_cpu_grad_norm(model)) + norms.append(_running_grad_norm(model)) model.destroy() - assert norms[0] > 0, "accumulated_grads_in_cpu should be non-zero after first backward" + assert norms[0] > 0, "running gradient sum should be non-zero after first backward" for i in range(1, len(norms)): - assert norms[i] != norms[0], (f"accumulated_grads_in_cpu norm did not change after micro-step {i}: " + assert norms[i] != norms[0], (f"running gradient sum norm did not change after micro-step {i}: " f"norm[0]={norms[0]:.6f}, norm[{i}]={norms[i]:.6f}. " - "Gradients were not copied back to CPU (PR #7967 regression).") + "Gradients were not accumulated (PR #7967 regression).") From d53ddea33db26606d5c7f13d1103cdba2ef85abe Mon Sep 17 00:00:00 2001 From: Olatunji Ruwase Date: Mon, 9 Nov 2026 14:13:24 +0000 Subject: [PATCH 02/12] Format grad_accum_dtype check with yapf Signed-off-by: Olatunji Ruwase Co-authored-by: Cursor --- deepspeed/runtime/config.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/deepspeed/runtime/config.py b/deepspeed/runtime/config.py index 5b62896a63eb..fa924a11637a 100755 --- a/deepspeed/runtime/config.py +++ b/deepspeed/runtime/config.py @@ -716,9 +716,8 @@ def _do_error_check(self): ZeroStageEnum.optimizer_states, ZeroStageEnum.gradients, ZeroStageEnum.weights), "bf16_optimizer_states is only supported with ZeRO Stage 1, 2, or 3." assert self.bfloat16_config.bf16_master_weights_and_grads, "bf16_optimizer_states requires bf16_master_weights_and_grads to be enabled." - if (self.grad_accum_dtype is not None and DtypeEnum(self.grad_accum_dtype).value == torch.float32 - and (self.float16_config.fp16_master_weights_and_grads - or self.bfloat16_config.bf16_master_weights_and_grads)): + if (self.grad_accum_dtype is not None and DtypeEnum(self.grad_accum_dtype).value == torch.float32 and + (self.float16_config.fp16_master_weights_and_grads or self.bfloat16_config.bf16_master_weights_and_grads)): raise ValueError("data_types.grad_accum_dtype='fp32' is incompatible with " "fp16/bf16_master_weights_and_grads: the optimizer step runs in the master dtype, " "so the extra accumulation precision is discarded. Use an fp32 master, or omit " From be4ef87500e870b9876bb486db7884e4715de059 Mon Sep 17 00:00:00 2001 From: Olatunji Ruwase Date: Mon, 9 Nov 2026 15:18:48 +0000 Subject: [PATCH 03/12] Allow fp32 grad accumulation with low-precision master weights Remove the config-time rejection of data_types.grad_accum_dtype='fp32' combined with fp16/bf16 master weights and grads. The rejection applied to every ZeRO stage and offload mode, although the compact-buffer path it was meant to protect already keeps the device sum resident when the bf16/fp16 host copy cannot restore it exactly. Validated on 4x B200: the overflow-recovery tests pass for all fp32-accumulation cases with low-precision masters, and a bf16-master fp32-accumulation smoke test trains with finite losses for stage 2 with and without CPU offload and for stages 1/2 with CPU offload. Stage 1 without offload is still rejected by the existing master-weight assertion in stage_1_and_2.py. Tests: drop the rejection test and the overflow-test skip that covered the removed rule. Signed-off-by: Olatunji Ruwase Co-authored-by: Cursor --- deepspeed/runtime/config.py | 6 ------ tests/unit/runtime/test_ds_config_dict.py | 18 ------------------ .../zero/test_zero2_offload_multi_backward.py | 2 -- 3 files changed, 26 deletions(-) diff --git a/deepspeed/runtime/config.py b/deepspeed/runtime/config.py index fa924a11637a..9972bd1bf828 100755 --- a/deepspeed/runtime/config.py +++ b/deepspeed/runtime/config.py @@ -716,12 +716,6 @@ def _do_error_check(self): ZeroStageEnum.optimizer_states, ZeroStageEnum.gradients, ZeroStageEnum.weights), "bf16_optimizer_states is only supported with ZeRO Stage 1, 2, or 3." assert self.bfloat16_config.bf16_master_weights_and_grads, "bf16_optimizer_states requires bf16_master_weights_and_grads to be enabled." - if (self.grad_accum_dtype is not None and DtypeEnum(self.grad_accum_dtype).value == torch.float32 and - (self.float16_config.fp16_master_weights_and_grads or self.bfloat16_config.bf16_master_weights_and_grads)): - raise ValueError("data_types.grad_accum_dtype='fp32' is incompatible with " - "fp16/bf16_master_weights_and_grads: the optimizer step runs in the master dtype, " - "so the extra accumulation precision is discarded. Use an fp32 master, or omit " - "grad_accum_dtype so it matches the master.") def _do_warning_check(self): vocabulary_size = self._param_dict.get(VOCABULARY_SIZE, VOCABULARY_SIZE_DEFAULT) diff --git a/tests/unit/runtime/test_ds_config_dict.py b/tests/unit/runtime/test_ds_config_dict.py index fb389837ca26..43eab2d6861f 100644 --- a/tests/unit/runtime/test_ds_config_dict.py +++ b/tests/unit/runtime/test_ds_config_dict.py @@ -209,24 +209,6 @@ def test_sum_gradient_allreduce_rejects_deepcompile(zero_stage): }) -@pytest.mark.parametrize("master_key", ["bf16", "fp16"]) -def test_fp32_grad_accum_rejects_low_precision_master(master_key): - with pytest.raises(ValueError, match="grad_accum_dtype"): - DeepSpeedConfig({ - "train_batch_size": 1, - master_key: { - "enabled": True, - f"{master_key}_master_weights_and_grads": True, - }, - "data_types": { - "grad_accum_dtype": "fp32", - }, - "zero_optimization": { - "stage": 2, - }, - }) - - def test_fp32_grad_accum_with_fp32_master_is_allowed(): config = DeepSpeedConfig({ "train_batch_size": 1, diff --git a/tests/unit/v1/zero/test_zero2_offload_multi_backward.py b/tests/unit/v1/zero/test_zero2_offload_multi_backward.py index b46e64cf0ac8..439144dcf6b5 100644 --- a/tests/unit/v1/zero/test_zero2_offload_multi_backward.py +++ b/tests/unit/v1/zero/test_zero2_offload_multi_backward.py @@ -295,8 +295,6 @@ def test_finite_step_after_overflow(self, precision, low_precision_master, accum pytest.skip("BF16 is not supported") if precision == "fp16" and not get_accelerator().is_fp16_supported(): pytest.skip("FP16 is not supported") - if low_precision_master and accumulation_dtype == "fp32": - pytest.skip("fp32 accumulation with a low-precision master is rejected at config time") class TwoGroups(torch.nn.Module): From bca22e21385fa035a1de891a7e2b392714a2e871 Mon Sep 17 00:00:00 2001 From: Olatunji Ruwase Date: Mon, 9 Nov 2026 15:48:04 +0000 Subject: [PATCH 04/12] ZeRO-2 offload: check overflow on the host-dtype gradient; fix vacuous norm test Check the compact partition's overflow after the cast to the host gradient dtype, so an fp32 sum that exceeds the fp16 range is caught when fp16 master weights are used. Cover the host-accumulator path across request boundaries, the fp16 host overflow, and the freed-buffer state in the accumulation norm test. Drop a config test that never exercised a rejection. Signed-off-by: Olatunji Ruwase Co-authored-by: Cursor --- deepspeed/runtime/zero/stage_1_and_2.py | 11 +-- tests/unit/runtime/test_ds_config_dict.py | 17 ----- .../zero/test_zero2_offload_multi_backward.py | 69 ++++++++++++++++++- .../zero/test_zero_cpu_offload_grad_accum.py | 10 ++- 4 files changed, 82 insertions(+), 25 deletions(-) diff --git a/deepspeed/runtime/zero/stage_1_and_2.py b/deepspeed/runtime/zero/stage_1_and_2.py index 494b35a26443..7dd7c49117b8 100644 --- a/deepspeed/runtime/zero/stage_1_and_2.py +++ b/deepspeed/runtime/zero/stage_1_and_2.py @@ -655,7 +655,7 @@ def _enforce_cpu_offload(): self._offload_partition_only_param_ids = set() # Host sums updated by a non-boundary backward since they were last published to the FP32 partition. self._offload_unpublished_param_ids = set() - # Compact FP32 partitions freed at a boundary; the host gradient holds their running sum. + # Compact partitions freed at a boundary; the host gradient holds their running sum. self._host_owned_compact_partitions = set() self.temp_grad_buffer_for_cpu_offload = torch.zeros(largest_param_numel, device=self.device, @@ -1364,7 +1364,7 @@ def _get_compact_grad_partition_buffer(self, group_idx): return grad_group def _offload_compact_grad_partitions(self): - """Copy each compact FP32 partition's running sum to the host gradient at a boundary. + """Copy each compact partition's running sum to the host gradient at a boundary. Every parameter accumulated in this window is copied, including one that missed the boundary backward. Once the host holds the exact sum, the GPU partition is freed so it @@ -1386,8 +1386,11 @@ def _offload_compact_grad_partitions(self): [_, _, dest_offset, num_elements] = self.grad_position[param_id] source = self._get_compact_grad_partition_slice(group_idx, partition_id, param_id, num_elements) self.norm_for_param_grads[param_id] = source.data.to(get_norm_dtype()).norm(2) - self.update_offload_overflow_tracker(source) - host_grad.narrow(0, dest_offset, num_elements).copy_(source.to(host_grad.dtype), non_blocking=True) + # Check the value the optimizer will read: an fp32 sum can pass here and become inf in an + # fp16 host gradient. + host_value = source.to(host_grad.dtype) + self.update_offload_overflow_tracker(host_value) + host_grad.narrow(0, dest_offset, num_elements).copy_(host_value, non_blocking=True) self._record_offload_copy() # Free only when the host copy can restore the device sum bit for bit. Otherwise the diff --git a/tests/unit/runtime/test_ds_config_dict.py b/tests/unit/runtime/test_ds_config_dict.py index 43eab2d6861f..9837907fac23 100644 --- a/tests/unit/runtime/test_ds_config_dict.py +++ b/tests/unit/runtime/test_ds_config_dict.py @@ -209,23 +209,6 @@ def test_sum_gradient_allreduce_rejects_deepcompile(zero_stage): }) -def test_fp32_grad_accum_with_fp32_master_is_allowed(): - config = DeepSpeedConfig({ - "train_batch_size": 1, - "bf16": { - "enabled": True, - }, - "data_types": { - "grad_accum_dtype": "fp32", - }, - "zero_optimization": { - "stage": 2, - }, - }) - assert config.grad_accum_dtype == "fp32" - assert not config.bfloat16_config.bf16_master_weights_and_grads - - @pytest.mark.parametrize("gather_weights_key", ["stage3_gather_16bit_weights_on_model_save", "stage3_gather_fp16_weights_on_model_save"]) def test_gather_16bit_params_on_model_save(gather_weights_key): diff --git a/tests/unit/v1/zero/test_zero2_offload_multi_backward.py b/tests/unit/v1/zero/test_zero2_offload_multi_backward.py index 439144dcf6b5..e7220b720d61 100644 --- a/tests/unit/v1/zero/test_zero2_offload_multi_backward.py +++ b/tests/unit/v1/zero/test_zero2_offload_multi_backward.py @@ -167,7 +167,13 @@ def forward(self, inputs, projection_indices=(0, 1)): return loss -def _run_request_boundaries(rank, rendezvous, zero_stage, cpu_offload, accumulation_dtype, checkpointed): +def _run_request_boundaries(rank, + rendezvous, + zero_stage, + cpu_offload, + accumulation_dtype, + checkpointed, + host_accumulator=False): os.environ["LOCAL_RANK"] = str(rank) accelerator = get_accelerator() accelerator.set_device(rank) @@ -215,6 +221,9 @@ def _run_request_boundaries(rank, rendezvous, zero_stage, cpu_offload, accumulat optimizer=torch.optim.SGD(model.parameters(), lr=1 / 32), config=config, dist_init_required=False) + if host_accumulator: + # Muon groups accumulate in the host accumulator instead of the compact partition buffer. + engine.optimizer._use_compact_grad_partition_buffer = lambda group_idx: False calls = ["c0", "c1", "c2", "c3"] windows = [(requests, {}) for requests in [[calls], [["ping"], calls], [["c0"], ["c1"]], [["c0"], ["c1"], ["c2", "c3"]], @@ -282,9 +291,67 @@ def test_multiple_request_boundaries_before_step(tmp_path, zero_stage, cpu_offlo start_method="forkserver") +@pytest.mark.skipif(get_accelerator().device_name() not in ("cpu", "cuda") + or (get_accelerator().device_name() == "cuda" and get_accelerator().device_count() < 2), + reason="Requires CPU or two CUDA devices") +@pytest.mark.parametrize("accumulation_dtype", ["bf16", "fp32"]) +@pytest.mark.parametrize("checkpointed", [False, True], ids=["plain", "reentrant"]) +def test_multiple_request_boundaries_host_accumulator(tmp_path, accumulation_dtype, checkpointed): + # The host-accumulator path is what Muon groups use under stage-2 CPU offload. + torch.multiprocessing.start_processes(_run_request_boundaries, + args=(f"file://{tmp_path / 'rendezvous'}", 2, True, accumulation_dtype, + checkpointed, True), + nprocs=2, + join=True, + start_method="forkserver") + + class TestZero2OffloadOverflowRecovery(DistributedTest): world_size = 2 + @pytest.mark.parametrize("accumulation_dtype", [None, "fp32"]) + def test_fp16_host_gradient_overflow_skips_step(self, accumulation_dtype): + """A sum that exceeds the fp16 range must be caught when it reaches the fp16 host gradient. + + With fp32 accumulation the overflow appears only in the cast to the fp16 master gradient. + """ + if not deepspeed.ops.__compatible_ops__[CPUAdamBuilder.NAME]: + pytest.skip("CPUAdam is required for low-precision offloaded master weights") + if not get_accelerator().is_fp16_supported(): + pytest.skip("FP16 is not supported") + + class Scaled(torch.nn.Module): + + def __init__(self): + super().__init__() + self.weight = torch.nn.Parameter(torch.ones(16)) + + def forward(self, scale): + return (self.weight * scale).sum() + + config = _base_config(2, cpu_offload=True) + config.pop("bf16", None) + config["fp16"] = {"enabled": True, "loss_scale": 1.0, "fp16_master_weights_and_grads": True} + if accumulation_dtype is not None: + config["data_types"] = {"grad_accum_dtype": accumulation_dtype} + config["train_batch_size"] = 2 + config["managed_gradient_accumulation"] = False + model = Scaled() + engine, _, _, _ = deepspeed.initialize(model=model, model_parameters=model.parameters(), config=config) + try: + initial = _capture_params(engine) + # Each backward adds 40000 per element: finite in fp16 alone, 80000 (> 65504) in the sum. + for i in range(2): + engine.set_gradient_accumulation_boundary(i == 1) + engine.backward(engine(torch.tensor(40000., device=engine.device))) + engine.step() + after = _capture_params(engine) + for name in initial: + assert torch.isfinite(after[name]).all(), f"{name} became non-finite" + _assert_params_match(initial, after, "overflowed sum must skip the update", tol=1e-8) + finally: + engine.destroy() + @pytest.mark.parametrize("precision", ["bf16", "fp16"]) @pytest.mark.parametrize("low_precision_master", [True, False]) @pytest.mark.parametrize("accumulation_dtype", [None, "fp32"]) diff --git a/tests/unit/v1/zero/test_zero_cpu_offload_grad_accum.py b/tests/unit/v1/zero/test_zero_cpu_offload_grad_accum.py index e00dd94d0e64..077ff87358f1 100644 --- a/tests/unit/v1/zero/test_zero_cpu_offload_grad_accum.py +++ b/tests/unit/v1/zero/test_zero_cpu_offload_grad_accum.py @@ -20,8 +20,9 @@ def _running_grad_norm(engine): - # The running sum lives in the device partition buffer until a boundary publishes it. Fall back - # to the host accumulator for groups that use it (Muon, ZenFlow). + # The running sum lives in the device partition buffer until a boundary copies it to the host and + # frees the buffer; after that the host gradient holds it. Groups on the legacy path (Muon, ZenFlow) + # use the host accumulator. optimizer = engine.optimizer total_norm_sq = 0.0 for group_idx in range(len(optimizer.bit16_groups)): @@ -29,6 +30,9 @@ def _running_grad_norm(engine): flat_partition = getattr(grad_group, "flat_partition", None) if flat_partition is not None: total_norm_sq += flat_partition.float().norm(2).item()**2 + elif group_idx in optimizer._host_owned_compact_partitions: + host_grad = optimizer.single_partition_of_fp32_groups[group_idx].grad + total_norm_sq += host_grad.float().norm(2).item()**2 elif optimizer.accumulated_grads_in_cpu[group_idx] is not None: total_norm_sq += optimizer.accumulated_grads_in_cpu[group_idx].float().norm(2).item()**2 return total_norm_sq**0.5 @@ -90,7 +94,7 @@ def test(self): model.destroy() - assert norms[0] > 0, "running gradient sum should be non-zero after first backward" + assert all(norm > 0 for norm in norms), f"running gradient sum should stay non-zero: {norms}" for i in range(1, len(norms)): assert norms[i] != norms[0], (f"running gradient sum norm did not change after micro-step {i}: " f"norm[0]={norms[0]:.6f}, norm[{i}]={norms[i]:.6f}. " From b1859ac8d2e314c38121708074b1124bde7c0e82 Mon Sep 17 00:00:00 2001 From: Olatunji Ruwase Date: Mon, 9 Nov 2026 16:11:24 +0000 Subject: [PATCH 05/12] Fix fp16 host overflow test to use managed accumulation Signed-off-by: Olatunji Ruwase --- tests/unit/v1/zero/test_zero2_offload_multi_backward.py | 1 - 1 file changed, 1 deletion(-) diff --git a/tests/unit/v1/zero/test_zero2_offload_multi_backward.py b/tests/unit/v1/zero/test_zero2_offload_multi_backward.py index e7220b720d61..c06fe3757926 100644 --- a/tests/unit/v1/zero/test_zero2_offload_multi_backward.py +++ b/tests/unit/v1/zero/test_zero2_offload_multi_backward.py @@ -335,7 +335,6 @@ def forward(self, scale): if accumulation_dtype is not None: config["data_types"] = {"grad_accum_dtype": accumulation_dtype} config["train_batch_size"] = 2 - config["managed_gradient_accumulation"] = False model = Scaled() engine, _, _, _ = deepspeed.initialize(model=model, model_parameters=model.parameters(), config=config) try: From 9960ecb7c86ba2e47f3bbd564f8921d5fe2b00ac Mon Sep 17 00:00:00 2001 From: Olatunji Ruwase Date: Mon, 9 Nov 2026 16:31:08 +0000 Subject: [PATCH 06/12] ZeRO-2 offload: use the compact partition buffer only for fp32 accumulation on 16-bit models Restore the gate that applied before this series. Default bf16/fp16 accumulation keeps the per-parameter path, so it does not hold a partition-sized buffer on the device. Signed-off-by: Olatunji Ruwase --- deepspeed/runtime/zero/stage_1_and_2.py | 6 ------ tests/unit/v1/zero/test_zero_cpu_offload_grad_accum.py | 7 ++++++- 2 files changed, 6 insertions(+), 7 deletions(-) diff --git a/deepspeed/runtime/zero/stage_1_and_2.py b/deepspeed/runtime/zero/stage_1_and_2.py index 7dd7c49117b8..bfaa19b91928 100644 --- a/deepspeed/runtime/zero/stage_1_and_2.py +++ b/deepspeed/runtime/zero/stage_1_and_2.py @@ -1298,12 +1298,6 @@ def _use_compact_grad_partition_buffer(self, group_idx): params_in_partition = self.params_in_partition[group_idx] if len(params_in_partition) > 0 and self._is_muon_group(params_in_partition): return False - # Stage-2 CPU offload keeps the running sum in one partition buffer in gradient_accumulation_dtype - # for every dtype, so the host publish is the only dtype conversion. Stage 1 (its unreduced - # grad_accum is cumulative across reentrant phases) and ZenFlow keep their existing gate. - if (getattr(self, "cpu_offload", False) and getattr(self, "partition_gradients", False) - and not getattr(self, "zenflow", False)): - return True gradient_accumulation_dtype = getattr(self, "gradient_accumulation_dtype", None) if gradient_accumulation_dtype != torch.float32 or gradient_accumulation_dtype == self.dtype: return False diff --git a/tests/unit/v1/zero/test_zero_cpu_offload_grad_accum.py b/tests/unit/v1/zero/test_zero_cpu_offload_grad_accum.py index 077ff87358f1..f4311e0c91b9 100644 --- a/tests/unit/v1/zero/test_zero_cpu_offload_grad_accum.py +++ b/tests/unit/v1/zero/test_zero_cpu_offload_grad_accum.py @@ -11,6 +11,7 @@ underestimated. """ +import pytest import torch import deepspeed @@ -41,7 +42,8 @@ def _running_grad_norm(engine): class TestZero2CPUOffloadGradAccumNorm(DistributedTest): world_size = 1 - def test(self): + @pytest.mark.parametrize("accumulation_dtype", [None, "fp32"]) + def test(self, accumulation_dtype): gradient_accumulation_steps = 4 hidden_dim = 10 @@ -65,6 +67,9 @@ def test(self): }, } + if accumulation_dtype is not None: + config_dict["data_types"] = {"grad_accum_dtype": accumulation_dtype} + if get_accelerator().is_bf16_supported(): config_dict["bf16"] = {"enabled": True} elif get_accelerator().is_fp16_supported(): From ebf01123d1fa04639a4bf57bc85f84a1a9475747 Mon Sep 17 00:00:00 2001 From: Olatunji Ruwase Date: Mon, 9 Nov 2026 22:18:47 +0000 Subject: [PATCH 07/12] Test ZeRO-1/2 offload window-sum precision and set_full_grad residency Characterize the window sum for stage x master x accumulation with bf16-exact micro-step gradients: stage 2 with fp32 masters and fp32 accumulation is exact; other cells round once (bf16 accumulation, or the host copy for bf16 masters). Also pin safe_set_full_grad: a value set after a freed boundary is kept and accumulated; one set while the partition is resident is overwritten at the boundary. Signed-off-by: Olatunji Ruwase Co-authored-by: Cursor --- .../zero/test_zero_offload_accum_precision.py | 168 ++++++++++++++++++ 1 file changed, 168 insertions(+) create mode 100644 tests/unit/v1/zero/test_zero_offload_accum_precision.py diff --git a/tests/unit/v1/zero/test_zero_offload_accum_precision.py b/tests/unit/v1/zero/test_zero_offload_accum_precision.py new file mode 100644 index 000000000000..ec4cbb6c88fa --- /dev/null +++ b/tests/unit/v1/zero/test_zero_offload_accum_precision.py @@ -0,0 +1,168 @@ +# SPDX-License-Identifier: Apache-2.0 +# DeepSpeed Team +""" +Accumulation precision of ZeRO-1/2 CPU offload across one optimizer window. + +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 +copy, which makes the error of each (stage, master dtype, accumulation dtype) cell directly +comparable. +""" + +import os + +import pytest +import torch + +import deepspeed +from deepspeed.utils import safe_get_full_grad + +from unit.common import DistributedTest +from deepspeed.accelerator import get_accelerator + +MICRO_STEPS = 16 +NUMEL = 16 + + +class Weighted(torch.nn.Module): + + def __init__(self, numel): + super().__init__() + self.w = torch.nn.Parameter(torch.zeros(numel)) + + def forward(self, c): + return (self.w * c).sum() + + +def _config(stage, low_precision_master, accumulation_dtype): + config = { + "train_batch_size": 1, + "gradient_accumulation_steps": 1, + "train_micro_batch_size_per_gpu": 1, + "gradient_clipping": 0, + "zero_allow_untested_optimizer": True, + "zero_force_ds_cpu_optimizer": False, + "optimizer": { + "type": "Adam", + "params": { + "lr": 1e-3 + } + }, + "zero_optimization": { + "stage": stage, + "offload_optimizer": { + "device": "cpu", + "pin_memory": False + }, + }, + "bf16": { + "enabled": True, + "bf16_master_weights_and_grads": low_precision_master, + }, + } + if accumulation_dtype is not None: + config["data_types"] = {"grad_accum_dtype": accumulation_dtype} + return config + + +def _window_error(stage, low_precision_master, accumulation_dtype): + """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=_config(stage, low_precision_master, accumulation_dtype)) + 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.bfloat16) + 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() + return ((grad - exact).abs().max() / exact.abs().max()).item() + finally: + engine.destroy() + + +@pytest.mark.parametrize("stage", [1, 2]) +@pytest.mark.parametrize("low_precision_master", [False, True], ids=["fp32-master", "bf16-master"]) +@pytest.mark.parametrize("accumulation_dtype", [None, "fp32"], ids=["bf16-accum", "fp32-accum"]) +class TestZeroOffloadAccumPrecision(DistributedTest): + world_size = 1 + + def test_window_sum(self, stage, low_precision_master, accumulation_dtype): + if not deepspeed.ops.__compatible_ops__[deepspeed.ops.op_builder.CPUAdamBuilder.NAME]: + pytest.skip("CPUAdam is required for offloaded low-precision masters") + if not get_accelerator().is_bf16_supported(): + pytest.skip("BF16 is not supported") + error = _window_error(stage, low_precision_master, accumulation_dtype) + out = os.environ.get("ACCUM_PRECISION_OUT") + if out: + 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. + assert error == 0.0, f"fp32 accumulation with fp32 masters lost precision: {error:.3e}" + + +def _set_grad_error(scenario, stage=2): + """Drive safe_set_full_grad between two backwards in one window and return the window sum read at its end. + + Returns the value written by safe_get_full_grad minus the sum the caller would expect if the set value + were kept and accumulated into: scenario "mid_window" sets while the GPU partition is resident (after the + first backward of a window); "after_boundary" sets after a boundary freed the partition. + """ + from deepspeed.utils import safe_set_full_grad + torch.manual_seed(0) + model = Weighted(NUMEL) + engine, _, _, _ = deepspeed.initialize(model=model, + model_parameters=model.parameters(), + config=_config(stage, False, "fp32")) + try: + ones = torch.ones(NUMEL, device=engine.device, dtype=torch.bfloat16) + c1 = (torch.arange(NUMEL, device=engine.device) % 7 + 128).float().div(128).to(torch.bfloat16) + c2 = (torch.arange(NUMEL, device=engine.device) % 5 + 129).float().div(128).to(torch.bfloat16) + value = torch.full((NUMEL, ), 0.5, device=engine.device, dtype=torch.float32) + if scenario == "mid_window": + engine.set_gradient_accumulation_boundary(False) + engine.backward(engine(c1)) + safe_set_full_grad(engine.module.w, value) + engine.set_gradient_accumulation_boundary(True) + engine.backward(engine(c2)) + expected = value + c2.float() + else: + engine.set_gradient_accumulation_boundary(True) + engine.backward(engine(c1)) + safe_set_full_grad(engine.module.w, value) + engine.set_gradient_accumulation_boundary(True) + engine.backward(engine(c2)) + expected = value + c2.float() + grad = safe_get_full_grad(engine.module.w).detach().float().cpu() + return (grad - expected.cpu()).abs().max().item(), (grad - (c1 + c2).float().cpu()).abs().max().item() + finally: + engine.destroy() + + +class TestZeroOffloadSetFullGrad(DistributedTest): + world_size = 1 + + @pytest.mark.parametrize("scenario", ["mid_window", "after_boundary"]) + def test_set_full_grad_between_backwards(self, scenario): + if not deepspeed.ops.__compatible_ops__[deepspeed.ops.op_builder.CPUAdamBuilder.NAME]: + pytest.skip("CPUAdam is required for offloaded low-precision masters") + err_expected, err_overwritten = _set_grad_error(scenario) + out = os.environ.get("ACCUM_PRECISION_OUT") + if out: + with open(out, "a") as f: + f.write(f"set_full_grad scenario={scenario} err_if_kept={err_expected:.3e} " + f"err_if_overwritten={err_overwritten:.3e}\n") + if scenario == "after_boundary": + assert err_expected < 1e-6, "a value set after a freed boundary must be kept and accumulated" + else: + # Characterizes the resident case: the boundary overwrites the set value (not kept). + assert err_overwritten < 1e-2, "mid-window set is no longer overwritten at the boundary" From 7273449e81e1cfe8e8c8db6369cc19d21a608aea Mon Sep 17 00:00:00 2001 From: Olatunji Ruwase Date: Tue, 10 Nov 2026 00:56:25 +0000 Subject: [PATCH 08/12] Add zero_optimization.release_compact_grad_partition With ZeRO-2 CPU offload and fp32 accumulation on a 16-bit model, the compact GPU partition is freed after each request boundary by default. Setting release_compact_grad_partition=false keeps it resident until step(), trading one fp32 partition of device memory for no per-request host copy and restore. Test: residency per boundary and final weights match in both settings. Signed-off-by: Olatunji Ruwase Co-authored-by: Cursor --- deepspeed/runtime/engine.py | 6 ++- deepspeed/runtime/zero/config.py | 9 ++++ deepspeed/runtime/zero/stage_1_and_2.py | 6 ++- .../zero/test_zero_offload_accum_precision.py | 43 +++++++++++++++++++ 4 files changed, 62 insertions(+), 2 deletions(-) diff --git a/deepspeed/runtime/engine.py b/deepspeed/runtime/engine.py index b52e81d9ca4f..6aa65c5ad5ca 100644 --- a/deepspeed/runtime/engine.py +++ b/deepspeed/runtime/engine.py @@ -1631,6 +1631,9 @@ def zero_allgather_bucket_size(self): def zero_compute_grad_norm(self): return self._config.zero_config.compute_grad_norm + def zero_release_compact_grad_partition(self): + return self._config.zero_config.release_compact_grad_partition + def zero_optimization_partition_gradients(self): return self.zero_optimization_stage() >= ZeroStageEnum.gradients @@ -2723,7 +2726,8 @@ def _configure_zero_optimizer(self, optimizer): communication_data_type=self.communication_data_type, elastic_checkpoint=self.zero_elastic_checkpoint(), check_grad_overflow=check_grad_overflow, - compute_grad_norm=self.zero_compute_grad_norm()) + compute_grad_norm=self.zero_compute_grad_norm(), + release_compact_grad_partition=self.zero_release_compact_grad_partition()) elif zero_stage == ZeroStageEnum.weights: self._validate_zero3_moe_compatibility() diff --git a/deepspeed/runtime/zero/config.py b/deepspeed/runtime/zero/config.py index ac2ff3c40e29..807762ba2b8a 100644 --- a/deepspeed/runtime/zero/config.py +++ b/deepspeed/runtime/zero/config.py @@ -147,6 +147,15 @@ class DeepSpeedZeroConfig(DeepSpeedConfigModel): and callers do not use ``get_global_grad_norm()``. """ + release_compact_grad_partition: bool = True + """ + With ZeRO-2 CPU optimizer offload and fp32 gradient accumulation on a 16-bit model, free the + device gradient partition after each request boundary and restore it from the host gradient for + the next backward. Set to ``false`` to keep the partition resident until ``step()``: this costs + device memory of one fp32 partition per rank, but avoids the per-request host copy and restore. + Has no effect on configurations that do not use the compact partition buffer. + """ + load_from_fp32_weights: bool = Field(True, json_schema_extra={"deprecated": True}) """ Deprecated and ignored by ``DeepSpeedEngine.load_checkpoint``. Full ZeRO diff --git a/deepspeed/runtime/zero/stage_1_and_2.py b/deepspeed/runtime/zero/stage_1_and_2.py index bfaa19b91928..ed71327899e5 100644 --- a/deepspeed/runtime/zero/stage_1_and_2.py +++ b/deepspeed/runtime/zero/stage_1_and_2.py @@ -205,10 +205,12 @@ def __init__(self, bf16_optimizer_states=False, elastic_checkpoint=False, check_grad_overflow=True, - compute_grad_norm=True): + compute_grad_norm=True, + release_compact_grad_partition=True): super().__init__() + self.release_compact_grad_partition = release_compact_grad_partition if not compute_grad_norm and clip_grad > 0.0: raise ValueError("zero_optimization.compute_grad_norm=false requires gradient_clipping=0") if not compute_grad_norm and zenflow_config is not None: @@ -1393,6 +1395,8 @@ def _offload_compact_grad_partitions(self): continue if not self._offload_gradient_safety_enabled: continue + if not self.release_compact_grad_partition: + continue self._record_gradient_stream(grad_group.flat_partition, stream) self.averaged_gradients[group_idx] = None self._host_owned_compact_partitions.add(group_idx) 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 ec4cbb6c88fa..02a521f1c63b 100644 --- a/tests/unit/v1/zero/test_zero_offload_accum_precision.py +++ b/tests/unit/v1/zero/test_zero_offload_accum_precision.py @@ -166,3 +166,46 @@ def test_set_full_grad_between_backwards(self, scenario): else: # Characterizes the resident case: the boundary overwrites the set value (not kept). assert err_overwritten < 1e-2, "mid-window set is no longer overwritten at the boundary" + + +def _release_option_run(release): + """Three request-boundary backwards and one step; returns residency per boundary, grads, and final weight.""" + torch.manual_seed(0) + model = Weighted(NUMEL) + config = _config(2, False, "fp32") + config["zero_optimization"]["release_compact_grad_partition"] = release + engine, _, _, _ = deepspeed.initialize(model=model, model_parameters=model.parameters(), config=config) + try: + generator = torch.Generator().manual_seed(99) + exact = torch.zeros(NUMEL, dtype=torch.float64) + resident = [] # True while the GPU partition is held + for _ in range(3): + k = torch.randint(0, 128, (NUMEL, ), generator=generator) + c = ((128 + k).float() / 128).to(device=engine.device, dtype=torch.bfloat16) + exact += c.double().cpu() + engine.set_gradient_accumulation_boundary(True) + engine.backward(engine(c)) + resident.append(engine.optimizer.averaged_gradients.get(0) is not None) + grad = safe_get_full_grad(engine.module.w).detach().float().cpu().double() + engine.step() + weight = engine.module.w.detach().float().cpu().clone() + return resident, (grad - exact).abs().max().item(), weight + finally: + engine.destroy() + + +class TestZeroOffloadReleaseOption(DistributedTest): + world_size = 1 + + def test_release_option_controls_residency_without_changing_results(self): + if not deepspeed.ops.__compatible_ops__[deepspeed.ops.op_builder.CPUAdamBuilder.NAME]: + pytest.skip("CPUAdam is required for offloaded low-precision masters") + resident_released, err_released, w_released = _release_option_run(True) + resident_kept, err_kept, w_kept = _release_option_run(False) + # `resident` is True while the GPU partition is held. With the option on, every boundary frees it. + assert resident_released == [False, False, + False], f"partition stayed resident with the option on: {resident_released}" + assert resident_kept == [True, True, True], f"partition was freed with the option off: {resident_kept}" + 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" From fb2afb9cb60039025e9eae7a88f5e49733a6ee22 Mon Sep 17 00:00:00 2001 From: Olatunji Ruwase Date: Tue, 10 Nov 2026 11:31:41 +0000 Subject: [PATCH 09/12] Rename release_compact_grad_partition to free_hbm_grad_partition_between_requests The new name states what the option controls: whether the fp32 gradient partition is freed from GPU HBM between requests. No behavior change. Signed-off-by: Olatunji Ruwase Co-authored-by: Cursor --- deepspeed/runtime/engine.py | 6 +++--- deepspeed/runtime/zero/config.py | 11 ++++++----- deepspeed/runtime/zero/stage_1_and_2.py | 6 +++--- .../unit/v1/zero/test_zero_offload_accum_precision.py | 2 +- 4 files changed, 13 insertions(+), 12 deletions(-) diff --git a/deepspeed/runtime/engine.py b/deepspeed/runtime/engine.py index 6aa65c5ad5ca..be45482b5776 100644 --- a/deepspeed/runtime/engine.py +++ b/deepspeed/runtime/engine.py @@ -1631,8 +1631,8 @@ def zero_allgather_bucket_size(self): def zero_compute_grad_norm(self): return self._config.zero_config.compute_grad_norm - def zero_release_compact_grad_partition(self): - return self._config.zero_config.release_compact_grad_partition + def zero_free_hbm_grad_partition_between_requests(self): + return self._config.zero_config.free_hbm_grad_partition_between_requests def zero_optimization_partition_gradients(self): return self.zero_optimization_stage() >= ZeroStageEnum.gradients @@ -2727,7 +2727,7 @@ def _configure_zero_optimizer(self, optimizer): elastic_checkpoint=self.zero_elastic_checkpoint(), check_grad_overflow=check_grad_overflow, compute_grad_norm=self.zero_compute_grad_norm(), - release_compact_grad_partition=self.zero_release_compact_grad_partition()) + free_hbm_grad_partition_between_requests=self.zero_free_hbm_grad_partition_between_requests()) elif zero_stage == ZeroStageEnum.weights: self._validate_zero3_moe_compatibility() diff --git a/deepspeed/runtime/zero/config.py b/deepspeed/runtime/zero/config.py index 807762ba2b8a..3a04e6819f20 100644 --- a/deepspeed/runtime/zero/config.py +++ b/deepspeed/runtime/zero/config.py @@ -147,13 +147,14 @@ class DeepSpeedZeroConfig(DeepSpeedConfigModel): and callers do not use ``get_global_grad_norm()``. """ - release_compact_grad_partition: bool = True + free_hbm_grad_partition_between_requests: bool = True """ With ZeRO-2 CPU optimizer offload and fp32 gradient accumulation on a 16-bit model, free the - device gradient partition after each request boundary and restore it from the host gradient for - the next backward. Set to ``false`` to keep the partition resident until ``step()``: this costs - device memory of one fp32 partition per rank, but avoids the per-request host copy and restore. - Has no effect on configurations that do not use the compact partition buffer. + fp32 gradient partition in GPU HBM after each request boundary, and restore it from the host + gradient for the next backward. This lowers HBM use between requests by one fp32 partition per + rank. Set to ``false`` to keep that partition in HBM until ``step()``: HBM use between requests + rises by one fp32 partition per rank, and the per-request host copy and restore are avoided. + Has no effect on configurations that do not use the compact gradient partition. """ load_from_fp32_weights: bool = Field(True, json_schema_extra={"deprecated": True}) diff --git a/deepspeed/runtime/zero/stage_1_and_2.py b/deepspeed/runtime/zero/stage_1_and_2.py index ed71327899e5..468d3c50a8a7 100644 --- a/deepspeed/runtime/zero/stage_1_and_2.py +++ b/deepspeed/runtime/zero/stage_1_and_2.py @@ -206,11 +206,11 @@ def __init__(self, elastic_checkpoint=False, check_grad_overflow=True, compute_grad_norm=True, - release_compact_grad_partition=True): + free_hbm_grad_partition_between_requests=True): super().__init__() - self.release_compact_grad_partition = release_compact_grad_partition + self.free_hbm_grad_partition_between_requests = free_hbm_grad_partition_between_requests if not compute_grad_norm and clip_grad > 0.0: raise ValueError("zero_optimization.compute_grad_norm=false requires gradient_clipping=0") if not compute_grad_norm and zenflow_config is not None: @@ -1395,7 +1395,7 @@ def _offload_compact_grad_partitions(self): continue if not self._offload_gradient_safety_enabled: continue - if not self.release_compact_grad_partition: + if not self.free_hbm_grad_partition_between_requests: continue self._record_gradient_stream(grad_group.flat_partition, stream) self.averaged_gradients[group_idx] = None 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 02a521f1c63b..8fb1df6700f9 100644 --- a/tests/unit/v1/zero/test_zero_offload_accum_precision.py +++ b/tests/unit/v1/zero/test_zero_offload_accum_precision.py @@ -173,7 +173,7 @@ def _release_option_run(release): torch.manual_seed(0) model = Weighted(NUMEL) config = _config(2, False, "fp32") - config["zero_optimization"]["release_compact_grad_partition"] = release + config["zero_optimization"]["free_hbm_grad_partition_between_requests"] = release engine, _, _, _ = deepspeed.initialize(model=model, model_parameters=model.parameters(), config=config) try: generator = torch.Generator().manual_seed(99) From f6d73eac6c8c85560d0527e234d77a15c3fce8b4 Mon Sep 17 00:00:00 2001 From: Olatunji Ruwase Date: Tue, 10 Nov 2026 11:36:47 +0000 Subject: [PATCH 10/12] Rename free_hbm_grad_partition_between_requests to free_hbm_grad_partition_cache No behavior change. Signed-off-by: Olatunji Ruwase Co-authored-by: Cursor --- deepspeed/runtime/engine.py | 6 +++--- deepspeed/runtime/zero/config.py | 2 +- deepspeed/runtime/zero/stage_1_and_2.py | 6 +++--- tests/unit/v1/zero/test_zero_offload_accum_precision.py | 2 +- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/deepspeed/runtime/engine.py b/deepspeed/runtime/engine.py index be45482b5776..9098d1db484b 100644 --- a/deepspeed/runtime/engine.py +++ b/deepspeed/runtime/engine.py @@ -1631,8 +1631,8 @@ def zero_allgather_bucket_size(self): def zero_compute_grad_norm(self): return self._config.zero_config.compute_grad_norm - def zero_free_hbm_grad_partition_between_requests(self): - return self._config.zero_config.free_hbm_grad_partition_between_requests + def zero_free_hbm_grad_partition_cache(self): + return self._config.zero_config.free_hbm_grad_partition_cache def zero_optimization_partition_gradients(self): return self.zero_optimization_stage() >= ZeroStageEnum.gradients @@ -2727,7 +2727,7 @@ def _configure_zero_optimizer(self, optimizer): elastic_checkpoint=self.zero_elastic_checkpoint(), check_grad_overflow=check_grad_overflow, compute_grad_norm=self.zero_compute_grad_norm(), - free_hbm_grad_partition_between_requests=self.zero_free_hbm_grad_partition_between_requests()) + free_hbm_grad_partition_cache=self.zero_free_hbm_grad_partition_cache()) elif zero_stage == ZeroStageEnum.weights: self._validate_zero3_moe_compatibility() diff --git a/deepspeed/runtime/zero/config.py b/deepspeed/runtime/zero/config.py index 3a04e6819f20..e219c8a5d85a 100644 --- a/deepspeed/runtime/zero/config.py +++ b/deepspeed/runtime/zero/config.py @@ -147,7 +147,7 @@ class DeepSpeedZeroConfig(DeepSpeedConfigModel): and callers do not use ``get_global_grad_norm()``. """ - free_hbm_grad_partition_between_requests: bool = True + free_hbm_grad_partition_cache: bool = True """ With ZeRO-2 CPU optimizer offload and fp32 gradient accumulation on a 16-bit model, free the fp32 gradient partition in GPU HBM after each request boundary, and restore it from the host diff --git a/deepspeed/runtime/zero/stage_1_and_2.py b/deepspeed/runtime/zero/stage_1_and_2.py index 468d3c50a8a7..0fc071ee5ea2 100644 --- a/deepspeed/runtime/zero/stage_1_and_2.py +++ b/deepspeed/runtime/zero/stage_1_and_2.py @@ -206,11 +206,11 @@ def __init__(self, elastic_checkpoint=False, check_grad_overflow=True, compute_grad_norm=True, - free_hbm_grad_partition_between_requests=True): + free_hbm_grad_partition_cache=True): super().__init__() - self.free_hbm_grad_partition_between_requests = free_hbm_grad_partition_between_requests + self.free_hbm_grad_partition_cache = free_hbm_grad_partition_cache if not compute_grad_norm and clip_grad > 0.0: raise ValueError("zero_optimization.compute_grad_norm=false requires gradient_clipping=0") if not compute_grad_norm and zenflow_config is not None: @@ -1395,7 +1395,7 @@ def _offload_compact_grad_partitions(self): continue if not self._offload_gradient_safety_enabled: continue - if not self.free_hbm_grad_partition_between_requests: + if not self.free_hbm_grad_partition_cache: continue self._record_gradient_stream(grad_group.flat_partition, stream) self.averaged_gradients[group_idx] = None 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 8fb1df6700f9..943e2251b29e 100644 --- a/tests/unit/v1/zero/test_zero_offload_accum_precision.py +++ b/tests/unit/v1/zero/test_zero_offload_accum_precision.py @@ -173,7 +173,7 @@ def _release_option_run(release): torch.manual_seed(0) model = Weighted(NUMEL) config = _config(2, False, "fp32") - config["zero_optimization"]["free_hbm_grad_partition_between_requests"] = release + config["zero_optimization"]["free_hbm_grad_partition_cache"] = release engine, _, _, _ = deepspeed.initialize(model=model, model_parameters=model.parameters(), config=config) try: generator = torch.Generator().manual_seed(99) From ef34708fe1b9e58345016bb59891d5c957a4b771 Mon Sep 17 00:00:00 2001 From: Olatunji Ruwase Date: Tue, 10 Nov 2026 11:44:09 +0000 Subject: [PATCH 11/12] Rename to retain_hbm_grad_partition (default false) Invert the flag: retain_hbm_grad_partition=true keeps the fp32 gradient partition in HBM until step(); the default false frees it between requests, as before. Behavior at the default is unchanged. Signed-off-by: Olatunji Ruwase Co-authored-by: Cursor --- deepspeed/runtime/engine.py | 6 +++--- deepspeed/runtime/zero/config.py | 12 ++++++------ deepspeed/runtime/zero/stage_1_and_2.py | 6 +++--- .../v1/zero/test_zero_offload_accum_precision.py | 8 ++++---- 4 files changed, 16 insertions(+), 16 deletions(-) diff --git a/deepspeed/runtime/engine.py b/deepspeed/runtime/engine.py index 9098d1db484b..61a60919374c 100644 --- a/deepspeed/runtime/engine.py +++ b/deepspeed/runtime/engine.py @@ -1631,8 +1631,8 @@ def zero_allgather_bucket_size(self): def zero_compute_grad_norm(self): return self._config.zero_config.compute_grad_norm - def zero_free_hbm_grad_partition_cache(self): - return self._config.zero_config.free_hbm_grad_partition_cache + def zero_retain_hbm_grad_partition(self): + return self._config.zero_config.retain_hbm_grad_partition def zero_optimization_partition_gradients(self): return self.zero_optimization_stage() >= ZeroStageEnum.gradients @@ -2727,7 +2727,7 @@ def _configure_zero_optimizer(self, optimizer): elastic_checkpoint=self.zero_elastic_checkpoint(), check_grad_overflow=check_grad_overflow, compute_grad_norm=self.zero_compute_grad_norm(), - free_hbm_grad_partition_cache=self.zero_free_hbm_grad_partition_cache()) + retain_hbm_grad_partition=self.zero_retain_hbm_grad_partition()) elif zero_stage == ZeroStageEnum.weights: self._validate_zero3_moe_compatibility() diff --git a/deepspeed/runtime/zero/config.py b/deepspeed/runtime/zero/config.py index e219c8a5d85a..bf6718a3e10e 100644 --- a/deepspeed/runtime/zero/config.py +++ b/deepspeed/runtime/zero/config.py @@ -147,13 +147,13 @@ class DeepSpeedZeroConfig(DeepSpeedConfigModel): and callers do not use ``get_global_grad_norm()``. """ - free_hbm_grad_partition_cache: bool = True + retain_hbm_grad_partition: bool = False """ - With ZeRO-2 CPU optimizer offload and fp32 gradient accumulation on a 16-bit model, free the - fp32 gradient partition in GPU HBM after each request boundary, and restore it from the host - gradient for the next backward. This lowers HBM use between requests by one fp32 partition per - rank. Set to ``false`` to keep that partition in HBM until ``step()``: HBM use between requests - rises by one fp32 partition per rank, and the per-request host copy and restore are avoided. + With ZeRO-2 CPU optimizer offload and fp32 gradient accumulation on a 16-bit model, the fp32 + gradient partition is freed from GPU HBM after each request boundary and restored from the host + gradient for the next backward. This is the default and keeps HBM use between requests low. + Set to ``true`` to keep the partition in HBM until ``step()``: HBM use between requests rises by + one fp32 partition per rank, and the per-request host copy and restore are avoided. Has no effect on configurations that do not use the compact gradient partition. """ diff --git a/deepspeed/runtime/zero/stage_1_and_2.py b/deepspeed/runtime/zero/stage_1_and_2.py index 0fc071ee5ea2..7c40e0637dd9 100644 --- a/deepspeed/runtime/zero/stage_1_and_2.py +++ b/deepspeed/runtime/zero/stage_1_and_2.py @@ -206,11 +206,11 @@ def __init__(self, elastic_checkpoint=False, check_grad_overflow=True, compute_grad_norm=True, - free_hbm_grad_partition_cache=True): + retain_hbm_grad_partition=False): super().__init__() - self.free_hbm_grad_partition_cache = free_hbm_grad_partition_cache + self.retain_hbm_grad_partition = retain_hbm_grad_partition if not compute_grad_norm and clip_grad > 0.0: raise ValueError("zero_optimization.compute_grad_norm=false requires gradient_clipping=0") if not compute_grad_norm and zenflow_config is not None: @@ -1395,7 +1395,7 @@ def _offload_compact_grad_partitions(self): continue if not self._offload_gradient_safety_enabled: continue - if not self.free_hbm_grad_partition_cache: + if self.retain_hbm_grad_partition: continue self._record_gradient_stream(grad_group.flat_partition, stream) self.averaged_gradients[group_idx] = None 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 943e2251b29e..9efed5405599 100644 --- a/tests/unit/v1/zero/test_zero_offload_accum_precision.py +++ b/tests/unit/v1/zero/test_zero_offload_accum_precision.py @@ -168,12 +168,12 @@ def test_set_full_grad_between_backwards(self, scenario): assert err_overwritten < 1e-2, "mid-window set is no longer overwritten at the boundary" -def _release_option_run(release): +def _retain_option_run(retain): """Three request-boundary backwards and one step; returns residency per boundary, grads, and final weight.""" torch.manual_seed(0) model = Weighted(NUMEL) config = _config(2, False, "fp32") - config["zero_optimization"]["free_hbm_grad_partition_cache"] = release + config["zero_optimization"]["retain_hbm_grad_partition"] = retain engine, _, _, _ = deepspeed.initialize(model=model, model_parameters=model.parameters(), config=config) try: generator = torch.Generator().manual_seed(99) @@ -200,8 +200,8 @@ class TestZeroOffloadReleaseOption(DistributedTest): def test_release_option_controls_residency_without_changing_results(self): if not deepspeed.ops.__compatible_ops__[deepspeed.ops.op_builder.CPUAdamBuilder.NAME]: pytest.skip("CPUAdam is required for offloaded low-precision masters") - resident_released, err_released, w_released = _release_option_run(True) - resident_kept, err_kept, w_kept = _release_option_run(False) + resident_released, err_released, w_released = _retain_option_run(False) + resident_kept, err_kept, w_kept = _retain_option_run(True) # `resident` is True while the GPU partition is held. With the option on, every boundary frees it. assert resident_released == [False, False, False], f"partition stayed resident with the option on: {resident_released}" From 5dd42923423496927d2215b9609311e2ab37fd1e Mon Sep 17 00:00:00 2001 From: Olatunji Ruwase Date: Tue, 10 Nov 2026 16:13:38 +0000 Subject: [PATCH 12/12] Rename to retain_gpu_grad_partition_until_step (default false) Per review: name the memory as GPU rather than HBM (LPDDR-attached GPUs exist) and state the span: the partition is kept until step(), not for each step. Behavior is unchanged. Signed-off-by: Olatunji Ruwase Co-authored-by: Cursor --- deepspeed/runtime/engine.py | 6 +++--- deepspeed/runtime/zero/config.py | 10 +++++----- deepspeed/runtime/zero/stage_1_and_2.py | 8 ++++---- .../unit/v1/zero/test_zero_offload_accum_precision.py | 2 +- 4 files changed, 13 insertions(+), 13 deletions(-) diff --git a/deepspeed/runtime/engine.py b/deepspeed/runtime/engine.py index 61a60919374c..cb0a9322b07a 100644 --- a/deepspeed/runtime/engine.py +++ b/deepspeed/runtime/engine.py @@ -1631,8 +1631,8 @@ def zero_allgather_bucket_size(self): def zero_compute_grad_norm(self): return self._config.zero_config.compute_grad_norm - def zero_retain_hbm_grad_partition(self): - return self._config.zero_config.retain_hbm_grad_partition + def zero_retain_gpu_grad_partition_until_step(self): + return self._config.zero_config.retain_gpu_grad_partition_until_step def zero_optimization_partition_gradients(self): return self.zero_optimization_stage() >= ZeroStageEnum.gradients @@ -2727,7 +2727,7 @@ def _configure_zero_optimizer(self, optimizer): elastic_checkpoint=self.zero_elastic_checkpoint(), check_grad_overflow=check_grad_overflow, compute_grad_norm=self.zero_compute_grad_norm(), - retain_hbm_grad_partition=self.zero_retain_hbm_grad_partition()) + retain_gpu_grad_partition_until_step=self.zero_retain_gpu_grad_partition_until_step()) elif zero_stage == ZeroStageEnum.weights: self._validate_zero3_moe_compatibility() diff --git a/deepspeed/runtime/zero/config.py b/deepspeed/runtime/zero/config.py index bf6718a3e10e..72791ecc6ba9 100644 --- a/deepspeed/runtime/zero/config.py +++ b/deepspeed/runtime/zero/config.py @@ -147,13 +147,13 @@ class DeepSpeedZeroConfig(DeepSpeedConfigModel): and callers do not use ``get_global_grad_norm()``. """ - retain_hbm_grad_partition: bool = False + retain_gpu_grad_partition_until_step: bool = False """ With ZeRO-2 CPU optimizer offload and fp32 gradient accumulation on a 16-bit model, the fp32 - gradient partition is freed from GPU HBM after each request boundary and restored from the host - gradient for the next backward. This is the default and keeps HBM use between requests low. - Set to ``true`` to keep the partition in HBM until ``step()``: HBM use between requests rises by - one fp32 partition per rank, and the per-request host copy and restore are avoided. + gradient partition is freed from GPU memory after each request boundary and restored from the host + gradient for the next backward. This is the default and keeps GPU memory use between requests low. + Set to ``true`` to keep the partition in GPU memory until ``step()``: GPU memory use between + requests rises by one fp32 partition per rank, and the per-request host copy and restore are avoided. Has no effect on configurations that do not use the compact gradient partition. """ diff --git a/deepspeed/runtime/zero/stage_1_and_2.py b/deepspeed/runtime/zero/stage_1_and_2.py index 7c40e0637dd9..18cc05b6248b 100644 --- a/deepspeed/runtime/zero/stage_1_and_2.py +++ b/deepspeed/runtime/zero/stage_1_and_2.py @@ -206,11 +206,11 @@ def __init__(self, elastic_checkpoint=False, check_grad_overflow=True, compute_grad_norm=True, - retain_hbm_grad_partition=False): + retain_gpu_grad_partition_until_step=False): super().__init__() - self.retain_hbm_grad_partition = retain_hbm_grad_partition + self.retain_gpu_grad_partition_until_step = retain_gpu_grad_partition_until_step if not compute_grad_norm and clip_grad > 0.0: raise ValueError("zero_optimization.compute_grad_norm=false requires gradient_clipping=0") if not compute_grad_norm and zenflow_config is not None: @@ -1364,7 +1364,7 @@ def _offload_compact_grad_partitions(self): Every parameter accumulated in this window is copied, including one that missed the boundary backward. Once the host holds the exact sum, the GPU partition is freed so it - does not occupy HBM between requests; a later backward in the window restores it. + does not occupy GPU memory between requests; a later backward in the window restores it. """ stream = get_accelerator().current_stream() if self.overlap_comm and self.reduction_stream is not None: @@ -1395,7 +1395,7 @@ def _offload_compact_grad_partitions(self): continue if not self._offload_gradient_safety_enabled: continue - if self.retain_hbm_grad_partition: + if self.retain_gpu_grad_partition_until_step: continue self._record_gradient_stream(grad_group.flat_partition, stream) self.averaged_gradients[group_idx] = None 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 9efed5405599..f54ace64343d 100644 --- a/tests/unit/v1/zero/test_zero_offload_accum_precision.py +++ b/tests/unit/v1/zero/test_zero_offload_accum_precision.py @@ -173,7 +173,7 @@ def _retain_option_run(retain): torch.manual_seed(0) model = Weighted(NUMEL) config = _config(2, False, "fp32") - config["zero_optimization"]["retain_hbm_grad_partition"] = retain + config["zero_optimization"]["retain_gpu_grad_partition_until_step"] = retain engine, _, _, _ = deepspeed.initialize(model=model, model_parameters=model.parameters(), config=config) try: generator = torch.Generator().manual_seed(99)