Skip to content
Merged
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
10 changes: 6 additions & 4 deletions deepspeed/runtime/engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -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, \
Expand Down Expand Up @@ -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()
Expand Down
6 changes: 6 additions & 0 deletions deepspeed/runtime/zero/stage3.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()

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



Expand Down
10 changes: 5 additions & 5 deletions docs/code-docs/source/training.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
32 changes: 23 additions & 9 deletions tests/unit/v1/zero/test_zero_user_backward.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)."""
Expand Down
Loading