From ea671a56c2d7663a1a57d11aab5d8702ec060c6e Mon Sep 17 00:00:00 2001 From: Olatunji Ruwase Date: Wed, 5 Aug 2026 15:44:23 +0000 Subject: [PATCH] Extend unmanaged gradient accumulation to ZeRO stage 3 Allow managed_gradient_accumulation=False for ZeRO stage 3 (non-offload). Stage 3 partitions gradients into __param_id_to_grad_partition on every backward (as in managed mode); step() only marks the boundary via finalize_gradient_accumulation_boundary(). Since stage 3 is now permitted, also reject ZeRO parameter offload (previously unreachable). ZeRO offload (optimizer state and parameter) remains rejected pending the follow-up PR; pipeline parallelism, DeepCompile, and Apex AMP stay unsupported. Validated on a 2-GPU node (full -k Unmanaged suite, 29 passed) incl. test_unmanaged_matches_managed[3] and test_unmanaged_varying_backward_count[3]. Signed-off-by: Olatunji Ruwase Co-authored-by: Cursor --- deepspeed/runtime/engine.py | 10 +++--- deepspeed/runtime/zero/stage3.py | 6 ++++ docs/_pages/config-json.md | 2 +- docs/code-docs/source/training.rst | 10 +++--- tests/unit/v1/zero/test_zero_user_backward.py | 32 +++++++++++++------ 5 files changed, 41 insertions(+), 19 deletions(-) diff --git a/deepspeed/runtime/engine.py b/deepspeed/runtime/engine.py index f93888cc219d..83896e2f939a 100755 --- a/deepspeed/runtime/engine.py +++ b/deepspeed/runtime/engine.py @@ -1648,10 +1648,12 @@ def _do_sanity_check(self): f'Client Optimizer (type = {type(self.client_optimizer)} is not instantiated but Client LR Scheduler is instantiated' if not self.managed_gradient_accumulation(): - assert not self.zero_optimization_partition_weights(), \ - "managed_gradient_accumulation=False is only supported for ZeRO stage 0, 1, and 2" - assert self.zero_offload_optimizer() is None, \ + offload_optimizer = self.zero_offload_optimizer() + offload_param = self.zero_offload_param() + assert offload_optimizer is None or offload_optimizer.device == OffloadDeviceEnum.none, \ "managed_gradient_accumulation=False is not supported with ZeRO optimizer state offload" + assert offload_param is None or offload_param.device == OffloadDeviceEnum.none, \ + "managed_gradient_accumulation=False is not supported with ZeRO parameter offload" assert self.zero_optimization_partition_gradients() or not self.zero_overlap_comm(), \ "managed_gradient_accumulation=False supports ZeRO overlap_comm only with ZeRO stage 2" assert not self.pipeline_parallelism, \ @@ -3376,7 +3378,7 @@ def step(self, lr_kwargs=None): # Unmanaged mode: step() is the accumulation boundary. self._running_engine_step = True - # Unmanaged boundary: stage 2 already reduced/partitioned per backward so only finalize; stage 0/1/DDP reduce here. + # Unmanaged boundary: stage 2/3 already reduced/partitioned per backward so only finalize; stage 0/1/DDP reduce here. if not self.managed_gradient_accumulation(): if self.zero_optimization_partition_gradients(): self.optimizer.finalize_gradient_accumulation_boundary() diff --git a/deepspeed/runtime/zero/stage3.py b/deepspeed/runtime/zero/stage3.py index 62cdf6cb9dad..e300a1d369c4 100644 --- a/deepspeed/runtime/zero/stage3.py +++ b/deepspeed/runtime/zero/stage3.py @@ -1349,6 +1349,12 @@ def independent_gradient_partition_epilogue(self): # The increment is deferred to clear_backward_seen_flag() which runs in forward(). self._epilogue_ran_this_backward = True + def finalize_gradient_accumulation_boundary(self): + # Unmanaged mode: grad partitions already accumulate across backwards via __param_id_to_grad_partition; nothing to finalize for non-offload. + assert not self.offload_optimizer and not self.offload_param, \ + "unmanaged gradient accumulation does not support ZeRO offload" + self.is_gradient_accumulation_boundary = True + def overlapping_partition_gradients_reduce_epilogue(self): self.independent_gradient_partition_epilogue() diff --git a/docs/_pages/config-json.md b/docs/_pages/config-json.md index c1a23f92e268..8b4a066314b2 100755 --- a/docs/_pages/config-json.md +++ b/docs/_pages/config-json.md @@ -33,7 +33,7 @@ toc_label: "Contents" | Description | Default | | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | -| Controls how gradient accumulation boundaries are managed. When `true`, DeepSpeed tracks micro-steps and applies the optimizer step only at the accumulation boundary, so `forward`/`backward`/`step` can be called symmetrically on every micro-batch. When `false`, micro-step tracking is disabled and the client is responsible for calling `step()` at the accumulation boundary; each `step()` finalizes the locally-accumulated gradients and applies an optimizer update. The `false` setting currently supports ZeRO stage 0/1/2 (and DDP); ZeRO stage 3 and ZeRO optimizer offload are planned but not yet available (rejected at initialization). It is also incompatible with pipeline parallelism, DeepCompile, and Apex AMP. ZeRO `overlap_comm` is supported only with ZeRO stage 2 (rejected for stage 0/1, where reduction is deferred to `step()`). | `true` | +| Controls how gradient accumulation boundaries are managed. When `true`, DeepSpeed tracks micro-steps and applies the optimizer step only at the accumulation boundary, so `forward`/`backward`/`step` can be called symmetrically on every micro-batch. When `false`, micro-step tracking is disabled and the client is responsible for calling `step()` at the accumulation boundary; each `step()` finalizes the locally-accumulated gradients and applies an optimizer update. The `false` setting currently supports ZeRO stage 0/1/2/3 (and DDP); ZeRO offload (optimizer state and parameter) is planned but not yet available (rejected at initialization). It is also incompatible with pipeline parallelism, DeepCompile, and Apex AMP. ZeRO `overlap_comm` is supported only with ZeRO stage 2 (rejected for stage 0/1, where reduction is deferred to `step()`). | `true` | diff --git a/docs/code-docs/source/training.rst b/docs/code-docs/source/training.rst index 3f7b76d7d086..2cc4f80ff789 100644 --- a/docs/code-docs/source/training.rst +++ b/docs/code-docs/source/training.rst @@ -104,11 +104,11 @@ This is useful when ``backward`` and ``step`` must be decoupled and the number o client- or RPC-driven RL backends where a single optimizer step arrives as ``N`` ``backward()`` calls followed by one ``step()``, with ``N`` unknown at configuration time. -Unmanaged mode currently supports **ZeRO stage 0/1/2 and DDP**. For ZeRO stage 0/1 (and DDP), +Unmanaged mode currently supports **ZeRO stage 0/1/2/3 and DDP**. For ZeRO stage 0/1 (and DDP), ``backward()`` accumulates gradients locally and ``step()`` performs the gradient all-reduce followed -by the optimizer update. For ZeRO stage 2, gradients are reduced/partitioned on every ``backward()`` +by the optimizer update. For ZeRO stage 2/3, gradients are reduced/partitioned on every ``backward()`` (as in managed mode) and ``step()`` finalizes the accumulated partition gradients before the optimizer -update; ZeRO ``overlap_comm`` is supported in this stage-2 path. +update; ZeRO ``overlap_comm`` is supported in the stage-2 path. .. note:: By default ``backward()`` scales the loss and gradients by the configured @@ -120,8 +120,8 @@ update; ZeRO ``overlap_comm`` is supported in this stage-2 path. applies and no manual averaging is needed.) .. note:: - Unmanaged mode is being added incrementally. ZeRO stage 0/1/2 (and DDP) is supported today; - ZeRO stage 3 and ZeRO optimizer offload are planned but **not yet available** -- enabling them + Unmanaged mode is being added incrementally. ZeRO stage 0/1/2/3 (and DDP) is supported today; + ZeRO offload (optimizer state and parameter) is planned but **not yet available** -- enabling it with ``managed_gradient_accumulation=false`` raises an ``AssertionError`` at initialization. Unmanaged mode is likewise incompatible with pipeline parallelism, DeepCompile, and Apex AMP, which are also rejected at initialization. ZeRO ``overlap_comm`` is supported only with ZeRO diff --git a/tests/unit/v1/zero/test_zero_user_backward.py b/tests/unit/v1/zero/test_zero_user_backward.py index 175ce76c6d9d..54059eb2720a 100644 --- a/tests/unit/v1/zero/test_zero_user_backward.py +++ b/tests/unit/v1/zero/test_zero_user_backward.py @@ -1850,7 +1850,7 @@ def build_managed_gas_config(zero_stage, gradient_accumulation_steps, managed_gr } -@pytest.mark.parametrize("zero_stage", [0, 1, 2]) +@pytest.mark.parametrize("zero_stage", [0, 1, 2, 3]) class TestUnmanagedGradientAccumulation(DistributedTest): """managed_gradient_accumulation=False: the caller's step() is the accumulation boundary.""" world_size = 2 @@ -2042,28 +2042,42 @@ def test_set_gradient_accumulation_boundary_rejected(self, zero_stage): class TestUnmanagedGradientAccumulationValidation(DistributedTest): - """Unmanaged mode rejects ZeRO stage 3 and ZeRO offload (until follow-up PRs).""" + """Unmanaged mode rejects ZeRO offload (until follow-up PR).""" world_size = 1 - def test_unmanaged_rejects_stage3(self): + def test_unmanaged_rejects_zero_offload(self): hidden_dim = 4 initialize_distributed() torch.manual_seed(42) model = SimpleModel(hidden_dim=hidden_dim, nlayers=2) - config = build_managed_gas_config(3, gradient_accumulation_steps=1, managed_gradient_accumulation=False) - with pytest.raises(AssertionError, match="only supported for ZeRO stage 0, 1, and 2"): + config = build_managed_gas_config(2, gradient_accumulation_steps=1, managed_gradient_accumulation=False) + config["zero_optimization"]["offload_optimizer"] = {"device": "cpu"} + with pytest.raises(AssertionError, match="not supported with ZeRO optimizer state offload"): deepspeed.initialize(config=config, model=model, model_parameters=model.parameters()) - def test_unmanaged_rejects_zero_offload(self): + def test_unmanaged_rejects_param_offload(self): hidden_dim = 4 initialize_distributed() torch.manual_seed(42) model = SimpleModel(hidden_dim=hidden_dim, nlayers=2) - config = build_managed_gas_config(2, gradient_accumulation_steps=1, managed_gradient_accumulation=False) - config["zero_optimization"]["offload_optimizer"] = {"device": "cpu"} - with pytest.raises(AssertionError, match="not supported with ZeRO optimizer state offload"): + config = build_managed_gas_config(3, gradient_accumulation_steps=1, managed_gradient_accumulation=False) + config["zero_optimization"]["offload_param"] = {"device": "cpu"} + with pytest.raises(AssertionError, match="not supported with ZeRO parameter offload"): deepspeed.initialize(config=config, model=model, model_parameters=model.parameters()) + def test_unmanaged_accepts_disabled_offload_blocks(self): + # A disabled offload block (device="none") is not offload, so init must succeed. + hidden_dim = 4 + initialize_distributed() + torch.manual_seed(42) + model = SimpleModel(hidden_dim=hidden_dim, nlayers=2) + config = build_managed_gas_config(3, gradient_accumulation_steps=1, managed_gradient_accumulation=False) + config["zero_optimization"]["offload_param"] = {"device": "none"} + config["zero_optimization"]["offload_optimizer"] = {"device": "none"} + engine, _, _, _ = deepspeed.initialize(config=config, model=model, model_parameters=model.parameters()) + assert not engine.managed_gradient_accumulation() + engine.destroy() + class TestUnmanagedGradientAccumulationOffloadValidation(DistributedTest): """Unmanaged mode does not support ZeRO optimizer offload (stage 1: before the stage-2/3 guard)."""