From 42243d788f84a8b256eaf49c33f2cca0dc9fb748 Mon Sep 17 00:00:00 2001 From: yh0903 Date: Sun, 4 Oct 2026 20:34:05 -0700 Subject: [PATCH 1/2] AutoEP: opt-in skip of the recomputed DeepEP combine With reentrant activation checkpointing, backward recomputes each decoder layer only to rebuild its autograd graph and never reads the recomputed outputs. In a decoder layer that adds the MoE output to the residual, the recomputed MoE output is therefore unread. expert_parallel.skip_recompute_combine lets the DeepEP route record the post-expert row weighting and the combine in that recompute without running them; their backward (a cached dispatch on the same handle, and the row-weighting gradients) is unchanged. Guards, since the skip relies on nothing reading the skipped output: - each recompute checks that the layer's decoder layer uses Hugging Face per-layer gradient checkpointing with use_reentrant=True, and raises otherwise; - only presets whose decoder layer adds the MoE output straight to the residual are accepted (deepseek_v2, deepseek_v3, minimax_m3, mixtral, qwen3_5_moe, qwen3_moe); - the skipped combine returns NaN, so a value-dependent reader outside the contract can produce non-finite values or gradients; - requires comm_backend="deepep" with autoep_size > 1. Eager and fused row weighting are both supported. Preserve the upstream non-reentrant replay and exact-size buffer handling. Normal and recorded combines share backward-context setup so replay entries are owned by their consuming graph rather than leaking into a later step. Cover changing routes over successive CPU steps and two-step real-DeepEP parity, and run the CUDA weighting comparison in a fresh test worker. Signed-off-by: yh0903 --- deepspeed/module_inject/auto_ep.py | 3 + deepspeed/module_inject/auto_ep_comm.py | 43 ++- deepspeed/module_inject/auto_ep_config.py | 15 + deepspeed/module_inject/auto_ep_layer.py | 87 +++++- .../module_inject/auto_ep_presets/base.py | 1 + .../ops/triton_ops/autoep_fused_token_ops.py | 15 + docs/_pages/config-json.md | 6 + docs/code-docs/source/autoep.rst | 58 ++++ tests/unit/module_inject/test_auto_ep_comm.py | 267 ++++++++++++++++++ .../unit/v1/moe/test_autoep_deepep_parity.py | 120 ++++++-- tests/unit/v1/moe/test_autoep_unit.py | 48 ++++ 11 files changed, 632 insertions(+), 31 deletions(-) diff --git a/deepspeed/module_inject/auto_ep.py b/deepspeed/module_inject/auto_ep.py index b119a218620a..6e9e334060d2 100644 --- a/deepspeed/module_inject/auto_ep.py +++ b/deepspeed/module_inject/auto_ep.py @@ -656,6 +656,9 @@ def _replace_moe_layer_without_retarget( deepep_scope=self.deepep_scope, ) + if self.config.skip_recompute_combine: + replacement.attach_decoder_layer(parent) + # Collected before the source module leaves the tree, and only when a caller-supplied # optimizer needs it: the values are the discarded pre-shard expert weights. sources = (collect_replacement_sources(source_module, replacement, spec, ep_size, ep_rank) diff --git a/deepspeed/module_inject/auto_ep_comm.py b/deepspeed/module_inject/auto_ep_comm.py index 10d643ff462a..0df8ce5761ff 100644 --- a/deepspeed/module_inject/auto_ep_comm.py +++ b/deepspeed/module_inject/auto_ep_comm.py @@ -491,21 +491,24 @@ def backward(ctx, grad_received, grad_recv_weights): return None, _conform_rows(grad_tokens, ctx.tokens_shape), None, conformed_weights, None +def _save_combine_context(ctx, exchange: DeepEPExchange, rows: torch.Tensor, handle) -> None: + pending = getattr(exchange, "last_pending", None) + if pending is not None and pending.handle is handle: + # Keeps the forward's replay entry alive exactly as long as the graph that needs its layout. + ctx.pending = pending + exchange.last_pending = None + ctx.exchange = exchange + ctx.handle = handle + # The backward dispatch hands back a whole buffer, while autograd requires the gradient to match its input. + ctx.rows_shape = rows.shape + + class _DeepEPCombine(torch.autograd.Function): """Combine whose backward is the matching dispatch, on the same handle.""" @staticmethod def forward(ctx, exchange: DeepEPExchange, rows: torch.Tensor, handle): - pending = getattr(exchange, "last_pending", None) - if pending is not None and pending.handle is handle: - # Keeps the forward's replay entry alive exactly as long as the graph that needs its layout. - ctx.pending = pending - exchange.last_pending = None - ctx.exchange = exchange - ctx.handle = handle - # The backward dispatch hands back a whole buffer, while autograd - # requires the gradient to match the input it is the gradient of. - ctx.rows_shape = rows.shape + _save_combine_context(ctx, exchange, rows, handle) return exchange.combine(rows, handle) @staticmethod @@ -514,6 +517,21 @@ def backward(ctx, grad_combined): return None, _conform_rows(grad_rows, ctx.rows_shape), None +class _RecordedDeepEPCombine(_DeepEPCombine): + """A combine whose result nobody reads: records the same backward and skips the transfer. + + For ``skip_recompute_combine``. The output is NaN, so that a reader the layer's contract rules out fails + loudly instead of training on garbage. + """ + + @staticmethod + def forward(ctx, exchange: DeepEPExchange, rows: torch.Tensor, handle): + _save_combine_context(ctx, exchange, rows, handle) + # The handle keeps the [tokens, top_k] routing it was dispatched with. + num_tokens = handle.topk_idx.shape[0] + return rows.new_full((num_tokens, rows.shape[1]), float("nan")) + + def deepep_dispatch(exchange: DeepEPExchange, tokens: torch.Tensor, topk_idx: torch.Tensor, @@ -536,3 +554,8 @@ def deepep_dispatch(exchange: DeepEPExchange, def deepep_combine(exchange: DeepEPExchange, rows: torch.Tensor, handle) -> torch.Tensor: return _DeepEPCombine.apply(exchange, rows, handle) + + +def deepep_record_combine(exchange: DeepEPExchange, rows: torch.Tensor, handle) -> torch.Tensor: + """Record :func:`deepep_combine`'s backward without running the combine; the result is all NaN.""" + return _RecordedDeepEPCombine.apply(exchange, rows, handle) diff --git a/deepspeed/module_inject/auto_ep_config.py b/deepspeed/module_inject/auto_ep_config.py index 007b9b9595ae..fac760a72dfd 100644 --- a/deepspeed/module_inject/auto_ep_config.py +++ b/deepspeed/module_inject/auto_ep_config.py @@ -6,6 +6,8 @@ from __future__ import annotations +import torch + from deepspeed.module_inject.auto_ep_presets.base import ( _UNSET, _raise_unsupported_load_balance_coeff, @@ -66,6 +68,7 @@ def parse_autoep_config(param_dict: dict) -> AutoEPConfig: config.comm_num_sm = param_dict.get("comm_num_sm", 12) config.comm_qp_margin = param_dict.get("comm_qp_margin", 4) config.comm_max_tokens_per_rank = param_dict.get("comm_max_tokens_per_rank", 0) + config.skip_recompute_combine = param_dict.get("skip_recompute_combine", False) config.num_expert_groups = param_dict.get("num_expert_groups", None) config.num_limited_groups = param_dict.get("num_limited_groups", None) config.score_func = param_dict.get("score_func", "auto") @@ -234,6 +237,18 @@ def validate_autoep_config( "Set it to the largest number of tokens one rank can route, normally " "train_micro_batch_size_per_gpu * maximum padded sequence length.") + if not isinstance(config.skip_recompute_combine, bool): + raise ValueError(f"skip_recompute_combine must be a boolean, got {config.skip_recompute_combine!r}") + if config.skip_recompute_combine: + if config.comm_backend != "deepep" or config.autoep_size == 1: + raise ValueError('skip_recompute_combine skips the DeepEP combine, so it requires comm_backend="deepep" ' + f'and autoep_size > 1, but comm_backend="{config.comm_backend}" and ' + f"autoep_size={config.autoep_size} were set.") + # The recompute is recognized as a grad-enabled forward that runs inside a backward pass. + if not hasattr(torch._C, "_current_graph_task_id"): + raise ValueError("skip_recompute_combine needs torch._C._current_graph_task_id, which this PyTorch " + "build lacks. Upgrade PyTorch or leave skip_recompute_combine unset.") + # Validate score_func valid_score_func = ("auto", "softmax", "sigmoid") if config.score_func not in valid_score_func: diff --git a/deepspeed/module_inject/auto_ep_layer.py b/deepspeed/module_inject/auto_ep_layer.py index 3c64b6370606..0f3dac923006 100644 --- a/deepspeed/module_inject/auto_ep_layer.py +++ b/deepspeed/module_inject/auto_ep_layer.py @@ -14,11 +14,13 @@ from __future__ import annotations -from functools import lru_cache +import weakref +from functools import lru_cache, partial from typing import Literal, NamedTuple import torch import torch.nn as nn +from torch.utils.checkpoint import checkpoint as torch_checkpoint import deepspeed.comm as dist from deepspeed.accelerator import get_accelerator from deepspeed.checkpoint.autoep_affine import (autoep_experts_for_rank, autoep_placement_to_affine_map, @@ -29,9 +31,9 @@ from deepspeed.module_inject.auto_ep_folding import mark_autoep_folding_router_parameter from deepspeed.ops.triton_ops import autoep_fused_token_ops as fused_token_ops from deepspeed.utils import logger -from deepspeed.module_inject.auto_ep_comm import (COMM_BACKEND, DEEPEP_BACKEND, DeepEPCheckpointReplay, +from deepspeed.module_inject.auto_ep_comm import (COMM_BACKEND, DEEPEP_BACKEND, DeepEPCheckpointReplay, _in_backward, assert_dtype_supported, deepep_combine, deepep_dispatch, - new_exchange_scope, shared_exchange) + deepep_record_combine, new_exchange_scope, shared_exchange) from deepspeed.moe.ep_router import TokenChoiceTopKRouter from deepspeed.moe.ep_count import count_tokens_per_expert from deepspeed.moe.ep_experts import GroupedExperts @@ -177,6 +179,42 @@ def apply_deepep_row_weights( return (rows.float() * weights).to(rows.dtype) +class _RecordedEagerRowWeighting(torch.autograd.Function): + """The backward of the eager row weighting, recorded without computing its product.""" + + @staticmethod + def forward(ctx, rows, weights): + ctx.save_for_backward(rows, weights) + return torch.empty_like(rows) + + @staticmethod + def backward(ctx, grad_output): + rows, weights = ctx.saved_tensors + # The steps autograd takes through (rows.float() * weights).to(rows.dtype), so the gradients match it. + grad = grad_output.float() + grad_rows = (grad * weights).to(rows.dtype) + grad_weights = (grad * rows.float()).sum_to_size(weights.shape) + return grad_rows, grad_weights + + +def record_deepep_row_weights( + rows: torch.Tensor, + weights: torch.Tensor, + row_weighting_impl: Literal["eager", "fused"], +) -> torch.Tensor: + """apply_deepep_row_weights for a result nobody reads: the same backward, an uninitialized result.""" + if row_weighting_impl == "fused": + return fused_token_ops.recorded_fused_row_weighting(rows, weights) + return _RecordedEagerRowWeighting.apply(rows, weights) + + +# skip_recompute_combine is limited to presets whose Hugging Face decoder layer adds the MoE output to the residual +# and returns the sum, checked against their modeling code. Inside that decoder layer's checkpoint, nothing reads +# the recomputed MoE output. +SKIP_RECOMPUTE_COMBINE_PRESETS = frozenset( + ("deepseek_v2", "deepseek_v3", "minimax_m3", "mixtral", "qwen3_5_moe", "qwen3_moe")) + + def _split_plan_from_expert_counts( num_tokens_per_expert: torch.Tensor, # [E_global], int32 ep_size: int, @@ -535,6 +573,14 @@ def __init__( self.score_apply = resolve_score_apply_mode(spec, config.score_apply) self.combine_impl = resolve_combine_impl(config.combine_impl) self.row_weighting_impl = resolve_row_weighting_impl(config.row_weighting_impl) + self.skip_recompute_combine = config.skip_recompute_combine + if self.skip_recompute_combine and spec.model_family not in SKIP_RECOMPUTE_COMBINE_PRESETS: + raise ValueError(f"skip_recompute_combine is not supported for preset '{spec.model_family}'. It relies " + "on the decoder layer only adding the MoE output to the residual, which has been " + f"checked for {sorted(SKIP_RECOMPUTE_COMBINE_PRESETS)}. Leave it unset for this model.") + # The decoder layer holding this layer, set by attach_decoder_layer; held weakly, as the decoder layer + # owns this module. + self._decoder_layer = None self._fused_combine_checked = False self._fused_row_weighting_checked = False route_norm = spec.route_norm if config.route_norm is None else config.route_norm @@ -802,6 +848,28 @@ def set_deepspeed_parallelism( ) self.ep_group = groups._get_expert_parallel_group(self.ep_group_name) + def attach_decoder_layer(self, decoder_layer: nn.Module) -> None: + """Record the decoder layer whose checkpoint skip_recompute_combine requires.""" + self._decoder_layer = weakref.ref(decoder_layer) + + def _assert_recompute_skip_contract(self) -> None: + """Fail unless this recompute is the reentrant checkpoint of this layer's own decoder layer. + + Only then is the recomputed output unread: the checkpoint only backpropagates through it, and the decoder + layer only adds it to the residual. A checkpoint spanning several layers would feed it to the next one. + """ + decoder_layer = None if self._decoder_layer is None else self._decoder_layer() + checkpoint_func = getattr(decoder_layer, "_gradient_checkpointing_func", None) + reentrant = (isinstance(checkpoint_func, partial) and checkpoint_func.func is torch_checkpoint + and checkpoint_func.keywords.get("use_reentrant") is True) + if not getattr(decoder_layer, "gradient_checkpointing", False) or not reentrant: + raise RuntimeError( + "skip_recompute_combine found a recompute that is not the reentrant checkpoint of this MoE " + "layer's own decoder layer. It requires Hugging Face per-layer gradient checkpointing with " + "use_reentrant=True, e.g. model.gradient_checkpointing_enable(" + "gradient_checkpointing_kwargs={'use_reentrant': True}), so that nothing reads the skipped output. " + "Leave skip_recompute_combine unset for other checkpointing.") + def _deepep_route(self, tokens: torch.Tensor, ro: "RouterOutput") -> torch.Tensor: """Dispatch, run the experts, and combine through DeepEP. @@ -840,6 +908,13 @@ def _deepep_route(self, tokens: torch.Tensor, ro: "RouterOutput") -> torch.Tenso "job will produce, normally train_micro_batch_size_per_gpu * maximum padded sequence length, or " 'set comm_backend="comm".') + # In the decoder layer's reentrant recompute nothing reads this layer's output; the checkpoint only + # backpropagates through it. The post-expert row weighting and the combine then record their backward + # without running. + record_only = self.skip_recompute_combine and torch.is_grad_enabled() and _in_backward() + if record_only: + self._assert_recompute_skip_contract() + received, recv_weights, exchange = deepep_dispatch(self._deepep_exchange, tokens, ro.selected_experts, @@ -880,9 +955,13 @@ def _deepep_route(self, tokens: torch.Tensor, ro: "RouterOutput") -> torch.Tenso expert_output = self.experts(received, counts) - if weights is not None: + if weights is not None and record_only: + expert_output = record_deepep_row_weights(expert_output, weights, self.row_weighting_impl) + elif weights is not None: expert_output = apply_deepep_row_weights(expert_output, weights, self.row_weighting_impl) + if record_only: + return deepep_record_combine(exchange, expert_output, handle) return deepep_combine(exchange, expert_output, handle) def _finalize_output(self, output: torch.Tensor, x: torch.Tensor, hidden_states: torch.Tensor, diff --git a/deepspeed/module_inject/auto_ep_presets/base.py b/deepspeed/module_inject/auto_ep_presets/base.py index d5904ad38bf9..840c5f2284ed 100644 --- a/deepspeed/module_inject/auto_ep_presets/base.py +++ b/deepspeed/module_inject/auto_ep_presets/base.py @@ -128,6 +128,7 @@ class AutoEPConfig: comm_num_sm: int = 12 comm_qp_margin: int = 4 comm_max_tokens_per_rank: int = 0 + skip_recompute_combine: bool = False num_expert_groups: int | None = None num_limited_groups: int | None = None score_func: Literal["auto", "softmax", "sigmoid"] = "auto" diff --git a/deepspeed/ops/triton_ops/autoep_fused_token_ops.py b/deepspeed/ops/triton_ops/autoep_fused_token_ops.py index 2493f4c9bec0..01711214bf0a 100644 --- a/deepspeed/ops/triton_ops/autoep_fused_token_ops.py +++ b/deepspeed/ops/triton_ops/autoep_fused_token_ops.py @@ -447,12 +447,27 @@ def backward(ctx, grad_output): return grad_rows, grad_weights +class _RecordedFusedRowWeighting(_FusedRowWeighting): + """The fused row weighting's backward, recorded without running its forward kernel.""" + + @staticmethod + def forward(ctx, rows, weights): + ctx.save_for_backward(rows, weights) + return torch.empty_like(rows) + + def fused_row_weighting(rows: torch.Tensor, weights: torch.Tensor) -> torch.Tensor: """Apply ``weights`` to ``rows`` as ``(rows.float() * weights).to(rows.dtype)``.""" assert_row_weighting_supported(rows, weights) return _FusedRowWeighting.apply(rows, weights) +def recorded_fused_row_weighting(rows: torch.Tensor, weights: torch.Tensor) -> torch.Tensor: + """:func:`fused_row_weighting` for a result nobody reads: the same backward, an uninitialized result.""" + assert_row_weighting_supported(rows, weights) + return _RecordedFusedRowWeighting.apply(rows, weights) + + def fused_weighted_restore( combined_rows: torch.Tensor, top_scores: torch.Tensor, diff --git a/docs/_pages/config-json.md b/docs/_pages/config-json.md index a658724ee577..80719e619fbc 100644 --- a/docs/_pages/config-json.md +++ b/docs/_pages/config-json.md @@ -1009,6 +1009,12 @@ smoke coverage used for this AutoEP surface produced the following version gates | -------------------------------------------------------------------------------------------------------------- | -------- | | How the grouped experts compute their gate and up projections. `"separate"` runs two grouped GEMMs. `"fused"` is experimental and runs one `torch._grouped_mm` over the gate and up weights concatenated on each call, followed by an activation that reads the two halves of its output in place; for `swiglu` this is a Triton kernel with first-order gradients only (`create_graph=True` raises). Parameters, checkpoints and optimizer state keep the separate `w1`/`w3` layout. The forward expression and parameter-gradient semantics are unchanged, but exact numerical equality is not guaranteed across GEMM shapes/backends; the input gradient accumulates both projections in one FP32 GEMM instead of adding two rounded results. Requires `use_grouped_mm=true` and the `torch._grouped_mm` path (set `disable_triton_grouped_mm=true` on devices that prefer the Triton grouped GEMM); unsupported configurations fail rather than falling back. | `"separate"` | +***skip_recompute_combine***: [boolean] + +| Description | Default | +| -------------------------------------------------------------------------------------------------------------- | -------- | +| Experimental. In the reentrant recompute of a decoder layer, record the DeepEP route's post-expert row weighting and combine without running them: nothing reads that recomputed output, and their backward is unchanged. The skipped output is NaN. Requires `comm_backend="deepep"` with `autoep_size > 1`, a preset whose decoder layer adds the MoE output to the residual (`deepseek_v2`, `deepseek_v3`, `minimax_m3`, `mixtral`, `qwen3_5_moe`, `qwen3_moe`), and Hugging Face per-layer gradient checkpointing with `use_reentrant=True`; anything else is rejected rather than ignored. | `false` | + ***route_norm***: [boolean] | Description | Default | diff --git a/docs/code-docs/source/autoep.rst b/docs/code-docs/source/autoep.rst index a20891eb904c..55f478da9c30 100644 --- a/docs/code-docs/source/autoep.rst +++ b/docs/code-docs/source/autoep.rst @@ -374,6 +374,64 @@ The model-level gradient comparison samples gradients before the wrapper computes the norm and clips them in ``engine.step()``. GPU validation applies both independent corrections; neither is part of this opt-in change. +**Skipping the recomputed combine (experimental):** + +With reentrant activation checkpointing, backward recomputes each decoder layer +only to rebuild its autograd graph, and never reads the recomputed outputs. In a +decoder layer that adds the MoE output to the residual, nothing reads the +recomputed MoE output either. ``skip_recompute_combine`` lets the DeepEP route +record the post-expert row weighting and the combine in that recompute without +running them. Their backward is unchanged: a cached dispatch on the same handle, +and the row-weighting gradients. The dispatch and the experts still run, because +backward needs their activations. + +.. code-block:: json + + { + "expert_parallel": { + "enabled": true, + "autoep_size": 8, + "comm_backend": "deepep", + "comm_max_tokens_per_rank": 16384, + "skip_recompute_combine": true + } + } + +On Qwen3-30B-A3B with 8 H100s (expert parallel size 8, micro-batch 4, 16 +accumulation steps, sequence length 4096, DeepEP with 28 SMs), an equivalent +benchmark prototype cut the step from 20.57 s to 19.94 s (-3.1%). Gradients +matched the normal recompute within the measured numerical bounds. Peak +allocated memory was unchanged; peak reserved memory was 0.25 GB lower. +These are same-allocation prototype measurements, not a retiming of every +supported model or of this branch after upstream integration. + +Recorded and normal combines share the backward context, including ownership +of the dispatch replay entry. That entry is released with its autograd graph, +so a later reentrant step cannot reuse a previous step's routing. + +The skip relies on nothing reading the skipped output, so it is guarded: + +- The recompute is recognized as a grad-enabled forward that runs inside a + backward pass. Each time, AutoEP checks that the MoE layer's decoder layer has + Hugging Face gradient checkpointing enabled with ``use_reentrant=True``, for + example via ``model.gradient_checkpointing_enable( + gradient_checkpointing_kwargs={"use_reentrant": True})``, and raises + otherwise. Transformers 5 defaults to non-reentrant checkpointing, so the + argument is required there. A checkpoint that spans several layers would + feed the skipped output to the next layer. Non-reentrant checkpointing and + DeepSpeed's own checkpointing API are also rejected. +- Only presets whose decoder layer adds the MoE output straight to the residual + are accepted: ``deepseek_v2``, ``deepseek_v3``, ``minimax_m3``, ``mixtral``, + ``qwen3_5_moe`` and ``qwen3_moe``. Other presets and custom patterns are + rejected at conversion. +- The skipped combine returns NaN rather than uninitialized memory. If + something outside the contract reads it in a value-dependent operation, + it can produce non-finite outputs or gradients. The sentinel is not a + general runtime proof that no consumer reads the value. +- It requires ``comm_backend="deepep"`` and ``autoep_size > 1``. Both + ``row_weighting_impl`` values are supported; the recorded eager weighting + takes autograd's own steps through the eager expression. + Requirements and limits: - The ``deep_ep`` package must be installed. It is imported only when this diff --git a/tests/unit/module_inject/test_auto_ep_comm.py b/tests/unit/module_inject/test_auto_ep_comm.py index b88dd678050f..e3d0621d8fb2 100644 --- a/tests/unit/module_inject/test_auto_ep_comm.py +++ b/tests/unit/module_inject/test_auto_ep_comm.py @@ -6,11 +6,14 @@ import gc import inspect import itertools +import os import textwrap import sys import unittest +import pytest import torch +from torch.utils.checkpoint import checkpoint from types import SimpleNamespace from unittest import mock @@ -18,8 +21,10 @@ _DeepEPCombine, _DeepEPDispatch, _import_deep_ep, _qps_for_sms, assert_dtype_supported, destroy_exchanges, new_exchange_scope, shared_exchange) +from deepspeed.accelerator import get_accelerator from deepspeed.module_inject import auto_ep_comm, auto_ep_layer from deepspeed.module_inject.auto_ep_config import parse_autoep_config, validate_autoep_config +from unit.common import DistributedTest class TestAutoEPCommBackendSelection(unittest.TestCase): @@ -603,6 +608,7 @@ def layer(ep_size=2, comm_backend=DEEPEP_BACKEND, *, return_router_logits=False) # Keep the fixture valid when composed with opt-in async split planning. layer.async_split_plan = False layer._async_split_plan_pending = None + layer.skip_recompute_combine = False layer.top_k = 2 layer.num_experts = 2 layer.num_local_experts = 1 @@ -1137,5 +1143,266 @@ def test_dispatch_forward_returns_weights_so_they_stay_differentiable(self): self.assertIn("return received, recv_weights", source) +class TestSkipRecomputeCombine(unittest.TestCase): + """skip_recompute_combine: the decoder layer's reentrant recompute records the combine without running it.""" + + TOKENS, TOP_K, EXPERTS, HIDDEN, INTER = 24, 2, 4, 16, 8 + + class Buffer: + """DeepEP's expanded dispatch/combine contract on one rank, logging which calls ran.""" + + def __init__(self, test, log): + self.test = test + self.log = log + + def dispatch(self, tokens, *, topk_idx=None, topk_weights=None, handle=None, do_expand=False, **kwargs): + test = self.test + if handle is None: + self.log.append("dispatch") + slots = [(t, k) for e in range(test.EXPERTS) for t, k in (topk_idx == e).nonzero().tolist()] + counts = torch.bincount(topk_idx.flatten(), minlength=test.EXPERTS) + handle = SimpleNamespace(do_expand=do_expand, + topk_idx=topk_idx.clone(), + token_of_row=torch.tensor([t for t, _ in slots], dtype=torch.long), + slot_of_row=torch.tensor([k for _, k in slots], dtype=torch.long), + num_expanded_tokens=len(slots), + psum_num_recv_tokens_per_expert=torch.cumsum(counts, 0)) + else: + self.log.append("cached_dispatch") + weights = None if topk_weights is None else topk_weights[handle.token_of_row, handle.slot_of_row] + # A real buffer hands back more rows than arrived. + rows = torch.cat([tokens[handle.token_of_row], tokens.new_full((3, tokens.shape[1]), float("nan"))]) + return rows, None, weights, handle, None + + def combine(self, rows, *, handle, topk_weights=None, **kwargs): + self.log.append("combine") + rows = rows[:handle.num_expanded_tokens] + num_tokens = handle.topk_idx.shape[0] + combined = rows.new_zeros(num_tokens, rows.shape[1]).index_add(0, handle.token_of_row, rows) + combined_weights = None + if topk_weights is not None: + combined_weights = topk_weights.new_zeros(num_tokens, self.test.TOP_K) + combined_weights[handle.token_of_row, handle.slot_of_row] = topk_weights[:handle.num_expanded_tokens] + return combined, combined_weights, None + + class DecoderLayer(torch.nn.Module): + """A Hugging Face decoder layer as far as the contract goes: its own checkpoint, and a residual add.""" + + def __init__(self, mlp, gate, routing, checkpoint_func, reads_output=False): + super().__init__() + self.mlp = mlp + self.gate = torch.nn.Parameter(gate.clone()) + self.routing = routing + self.gradient_checkpointing = checkpoint_func is not None + self._gradient_checkpointing_func = checkpoint_func + self.reads_output = reads_output + + def block(self, x): + scores = torch.softmax(x.float() @ self.gate.float(), dim=-1).gather(1, self.routing) + counts = torch.bincount(self.routing.flatten(), minlength=self.gate.shape[1]) + router_output = auto_ep_layer.RouterOutput(top_scores=scores, + selected_experts=self.routing, + num_tokens_per_expert=counts) + moe = self.mlp._deepep_route(x, router_output) + if self.reads_output: + # Outside the contract: the product saves the MoE output for its backward. + return x + moe * moe + return x + moe + + def forward(self, x): + if self.gradient_checkpointing: + return self._gradient_checkpointing_func(self.block, x) + return self.block(x) + + def setUp(self): + torch.manual_seed(0) + self.routing = torch.randint(0, self.EXPERTS, (self.TOKENS, self.TOP_K)) + self.inputs = torch.randn(self.TOKENS, self.HIDDEN).bfloat16() + self.gate = torch.randn(self.HIDDEN, self.EXPERTS).bfloat16() + self.expert_weights = [ + torch.randn(self.EXPERTS, self.INTER, self.HIDDEN) * 0.3, + torch.randn(self.EXPERTS, self.HIDDEN, self.INTER) * 0.3, + torch.randn(self.EXPERTS, self.INTER, self.HIDDEN) * 0.3, + ] + self.target = torch.randn(self.TOKENS, self.HIDDEN) + + def make_layer(self, log, skip, score_apply): + from deepspeed.moe.ep_experts import GroupedExperts + + exchange = auto_ep_comm.DeepEPExchange.__new__(auto_ep_comm.DeepEPExchange) + exchange.buffer = self.Buffer(self, log) + exchange.deep_ep = SimpleNamespace(topk_idx_t=torch.int64) + exchange.num_experts, exchange.num_sms, exchange.last_handle = self.EXPERTS, 12, None + exchange.num_max_tokens_per_rank = self.TOKENS + # A form without a Triton kernel, so the CPU route runs wherever Triton is installed. + experts = GroupedExperts(dim=self.HIDDEN, + hidden_dim=self.INTER, + num_experts=self.EXPERTS, + use_grouped_mm=True, + disable_triton_grouped_mm=True, + activation="geglu_tanh").bfloat16() + with torch.no_grad(): + for name, value in zip(("w1", "w2", "w3"), self.expert_weights): + getattr(experts, name).copy_(value) + # Only the attributes the DeepEP route reads, without building a router or a buffer. + layer = auto_ep_layer.AutoEPMoELayer.__new__(auto_ep_layer.AutoEPMoELayer) + torch.nn.Module.__init__(layer) + layer.experts = experts + layer._deepep_exchange = exchange + layer._deepep_replay = auto_ep_comm.DeepEPCheckpointReplay() + layer.num_local_experts = self.EXPERTS + layer.score_apply = score_apply + layer.row_weighting_impl = "eager" + layer.skip_recompute_combine = skip + layer._decoder_layer = None + return layer + + def run_block(self, + skip, + checkpoint_func, + score_apply="post", + reads_output=False, + attach=True, + routing=None, + steps=1): + log = [] + layer = self.make_layer(log, skip, score_apply) + decoder = self.DecoderLayer(layer, self.gate, self.routing if routing is None else routing, checkpoint_func, + reads_output) + if attach: + layer.attach_decoder_layer(decoder) + initial_routing = decoder.routing + step_results = [] + for step in range(steps): + decoder.zero_grad(set_to_none=True) + decoder.routing = (initial_routing + step) % self.EXPERTS + x = (self.inputs + step).requires_grad_(True) + output = decoder(x) + (output.float() * self.target).sum().backward() + result = {"output": output.detach(), "x": x.grad, "gate": decoder.gate.grad} + result.update({name: getattr(layer.experts, name).grad for name in ("w1", "w2", "w3")}) + step_results.append(result) + result = {} + for name in step_results[0]: + values = [step[name] for step in step_results] + result[name] = values[0] if steps == 1 else torch.stack(values) + return result, log + + @staticmethod + def reentrant(): + return functools.partial(checkpoint, use_reentrant=True) + + def test_recorded_recompute_matches_the_normal_recompute_bitwise(self): + routings = {"spread": self.routing, "empty_expert": self.routing % (self.EXPERTS - 1)} + for (routing_name, routing), score_apply in itertools.product(routings.items(), ("post", "pre")): + with self.subTest(routing=routing_name, score_apply=score_apply): + normal, normal_log = self.run_block(False, self.reentrant(), score_apply, routing=routing) + skipped, skipped_log = self.run_block(True, self.reentrant(), score_apply, routing=routing) + for name, expected in normal.items(): + self.assertTrue(torch.equal(skipped[name], expected), name) + # Forward, recompute, then backward's cached dispatch and the dispatch's combine. The recompute + # still dispatches, since backward needs the experts' activations, but does not combine. + self.assertEqual(normal_log, + ["dispatch", "combine", "dispatch", "combine", "cached_dispatch", "combine"]) + self.assertEqual(skipped_log, ["dispatch", "combine", "dispatch", "cached_dispatch", "combine"]) + + def test_nothing_is_skipped_without_a_recompute(self): + normal, normal_log = self.run_block(False, None) + skipped, skipped_log = self.run_block(True, None) + for name, expected in normal.items(): + self.assertTrue(torch.equal(skipped[name], expected), name) + self.assertEqual(skipped_log, normal_log) + self.assertEqual(skipped_log, ["dispatch", "combine", "cached_dispatch", "combine"]) + + def test_repeated_steps_do_not_replay_the_previous_steps_dispatch(self): + for score_apply in ("pre", "post"): + normal, normal_log = self.run_block(False, self.reentrant(), score_apply, steps=3) + skipped, skipped_log = self.run_block(True, self.reentrant(), score_apply, steps=3) + for name, expected in normal.items(): + self.assertTrue(torch.equal(skipped[name], expected), name) + self.assertEqual(normal_log, + ["dispatch", "combine", "dispatch", "combine", "cached_dispatch", "combine"] * 3) + self.assertEqual(skipped_log, ["dispatch", "combine", "dispatch", "cached_dispatch", "combine"] * 3) + + def test_the_skipped_combine_returns_nan_so_a_reader_fails_loudly(self): + normal, _ = self.run_block(False, self.reentrant(), reads_output=True) + skipped, _ = self.run_block(True, self.reentrant(), reads_output=True) + self.assertTrue(torch.isfinite(normal["x"]).all()) + self.assertTrue(torch.isnan(skipped["x"]).any()) + + log = [] + layer = self.make_layer(log, True, "post") + handle = SimpleNamespace(topk_idx=self.routing) + recorded = auto_ep_comm.deepep_record_combine(layer._deepep_exchange, torch.ones(5, self.HIDDEN), handle) + self.assertEqual(recorded.shape, (self.TOKENS, self.HIDDEN)) + self.assertTrue(torch.isnan(recorded).all()) + self.assertEqual(log, []) + + def test_any_other_recompute_is_rejected(self): + non_reentrant = functools.partial(checkpoint, use_reentrant=False) + another_function = lambda function, *args: checkpoint(function, *args, use_reentrant=True) + cases = { + "not attached to a decoder layer": dict(checkpoint_func=self.reentrant(), attach=False), + "non-reentrant checkpointing": dict(checkpoint_func=non_reentrant), + "a checkpoint function other than torch's": dict(checkpoint_func=another_function), + } + for name, kwargs in cases.items(): + with self.subTest(case=name), self.assertRaisesRegex(RuntimeError, "skip_recompute_combine"): + self.run_block(True, **kwargs) + + # A checkpoint that spans the decoder layer from outside, with its own checkpointing off. + layer = self.make_layer([], True, "post") + decoder = self.DecoderLayer(layer, self.gate, self.routing, None) + layer.attach_decoder_layer(decoder) + x = self.inputs.clone().requires_grad_(True) + output = checkpoint(decoder, x, use_reentrant=True) + with self.assertRaisesRegex(RuntimeError, "skip_recompute_combine"): + output.float().sum().backward() + + def test_recorded_eager_row_weighting_backward_matches_autograd_bitwise(self): + for dtype in (torch.bfloat16, torch.float32): + with self.subTest(dtype=dtype): + rows = torch.randn(32, self.HIDDEN).to(dtype) + weights = torch.rand(32, 1) + grad_output = torch.randn(32, self.HIDDEN).to(dtype) + gradients = [] + for apply in (auto_ep_layer.apply_deepep_row_weights, auto_ep_layer.record_deepep_row_weights): + leaf_rows = rows.clone().requires_grad_(True) + leaf_weights = weights.clone().requires_grad_(True) + output = apply(leaf_rows, leaf_weights, "eager") + self.assertEqual((output.shape, output.dtype), (rows.shape, dtype)) + output.backward(grad_output) + gradients.append((leaf_rows.grad, leaf_weights.grad)) + (rows_eager, weights_eager), (rows_recorded, weights_recorded) = gradients + self.assertTrue(torch.equal(rows_recorded, rows_eager)) + self.assertTrue(torch.equal(weights_recorded, weights_eager)) + + +@pytest.mark.skipif(os.environ.get("DS_ACCELERATOR") == "cpu", reason="fused row weighting needs CUDA and Triton") +class TestRecordedFusedRowWeightingCUDA(DistributedTest): + world_size = 1 + init_distributed = False + + def test_recorded_fused_row_weighting_backward_matches_the_fused_one_bitwise(self): + from deepspeed.ops.triton_ops import autoep_fused_token_ops as fused_token_ops + + if not (get_accelerator().device_name() == "cuda" and fused_token_ops.is_available()): + pytest.skip("the fused row weighting needs CUDA and Triton") + device = get_accelerator().current_device_name() + generator = torch.Generator(device=device).manual_seed(8745) + rows = torch.randn(64, 256, device=device, generator=generator).bfloat16() + weights = torch.rand(64, 1, device=device, generator=generator) + grad_output = torch.randn(rows.shape, device=device, dtype=rows.dtype, generator=generator) + gradients = [] + for apply in (auto_ep_layer.apply_deepep_row_weights, auto_ep_layer.record_deepep_row_weights): + leaf_rows = rows.clone().requires_grad_(True) + leaf_weights = weights.clone().requires_grad_(True) + apply(leaf_rows, leaf_weights, "fused").backward(grad_output) + gradients.append((leaf_rows.grad, leaf_weights.grad)) + (rows_fused, weights_fused), (rows_recorded, weights_recorded) = gradients + assert torch.equal(rows_recorded, rows_fused) + assert torch.equal(weights_recorded, weights_fused) + + if __name__ == "__main__": unittest.main() diff --git a/tests/unit/v1/moe/test_autoep_deepep_parity.py b/tests/unit/v1/moe/test_autoep_deepep_parity.py index 6a784383d1da..0a537bc4b70d 100644 --- a/tests/unit/v1/moe/test_autoep_deepep_parity.py +++ b/tests/unit/v1/moe/test_autoep_deepep_parity.py @@ -156,6 +156,30 @@ def counted(exchange, rows, handle): yield counts +def _checkpoint_decoder_layers(engine): + """Hugging Face per-layer gradient checkpointing: each decoder layer checkpoints its own block, reentrantly.""" + model = engine.module + for layer in model.model.layers: + layer.gradient_checkpointing = True + layer._gradient_checkpointing_func = functools.partial(checkpoint, use_reentrant=True) + + def block(layer, x): + residual = x + x = layer.input_layernorm(x) + x, _ = layer.self_attn(x, x, x) + x = residual + x + residual = x + x = layer.post_attention_layernorm(x) + return residual + layer.mlp(x) + + def forward(x): + for layer in model.model.layers: + x = layer._gradient_checkpointing_func(block, layer, x) + return model.lm_head(x) + + model.forward = forward + + def _count_autoep_layer_forwards(engine): forward_counts = {} for name, module in engine.module.named_modules(): @@ -199,7 +223,13 @@ def _snapshot_fp32_parameters(engine): return snapshot -def _build_test_engine(backend, ep_size, seed, *, row_weighting_impl="auto", score_apply=None): +def _build_test_engine(backend, + ep_size, + seed, + *, + row_weighting_impl="auto", + score_apply=None, + skip_recompute_combine=False): seed_everything(seed) config = make_autoep_config(ep_size=ep_size) @@ -216,6 +246,8 @@ def _build_test_engine(backend, ep_size, seed, *, row_weighting_impl="auto", sco config["expert_parallel"]["row_weighting_impl"] = row_weighting_impl if score_apply is not None: config["expert_parallel"]["score_apply"] = score_apply + if skip_recompute_combine: + config["expert_parallel"]["skip_recompute_combine"] = True if backend == "deepep": # Sized explicitly rather than from the first batch, so both backends # see identical shapes whatever that batch turns out to be. @@ -247,9 +279,17 @@ def _run_one_step(backend, skewed_routing=False, row_weighting_impl="auto", score_apply=None, + decoder_layer_checkpointing=False, + skip_recompute_combine=False, + steps=1, seq_len=SEQ_LEN): """Build a model on ``backend``, run one step, return its output and grads.""" - engine = _build_test_engine(backend, ep_size, seed, row_weighting_impl=row_weighting_impl, score_apply=score_apply) + engine = _build_test_engine(backend, + ep_size, + seed, + row_weighting_impl=row_weighting_impl, + score_apply=score_apply, + skip_recompute_combine=skip_recompute_combine) if backend == "deepep" and not cleanup: _install_legacy_deepep_prep(engine) if skewed_routing: @@ -257,6 +297,8 @@ def _run_one_step(backend, forward_counts = _count_autoep_layer_forwards(engine) if activation_checkpointing: _checkpoint_autoep_layers(engine, use_reentrant=reentrant_checkpointing, nested=nested_checkpointing) + if decoder_layer_checkpointing: + _checkpoint_decoder_layers(engine) # Reseeded so the input is identical on every rank and across backends: the # comparison is of the transport, so nothing else may differ. @@ -280,21 +322,26 @@ def capture_route(_module, _inputs, output, *, _name=name): hooks.append(module.router.register_forward_hook(capture_route)) - output = engine(hidden) - loss = output.float().pow(2).mean() - engine.backward(loss) - - gradients = { - name: parameter.grad.detach().float().clone() - for name, parameter in engine.module.named_parameters() if parameter.grad is not None - } - score_gradient_parts = {} - for name, scores in score_tensors: - if scores.grad is not None: - score_gradient_parts.setdefault(name, []).append(scores.grad.detach().float()) - score_gradients = {name: torch.stack(parts).sum(dim=0) for name, parts in score_gradient_parts.items()} - input_gradient = hidden.grad.detach().float().clone() - engine.step() + for step in range(steps): + if step: + hidden = torch.randn(1, seq_len, HIDDEN_SIZE, device=engine.device, + dtype=engine_input_dtype(engine)).requires_grad_(True) + score_tensors.clear() + output = engine(hidden) + loss = output.float().pow(2).mean() + engine.backward(loss) + + gradients = { + name: parameter.grad.detach().float().clone() + for name, parameter in engine.module.named_parameters() if parameter.grad is not None + } + score_gradient_parts = {} + for name, scores in score_tensors: + if scores.grad is not None: + score_gradient_parts.setdefault(name, []).append(scores.grad.detach().float()) + score_gradients = {name: torch.stack(parts).sum(dim=0) for name, parts in score_gradient_parts.items()} + input_gradient = hidden.grad.detach().float().clone() + engine.step() parameters_after = _snapshot_fp32_parameters(engine) parameter_deltas = {name: parameters_after[name] - parameters_before[name] for name in parameters_before} for hook in hooks: @@ -697,6 +744,45 @@ def test_retained_checkpoint_graph_interleaved_with_new_forward_is_rejected(self destroy_exchanges(engine.module) dist.barrier() + @pytest.mark.parametrize("skewed_routing", [False, True]) + @pytest.mark.parametrize("row_weighting_impl", ["eager", "fused"]) + def test_skipping_the_recomputed_combine_matches_the_normal_recompute(self, row_weighting_impl, skewed_routing): + if row_weighting_impl == "fused": + _skip_unless_fused_row_weighting_enabled("fused DeepEP row weighting needs H100s and a DeepEP build") + else: + skip_unless_h100_tests_enabled("skip_recompute_combine parity needs H100s and a DeepEP build") + seed = 2468 + steps = 2 + results = {} + for skip in (False, True): + with _count_deepep_combines() as counts: + results[skip] = _run_one_step("deepep", + self.world_size, + seed, + decoder_layer_checkpointing=True, + skip_recompute_combine=skip, + row_weighting_impl=row_weighting_impl, + skewed_routing=skewed_routing, + steps=steps) + results[skip]["combines"] = counts["combine"] + + normal, skipped = results[False], results[True] + layers = len(skipped["forward_counts"]) + assert layers > 0 and all(count == 2 * steps for count in skipped["forward_counts"].values()) + # The recompute no longer combines: one forward combine per layer instead of two. + assert normal["combines"] == 2 * layers * steps + assert skipped["combines"] == layers * steps + _assert_cleanup_results_close(skipped, normal, compare_score_gradients=False) + # DeepEP's arrival order can differ between the recomputes, so this is not bitwise; a dropped or + # misrouted gradient would be far outside 2e-2. + _assert_native_fused_gradient_close(skipped["input_gradient"], normal["input_gradient"], name="input") + for name, gradient in normal["gradients"].items(): + if gradient.norm() == 0: + # Skewed routing leaves an expert without tokens on the rank that owns it. + assert skipped["gradients"][name].norm() == 0, f"{name} gradient should be zero" + continue + _assert_native_fused_gradient_close(skipped["gradients"][name], gradient, name=name) + @pytest.mark.parametrize( "activation_checkpointing, skewed_routing", [ diff --git a/tests/unit/v1/moe/test_autoep_unit.py b/tests/unit/v1/moe/test_autoep_unit.py index af58fae49f98..ea0a57d778c1 100644 --- a/tests/unit/v1/moe/test_autoep_unit.py +++ b/tests/unit/v1/moe/test_autoep_unit.py @@ -348,6 +348,33 @@ def test_fused_row_weighting_accepts_the_deepep_path(self): }) validate_autoep_config(config, world_size=2, pp_size=1, tp_size=1, sp_size=1) + def test_skip_recompute_combine_defaults_off_and_requires_the_deepep_route(self): + assert parse_autoep_config({}).skip_recompute_combine is False + deepep = {"comm_backend": "deepep", "comm_max_tokens_per_rank": 4096} + rejected = ( + ({ + "autoep_size": 2, + "skip_recompute_combine": "true" + }, "skip_recompute_combine must be a boolean"), + ({ + "autoep_size": 2, + "skip_recompute_combine": True + }, 'comm_backend="comm"'), + ({ + "autoep_size": 1, + "skip_recompute_combine": True, + **deepep + }, "autoep_size=1"), + ) + for overrides, match in rejected: + config = parse_autoep_config({"enabled": True, **overrides}) + with pytest.raises(ValueError, match=match): + validate_autoep_config(config, world_size=2, pp_size=1, tp_size=1, sp_size=1) + + config = parse_autoep_config({"enabled": True, "autoep_size": 2, "skip_recompute_combine": True, **deepep}) + assert config.skip_recompute_combine is True + validate_autoep_config(config, world_size=2, pp_size=1, tp_size=1, sp_size=1) + def test_fused_combine_rejects_folded_tensor_parallelism(self): config = parse_autoep_config({ "enabled": True, @@ -1393,6 +1420,14 @@ def test_autoep_layer_forward_and_expert_bias_rejection(self): ep_rank=0, config=AutoEPConfig(enabled=True, autoep_size=1, load_balance_coeff=0.02)) + def test_skip_recompute_combine_is_limited_to_checked_presets(self): + source = MockMoEBlock(num_experts=4, ffn_hidden=128, hidden_size=64) + config = _runtime_config(enabled=True, autoep_size=1, skip_recompute_combine=True) + with pytest.raises(ValueError, match="skip_recompute_combine is not supported for preset 'custom_family'"): + AutoEPMoELayer(_make_spec(model_family="custom_family"), source, ep_size=1, ep_rank=0, config=config) + layer = AutoEPMoELayer(_make_spec(), source, ep_size=1, ep_rank=0, config=config) + assert layer.skip_recompute_combine is True + def test_router_cache_does_not_duplicate_model_level_gate_capture(self): source = MockMoEBlock(num_experts=4, ffn_hidden=128, hidden_size=64) layer = AutoEPMoELayer(_make_spec(router_logits_capture_target="router", router_logits_capture_mode="raw"), @@ -1949,6 +1984,19 @@ def test_mixtral_detect_replace_and_mock_forward(self): assert isinstance(model.model.layers[0].mlp, AutoEPMoELayer) assert model(torch.randn(1, 4, 64)).shape == (1, 4, 100) + def test_skip_recompute_combine_attaches_each_layer_to_its_decoder_layer(self): + for skip in (False, True): + model = MockMoETransformer(num_layers=2, moe_every_n=1) + config = _runtime_config(enabled=True, autoep_size=1, preset_model="mixtral", skip_recompute_combine=skip) + auto_ep = AutoEP(model, config) + for spec in auto_ep.ep_parser(): + auto_ep.replace_moe_layer(spec, ep_size=1, ep_rank=0) + for decoder_layer in model.model.layers: + attached = decoder_layer.mlp._decoder_layer + # Held weakly, so the decoder layer is not registered as a child of its own MoE layer. + assert (attached() if skip else attached) is (decoder_layer if skip else None) + assert all(module is not decoder_layer for module in decoder_layer.mlp.modules()) + def test_fused_replacement_preserves_frozen_experts_and_trainable_router(self): model = MockMoETransformer(num_layers=1, num_experts=4, moe_every_n=1).to(dtype=torch.bfloat16) source = model.model.layers[0].mlp From d1776a8c00a7d1e7ebd58680559de7cb2b10168d Mon Sep 17 00:00:00 2001 From: yh0903 Date: Mon, 19 Oct 2026 16:02:32 -0700 Subject: [PATCH 2/2] AutoEP: reject layer-pattern overrides when skipping combine A pattern override can select an unchecked decoder parent while retaining a supported preset name. Reject any non-null moe_layer_pattern before enabling the recompute skip, since the preset whitelist alone cannot establish the output-consumer contract. Cover automatic and explicit preset selection, custom, matching and empty pattern overrides, and unchanged validation with the skip disabled or the pattern unset. Document the restriction at both configuration entry points. Signed-off-by: yh0903 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- deepspeed/module_inject/auto_ep_config.py | 4 ++++ docs/_pages/config-json.md | 2 +- docs/code-docs/source/autoep.rst | 8 ++++++-- tests/unit/v1/moe/test_autoep_unit.py | 21 +++++++++++++++++++++ 4 files changed, 32 insertions(+), 3 deletions(-) diff --git a/deepspeed/module_inject/auto_ep_config.py b/deepspeed/module_inject/auto_ep_config.py index fac760a72dfd..fc12cb381090 100644 --- a/deepspeed/module_inject/auto_ep_config.py +++ b/deepspeed/module_inject/auto_ep_config.py @@ -244,6 +244,10 @@ def validate_autoep_config( raise ValueError('skip_recompute_combine skips the DeepEP combine, so it requires comm_backend="deepep" ' f'and autoep_size > 1, but comm_backend="{config.comm_backend}" and ' f"autoep_size={config.autoep_size} were set.") + if config.moe_layer_pattern is not None: + raise ValueError("skip_recompute_combine does not support a custom moe_layer_pattern, because the " + "optimization requires a checked preset decoder-layer contract. Leave the pattern " + "unset or disable skip_recompute_combine.") # The recompute is recognized as a grad-enabled forward that runs inside a backward pass. if not hasattr(torch._C, "_current_graph_task_id"): raise ValueError("skip_recompute_combine needs torch._C._current_graph_task_id, which this PyTorch " diff --git a/docs/_pages/config-json.md b/docs/_pages/config-json.md index 80719e619fbc..90a2d2d62e97 100644 --- a/docs/_pages/config-json.md +++ b/docs/_pages/config-json.md @@ -1013,7 +1013,7 @@ smoke coverage used for this AutoEP surface produced the following version gates | Description | Default | | -------------------------------------------------------------------------------------------------------------- | -------- | -| Experimental. In the reentrant recompute of a decoder layer, record the DeepEP route's post-expert row weighting and combine without running them: nothing reads that recomputed output, and their backward is unchanged. The skipped output is NaN. Requires `comm_backend="deepep"` with `autoep_size > 1`, a preset whose decoder layer adds the MoE output to the residual (`deepseek_v2`, `deepseek_v3`, `minimax_m3`, `mixtral`, `qwen3_5_moe`, `qwen3_moe`), and Hugging Face per-layer gradient checkpointing with `use_reentrant=True`; anything else is rejected rather than ignored. | `false` | +| Experimental. In the reentrant recompute of a decoder layer, record the DeepEP route's post-expert row weighting and combine without running them: nothing reads that recomputed output, and their backward is unchanged. The skipped output is NaN. Requires `comm_backend="deepep"` with `autoep_size > 1`, a preset whose decoder layer adds the MoE output to the residual (`deepseek_v2`, `deepseek_v3`, `minimax_m3`, `mixtral`, `qwen3_5_moe`, `qwen3_moe`), and Hugging Face per-layer gradient checkpointing with `use_reentrant=True`. Any non-null `moe_layer_pattern` is rejected, even alongside an explicit or auto-detected supported preset, because the override can select an unvalidated decoder parent. Leave the pattern unset or disable the skip; custom patterns are unchanged when the option is off. Unsupported settings are rejected rather than ignored. | `false` | ***route_norm***: [boolean] diff --git a/docs/code-docs/source/autoep.rst b/docs/code-docs/source/autoep.rst index 55f478da9c30..529d10b95161 100644 --- a/docs/code-docs/source/autoep.rst +++ b/docs/code-docs/source/autoep.rst @@ -422,8 +422,12 @@ The skip relies on nothing reading the skipped output, so it is guarded: DeepSpeed's own checkpointing API are also rejected. - Only presets whose decoder layer adds the MoE output straight to the residual are accepted: ``deepseek_v2``, ``deepseek_v3``, ``minimax_m3``, ``mixtral``, - ``qwen3_5_moe`` and ``qwen3_moe``. Other presets and custom patterns are - rejected at conversion. + ``qwen3_5_moe`` and ``qwen3_moe``. Other presets are rejected at conversion. + Any non-null ``moe_layer_pattern`` is rejected during configuration validation, + even with an explicit or auto-detected supported preset: overriding the pattern + changes the decoder parent, so the preset name no longer establishes its + output-consumer contract. Leave the pattern unset or disable the skip; + custom patterns remain supported when this option is off. - The skipped combine returns NaN rather than uninitialized memory. If something outside the contract reads it in a value-dependent operation, it can produce non-finite outputs or gradients. The sentinel is not a diff --git a/tests/unit/v1/moe/test_autoep_unit.py b/tests/unit/v1/moe/test_autoep_unit.py index ea0a57d778c1..12d207f9460e 100644 --- a/tests/unit/v1/moe/test_autoep_unit.py +++ b/tests/unit/v1/moe/test_autoep_unit.py @@ -375,6 +375,27 @@ def test_skip_recompute_combine_defaults_off_and_requires_the_deepep_route(self) assert config.skip_recompute_combine is True validate_autoep_config(config, world_size=2, pp_size=1, tp_size=1, sp_size=1) + @pytest.mark.parametrize("preset_model", [None, "mixtral"], ids=["automatic-preset", "explicit-preset"]) + @pytest.mark.parametrize("pattern", [r"custom\.wrapper\.moe", r"model\.layers\.\d+\.block_sparse_moe", ""], + ids=["custom-parent", "preset-pattern", "empty-pattern"]) + def test_skip_recompute_combine_rejects_pattern_overrides_even_with_supported_presets(self, preset_model, pattern): + settings = { + "enabled": True, + "autoep_size": 2, + "comm_backend": "deepep", + "comm_max_tokens_per_rank": 4096, + "preset_model": preset_model, + "moe_layer_pattern": pattern, + } + config = parse_autoep_config({**settings, "skip_recompute_combine": True}) + with pytest.raises(ValueError, match="skip_recompute_combine.*moe_layer_pattern"): + validate_autoep_config(config, world_size=2, pp_size=1, tp_size=1, sp_size=1) + + config = parse_autoep_config({**settings, "skip_recompute_combine": False}) + validate_autoep_config(config, world_size=2, pp_size=1, tp_size=1, sp_size=1) + config = parse_autoep_config({**settings, "skip_recompute_combine": True, "moe_layer_pattern": None}) + validate_autoep_config(config, world_size=2, pp_size=1, tp_size=1, sp_size=1) + def test_fused_combine_rejects_folded_tensor_parallelism(self): config = parse_autoep_config({ "enabled": True,