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
3 changes: 3 additions & 0 deletions deepspeed/module_inject/auto_ep.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
43 changes: 33 additions & 10 deletions deepspeed/module_inject/auto_ep_comm.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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,
Expand All @@ -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)
19 changes: 19 additions & 0 deletions deepspeed/module_inject/auto_ep_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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")
Expand Down Expand Up @@ -234,6 +237,22 @@ 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.")
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 "
"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:
Expand Down
89 changes: 85 additions & 4 deletions deepspeed/module_inject/auto_ep_layer.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,13 @@
from __future__ import annotations

import math
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,
Expand All @@ -34,9 +36,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
Expand Down Expand Up @@ -182,6 +184,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,
Expand Down Expand Up @@ -540,6 +578,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:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Reject custom MoE patterns before enabling combine skipping

With a supported preset_model (or auto-detected model_type) plus a moe_layer_pattern override, resolve_preset_candidates() applies the override while preserving the supported preset name, so this test accepts a custom parent even though docs/code-docs/source/autoep.rst:423-426 says custom patterns are rejected. If that checkpointed parent does anything value-dependent with the MoE output before the residual, _RecordedDeepEPCombine feeds it NaNs and can corrupt gradients. Reject the override at validation/conversion or validate the actual parent contract rather than only model_family.

Useful? React with 👍 / 👎.

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
Expand Down Expand Up @@ -940,6 +986,30 @@ 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)
checkpointing = (getattr(decoder_layer, "gradient_checkpointing", False)
and getattr(decoder_layer, "training", False))
if not checkpointing 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 training mode and 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.

Expand Down Expand Up @@ -978,6 +1048,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,
Expand Down Expand Up @@ -1018,9 +1095,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,
Expand Down
1 change: 1 addition & 0 deletions deepspeed/module_inject/auto_ep_presets/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
15 changes: 15 additions & 0 deletions deepspeed/ops/triton_ops/autoep_fused_token_ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
6 changes: 6 additions & 0 deletions docs/_pages/config-json.md
Original file line number Diff line number Diff line change
Expand Up @@ -1023,6 +1023,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 a decoder layer in training mode with Hugging Face per-layer gradient checkpointing and `use_reentrant=True`. Eval-mode outer recomputes are rejected because the decoder does not checkpoint; ordinary eval forwards are unchanged. 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]

| Description | Default |
Expand Down
Loading
Loading