diff --git a/deepspeed/module_inject/auto_ep_config.py b/deepspeed/module_inject/auto_ep_config.py index 23da27431c7b..f85746badb25 100644 --- a/deepspeed/module_inject/auto_ep_config.py +++ b/deepspeed/module_inject/auto_ep_config.py @@ -257,10 +257,6 @@ def validate_autoep_config( if tp_size > 1: raise ValueError("deferred_dw_flush_period does not support AutoEP+AutoTP folding yet. Set " "tensor_parallel.autotp_size to 1, or leave deferred_dw_flush_period unset.") - if zero_stage not in (0, 1, 2): - raise ValueError("deferred_dw_flush_period leaves the expert weights without a gradient on the " - f"backward passes that stage, which has not been validated with ZeRO stage " - f"{zero_stage}. Use ZeRO stage 0, 1 or 2, or leave deferred_dw_flush_period unset.") elif rows_per_expert != 0: raise ValueError("deferred_dw_rows_per_expert sizes the staging that deferred_dw_flush_period > 1 enables. " "Set deferred_dw_flush_period, or leave deferred_dw_rows_per_expert unset.") diff --git a/deepspeed/moe/ep_experts.py b/deepspeed/moe/ep_experts.py index 5a7281ba745d..95b76f28b408 100644 --- a/deepspeed/moe/ep_experts.py +++ b/deepspeed/moe/ep_experts.py @@ -319,6 +319,18 @@ def _zero_empty_expert_grad(weight: torch.Tensor, num_tokens_per_expert: torch.T return _ZeroEmptyExpertGrad.apply(weight, num_tokens_per_expert) +def _grouped_mm_weight(weight: torch.Tensor, dtype: torch.dtype) -> torch.Tensor: + """``weight`` in ``dtype``, at an address ``torch._grouped_mm`` accepts. + + The CUDA grouped GEMM needs 16-byte aligned operands. A tensor's own allocation is, but ZeRO-3 gathers a + parameter into a slice of a shared flat buffer, which starts wherever the parameters before it end. + """ + weight = weight.to(dtype) + if weight.data_ptr() % 16 != 0: + weight = weight.clone() + return weight + + def _run_experts_grouped_mm( w1: torch.Tensor, w2: torch.Tensor, @@ -352,18 +364,18 @@ def _run_experts_grouped_mm( w3 = _zero_empty_expert_grad(w3, num_tokens_per_expert) gate = torch._grouped_mm( x.to(cast_dtype), - w1.to(cast_dtype).transpose(-2, -1), + _grouped_mm_weight(w1, cast_dtype).transpose(-2, -1), offs=offsets, ) up = torch._grouped_mm( x.to(cast_dtype), - w3.to(cast_dtype).transpose(-2, -1), + _grouped_mm_weight(w3, cast_dtype).transpose(-2, -1), offs=offsets, ) h = apply_expert_activation(gate, up, activation, alpha, limit) out = torch._grouped_mm( h, - w2.to(cast_dtype).transpose(-2, -1), + _grouped_mm_weight(w2, cast_dtype).transpose(-2, -1), offs=offsets, ).type_as(x) @@ -405,7 +417,7 @@ def _run_experts_grouped_mm_fused_gate_up( h = apply_packed_expert_activation(gate_up, activation, alpha, limit) out = torch._grouped_mm( h, - w2.to(cast_dtype).transpose(-2, -1), + _grouped_mm_weight(w2, cast_dtype).transpose(-2, -1), offs=offsets, ).type_as(x) @@ -694,17 +706,21 @@ def forward(ctx, num_valid_tokens_per_expert=None): offsets = torch.cumsum(num_tokens_per_expert, dim=0, dtype=torch.int32) dtype = x.dtype - w1c, w2c, w3c = w1.to(dtype), w2.to(dtype), w3.to(dtype) + w1c, w2c, w3c = (_grouped_mm_weight(weight.detach(), dtype) for weight in (w1, w2, w3)) + # The parameters are saved, not the tensors computed with: ZeRO-3 releases a parameter's gathered data once + # the module's forward returns and gathers it again for the backward, and a saved alias or copy would keep + # every layer's expert weights allocated in between. The packed gate+up weight is this forward's own copy + # and is kept, since packing it again in the backward costs more than the staging saves. if fused_gate_up: w13 = torch.cat([w1c, w3c], dim=1) gate_up = torch._grouped_mm(x, w13.transpose(-2, -1), offs=offsets) h = apply_packed_expert_activation(gate_up, activation, alpha, limit) - ctx.save_for_backward(x, offsets, w2c, h, w13, gate_up) + ctx.save_for_backward(x, offsets, w2, h, w13, gate_up) else: gate = torch._grouped_mm(x, w1c.transpose(-2, -1), offs=offsets) up = torch._grouped_mm(x, w3c.transpose(-2, -1), offs=offsets) h = apply_expert_activation(gate, up, activation, alpha, limit) - ctx.save_for_backward(x, offsets, w2c, h, w1c, w3c, gate, up) + ctx.save_for_backward(x, offsets, w2, h, w1, w3, gate, up) ctx.slot = slot ctx.dw_staging = dw_staging ctx.num_valid_tokens_per_expert = num_valid_tokens_per_expert @@ -718,7 +734,8 @@ def backward(ctx, grad_out): if torch.is_grad_enabled(): raise RuntimeError("Deferred expert gradients have no second derivative; " "backward with create_graph=True is not supported") - x, offsets, w2c, h, *projection = ctx.saved_tensors + x, offsets, w2, h, *projection = ctx.saved_tensors + w2c = _grouped_mm_weight(w2.detach(), x.dtype) grad_out = grad_out.contiguous() grad_h = torch._grouped_mm(grad_out, w2c, offs=offsets) if ctx.fused_gate_up: @@ -726,7 +743,8 @@ def backward(ctx, grad_out): grad_gate_up = _packed_expert_activation_backward(grad_h, gate_up, *ctx.activation) grad_x = torch._grouped_mm(grad_gate_up, w13, offs=offsets) else: - w1c, w3c, gate, up = projection + w1, w3, gate, up = projection + w1c, w3c = _grouped_mm_weight(w1.detach(), x.dtype), _grouped_mm_weight(w3.detach(), x.dtype) grad_gate, grad_up = _expert_activation_backward(grad_h, gate, up, *ctx.activation) grad_x = torch._grouped_mm(grad_gate, w1c, offs=offsets) + torch._grouped_mm(grad_up, w3c, offs=offsets) diff --git a/deepspeed/runtime/zero/stage3.py b/deepspeed/runtime/zero/stage3.py index 9aea43d03cf9..ab59dd56ef2a 100644 --- a/deepspeed/runtime/zero/stage3.py +++ b/deepspeed/runtime/zero/stage3.py @@ -1784,6 +1784,10 @@ def reduce_independent_p_g_buckets_and_remove_grads(self, param): # 0). Otherwise if the incoming param.ds_numel is large, this branch may get triggered on a # garbage data and `self.average_tensor()` will crash because its params_to_reduce will be # empty, while reduction_list will have that garbage data. + if param.grad is None: + # The hook also fires when the backward delivered no gradient for a parameter in the graph, as when + # AutoEP stages an expert weight gradient for a later backward. There is nothing to reduce yet. + return comm_dtype = self.get_param_comm_dtype(param) bucket = self.ipg_buckets[comm_dtype] param_process_group = self._get_param_partition_group(param) diff --git a/docs/_pages/config-json.md b/docs/_pages/config-json.md index f8c6f4b08f79..3b16d0e68578 100644 --- a/docs/_pages/config-json.md +++ b/docs/_pages/config-json.md @@ -1033,7 +1033,7 @@ smoke coverage used for this AutoEP surface produced the following version gates | Description | Default | | -------------------------------------------------------------------------------------------------------------- | -------- | -| Experimental. Values above `1` stage the rows of the experts' weight-gradient GEMMs across backward passes instead of running the GEMMs in each one. A backward appends each expert's rows to a per-expert staging buffer and returns no expert weight gradient; one backward in every `deferred_dw_flush_period` runs the GEMMs once over everything staged. The backward that closes a gradient accumulation window always does the same, so every optimizer step sees the same accumulated gradient as before, up to floating-point summation order. This helps when each expert receives few rows per microbatch (many experts, small microbatches) and costs memory for the staged rows; with many rows per expert it is slower. First-order gradients only. Requires the `torch._grouped_mm` expert path (`use_grouped_mm=true`, and `disable_triton_grouped_mm=true` on devices that prefer the Triton grouped GEMM), ZeRO stage 0, 1 or 2, and `managed_gradient_accumulation=true`; it cannot be combined with `overlap_weight_grad`, AutoEP+AutoTP folding, ZenFlow or DeepCompile. Unsupported configurations fail rather than falling back. | `1` | +| Experimental. Values above `1` stage the rows of the experts' weight-gradient GEMMs across backward passes instead of running the GEMMs in each one. A backward appends each expert's rows to a per-expert staging buffer and returns no expert weight gradient; one backward in every `deferred_dw_flush_period` runs the GEMMs once over everything staged. The backward that closes a gradient accumulation window always does the same, so every optimizer step sees the same accumulated gradient as before, up to floating-point summation order. This helps when each expert receives few rows per microbatch (many experts, small microbatches) and costs memory for the staged rows; with many rows per expert it is slower. First-order gradients only. Requires the `torch._grouped_mm` expert path (`use_grouped_mm=true`, and `disable_triton_grouped_mm=true` on devices that prefer the Triton grouped GEMM), and `managed_gradient_accumulation=true`; it cannot be combined with `overlap_weight_grad`, AutoEP+AutoTP folding, ZenFlow or DeepCompile. Unsupported configurations fail rather than falling back. | `1` | ***deferred_dw_rows_per_expert***: [integer] diff --git a/docs/code-docs/source/autoep.rst b/docs/code-docs/source/autoep.rst index fac2377e52a5..1edb62ef701e 100644 --- a/docs/code-docs/source/autoep.rst +++ b/docs/code-docs/source/autoep.rst @@ -415,7 +415,7 @@ once. Either result is held, at the size of the expert weight gradients, and returned by the next flush. Which backward returns expert weight gradients therefore depends only on the count of backward passes, not on the routing: ranks that hold replicas of the same experts receive different rows, and ZeRO -stage 2 reduces a gradient across them in the backward that returns it. +stages 2 and 3 reduce a gradient across them in the backward that returns it. Gradient reduction, clipping and the optimizer see what they saw before: the sum over the window. Between flushes the expert weights have no new @@ -452,9 +452,10 @@ no convergence run has been done with this option yet. ``deferred_dw_flush_period`` above ``1`` is rejected, rather than silently ignored, unless the experts run ``torch._grouped_mm`` (``use_grouped_mm=true``, and ``disable_triton_grouped_mm=true`` on devices that select the Triton -grouped GEMM), ZeRO stage is 0, 1 or 2, and ``managed_gradient_accumulation`` -is on. It cannot be combined with ``overlap_weight_grad``, AutoEP+AutoTP -folding, ZenFlow or DeepCompile. It supports first-order gradients only. +grouped GEMM) and ``managed_gradient_accumulation`` is on. It cannot be +combined with ``overlap_weight_grad``, AutoEP+AutoTP folding, ZenFlow or +DeepCompile. It supports first-order gradients only. It runs with ZeRO stages +0 to 3; optimizer and parameter offload have not been validated with it. **DeepEP row weighting implementation (experimental):** diff --git a/tests/unit/v1/moe/test_autoep_expert_activation.py b/tests/unit/v1/moe/test_autoep_expert_activation.py index 37298fc6b424..f441adb892f0 100644 --- a/tests/unit/v1/moe/test_autoep_expert_activation.py +++ b/tests/unit/v1/moe/test_autoep_expert_activation.py @@ -893,6 +893,32 @@ def test_a_period_without_rows_still_returns_a_gradient(self): assert weight.grad is not None assert torch.count_nonzero(weight.grad) == 0 + def test_released_weights_are_not_kept_allocated_for_the_backward(self): + from torch.multiprocessing.reductions import StorageWeakRef + + device, dtype = self._device_and_dtype() + plain, staged = self._experts_pair(device, dtype, "separate") + weights = (staged.w1, staged.w2, staged.w3) + values = [weight.data.clone() for weight in weights] + gathered = [StorageWeakRef(weight.data.untyped_storage()) for weight in weights] + x, grad_out, counts, valid_counts = self._backward_inputs(device, dtype, padded=True)[0] + staging = MoeDeferredDwStaging(4, flush_period=2) + staging.flush_on_stage = True + + output = staged(x, counts, dw_staging=staging, num_valid_tokens_per_expert=valid_counts) + # ZeRO-3 releases a module's gathered weights when its forward returns. A weight the graph still held + # would stay allocated in every layer until its backward runs. + for weight in weights: + weight.data = torch.empty(0, device=device, dtype=dtype) + assert all(storage.expired() for storage in gathered) + + # ZeRO-3 gathers them again for the backward, into another allocation. + for weight, value in zip(weights, values): + weight.data = value + output.backward(grad_out) + plain(x, counts).backward(grad_out) + self._assert_weight_grads_match(staged, plain) + @pytest.mark.parametrize("gate_up_impl", ["separate", "fused"]) @pytest.mark.parametrize("trainable", [(False, True, True), (True, False, True), (True, True, False), (False, False, False)]) @@ -931,6 +957,34 @@ def test_staging_needs_the_grouped_mm_path_and_no_slot(self): with pytest.raises(RuntimeError, match="not both"): experts(torch.randn(4, 8), torch.tensor([2, 2]), ExpertWeightGradSlot(), dw_staging=staging) + @pytest.mark.parametrize("staged", [False, True]) + @pytest.mark.parametrize("gate_up_impl", ["separate", "fused"]) + def test_weights_inside_a_flat_buffer_run(self, gate_up_impl, staged): + device, dtype = self._device_and_dtype() + plain, in_buffer = self._experts_pair(device, dtype, gate_up_impl) + # ZeRO-3 hands the module its weights as slices of one gathered buffer, which need not start at the + # 16-byte boundary the CUDA grouped GEMM requires of its operands. + weights = (in_buffer.w1, in_buffer.w2, in_buffer.w3) + flat = torch.empty(sum(weight.numel() + 1 for weight in weights), device=device, dtype=dtype) + offset = 0 + for weight in weights: + offset += 1 + gathered = flat.narrow(0, offset, weight.numel()).view(weight.shape) + gathered.copy_(weight.data) + weight.data = gathered + offset += weight.numel() + x, grad_out, counts, valid_counts = self._backward_inputs(device, dtype, padded=True)[0] + staging_kwargs = {} + if staged: + staging = MoeDeferredDwStaging(4, flush_period=2) + staging.flush_on_stage = True + staging_kwargs = dict(dw_staging=staging, num_valid_tokens_per_expert=valid_counts) + x_plain, x_in_buffer = x.clone().requires_grad_(True), x.clone().requires_grad_(True) + plain(x_plain, counts).backward(grad_out) + in_buffer(x_in_buffer, counts, **staging_kwargs).backward(grad_out) + torch.testing.assert_close(x_in_buffer.grad, x_plain.grad, rtol=0, atol=0) + self._assert_weight_grads_match(in_buffer, plain) + def test_settings_are_validated(self, monkeypatch): def validate(zero_stage=1, tp_size=1, **settings): @@ -938,7 +992,7 @@ def validate(zero_stage=1, tp_size=1, **settings): validate_autoep_config(config, 2 * tp_size, 1, tp_size, 1, zero_stage=zero_stage) assert parse_autoep_config({"enabled": True}).deferred_dw_flush_period == 1 - for stage in (0, 1, 2): + for stage in (0, 1, 2, 3): validate(deferred_dw_flush_period=4, deferred_dw_rows_per_expert=256, zero_stage=stage) for period in (0, 1.5, True, "4"): with pytest.raises(ValueError, match="deferred_dw_flush_period must be a positive integer"): @@ -950,8 +1004,6 @@ def validate(zero_stage=1, tp_size=1, **settings): validate(deferred_dw_rows_per_expert=256) with pytest.raises(ValueError, match="sequential expert loop"): validate(deferred_dw_flush_period=4, use_grouped_mm=False) - with pytest.raises(ValueError, match="ZeRO stage 3"): - validate(deferred_dw_flush_period=4, zero_stage=3) with pytest.raises(ValueError, match="Enable one of them"): validate(deferred_dw_flush_period=4, overlap_weight_grad=True, diff --git a/tests/unit/v1/moe/test_autoep_grad_parity.py b/tests/unit/v1/moe/test_autoep_grad_parity.py index da6f23ccacce..7c64e32b4bde 100644 --- a/tests/unit/v1/moe/test_autoep_grad_parity.py +++ b/tests/unit/v1/moe/test_autoep_grad_parity.py @@ -814,7 +814,8 @@ class TestAutoEPDeferredDwParity(DistributedTest): def _window_grads(self, zero_stage, ep_size, flush_period, reference_state, seed, rows_per_expert=0): """The expert gradients each of two accumulation windows hands to the optimizer, and the layers' stagings. - The second window starts from the first window's update, so it also covers what that update applied. + The second window starts from the first window's update, so it also covers what that update applied, and + under ZeRO-3 it accumulates into buffers that still hold the first window's gradients. """ model = _make_async_split_model() model.load_state_dict(reference_state) @@ -848,7 +849,7 @@ def _assert_window_grads_match(self, staged_windows, unstaged_windows): atol=2e-2 * expected.abs().max().item(), msg=f"window {window}: {name}") - @pytest.mark.parametrize("zero_stage", [0, 1, 2]) + @pytest.mark.parametrize("zero_stage", [0, 1, 2, 3]) def test_staged_expert_gradients_match_unstaged_over_two_updates(self, zero_stage): _skip_unless_cuda_grouped_mm() ep_size = 2 @@ -864,7 +865,7 @@ def test_staged_expert_gradients_match_unstaged_over_two_updates(self, zero_stag assert not any(staging.has_staged_rows for staging in stagings) self._assert_window_grads_match(staged, unstaged) - @pytest.mark.parametrize("zero_stage", [1, 2]) + @pytest.mark.parametrize("zero_stage", [1, 2, 3]) def test_replicas_that_fill_their_buffers_in_different_backwards_still_reduce_together(self, zero_stage): _skip_unless_cuda_grouped_mm() # Both ranks hold every expert and train on different data, so each expert weight is reduced across them.