Skip to content
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
2566921
Add DeepEP v2 flex dispatcher backend
Autumn1998 May 14, 2026
fefb564
Make DeepEP v2 manager inherit DeepEP manager
Autumn1998 May 14, 2026
c3cfcb9
Restore DispatchManager base interface
Autumn1998 May 14, 2026
9985ab3
Clarify DeepEP v2 dispatch comments
Autumn1998 Jun 4, 2026
be17dd5
Fix DeepEP v2 combine backward defaults
Autumn1998 Jun 11, 2026
d3114d1
Simplify DeepEP v2 SM default handling
Autumn1998 Jun 11, 2026
30e602f
Use DeepEP v2 automatic SM default
Autumn1998 Jun 11, 2026
5f78fea
Merge remote-tracking branch 'origin/main' into tongliu/deepepv2-flex…
Autumn1998 Jul 21, 2026
f533bd2
Merge remote-tracking branch 'origin/main' into tongliu/deepepv2-flex…
Autumn1998 Sep 2, 2026
eb688c4
test: reuse flex dispatcher coverage for deepepv2
Autumn1998 Sep 2, 2026
0431824
Merge main into DeepEP v2 flex dispatcher branch
Autumn1998 Sep 14, 2026
fe18161
Fix DeepEP v2 buffer initialization and overlap input lifetime
Autumn1998 Sep 14, 2026
9f7cd50
Use first-use NCCL warmup without token-count synchronization
Autumn1998 Sep 14, 2026
6377af2
Merge branch 'main' into tongliu/deepepv2-flex-dispatcher-main
Autumn1998 Sep 22, 2026
e2f2392
Fix DeepEP v2 backward input event ordering
Autumn1998 Sep 22, 2026
266ab43
Handle DeepEP v2 grouped-tensor padding
Autumn1998 Sep 22, 2026
4e37802
Add DeepEP v2 installation guidance
Autumn1998 Sep 22, 2026
8242c59
Merge adlr/main into tongliu/deepepv2-flex-dispatcher-main
Autumn1998 Oct 8, 2026
ef6ec83
Enable deterministic DeepEP v2 and add replay coverage
Autumn1998 Oct 8, 2026
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
4 changes: 2 additions & 2 deletions megatron/core/models/gpt/fine_grained_callables.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ def should_free_input(name, is_moe, config, num_local_experts):
return False
enable_deepep = (
config.moe_token_dispatcher_type == "flex"
and config.moe_flex_dispatcher_backend == "deepep"
and config.moe_flex_dispatcher_backend in ("deepep", "deepepv2")
)
enable_hybridep = (
config.moe_token_dispatcher_type == "flex"
Expand Down Expand Up @@ -494,7 +494,7 @@ def build_transformer_layer_callables(layer: TransformerLayer):
is_moe = isinstance(layer.mlp, MoELayer)
enable_deepep = (
layer.config.moe_token_dispatcher_type == "flex"
and layer.config.moe_flex_dispatcher_backend == "deepep"
and layer.config.moe_flex_dispatcher_backend in ("deepep", "deepepv2")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Please also add deepepv2 to should_free_input() in megatron/core/models/common/utils.py. With MoE communication overlap enabled and moe_preprocess outside CUDA graphs, that helper currently lets the dispatch node free its input storage, but the router still needs the same tensor for backward. This leaves the router's saved input pointing at freed storage.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

fixed

)
enable_hybridep = (
layer.config.moe_token_dispatcher_type == "flex"
Expand Down
222 changes: 221 additions & 1 deletion megatron/core/transformer/moe/fused_a2a.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,32 @@
from megatron.core.utils import internal_api

try:
from deep_ep import Buffer
from deep_ep.utils import EventHandle, EventOverlap
except ImportError:
try:
from deep_ep import EventHandle, EventOverlap
except ImportError:
EventHandle = None
EventOverlap = None

try:
from deep_ep import Buffer

HAVE_DEEP_EP = True
except ImportError:
HAVE_DEEP_EP = False

try:
from deep_ep import ElasticBuffer

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Is there anyway we can leave some instructions for people who want to use deepepv2 about how to update their container and its potential impact like HybridEP might need to be uninstalled?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Added the installation instructions and the note about potentially uninstalling HybridEP here in the missing-DeepEP-v2 error message
(

if deepepv2_dispatch is None:
raise ImportError(
"DeepEP v2 (deep_ep.ElasticBuffer) is unavailable. Install or upgrade DeepEP "
"in your container following https://github.com/deepseek-ai/DeepEP#installation "
"and ensure its CUDA, PyTorch, and NCCL requirements are met. "
"HybridEP also uses the deep_ep Python module and may need to be uninstalled "
"first; replacing it with DeepEP v2 can make the hybridep backend unavailable."
)
).


HAVE_DEEP_EP_V2 = True
except ImportError:
HAVE_DEEP_EP_V2 = False

import torch

_buffer = None
_elastic_buffer = None


def get_hidden_bytes(x: torch.Tensor) -> int:
Expand Down Expand Up @@ -68,6 +84,32 @@ def get_buffer(group: torch.distributed.ProcessGroup, hidden_bytes: int):
return _buffer


def get_elastic_buffer(
Comment thread
Autumn1998 marked this conversation as resolved.
Resolved
group: torch.distributed.ProcessGroup, num_max_tokens_per_rank: int, hidden: int, num_topk: int
):
"""Get or create a DeepEP v2 elastic buffer for all-to-all communication."""
global _elastic_buffer

num_bytes = ElasticBuffer.get_buffer_size_hint(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Can we warm up this group's NCCL communicator before asking for the buffer size? On PyTorch builds with _comm_ptr(), a fresh group can still return 0, and DeepEP passes that straight into the native size calculation. That can segfault on the first dispatch, including in the new tests.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Warm up the NCCL communicator with a dummy all-reduce

group, num_max_tokens_per_rank=num_max_tokens_per_rank, hidden=hidden, num_topk=num_topk
)

if (
_elastic_buffer is None
or _elastic_buffer.group != group
or _elastic_buffer.num_bytes < num_bytes
or _elastic_buffer.num_max_tokens_per_rank < num_max_tokens_per_rank
):
_elastic_buffer = ElasticBuffer(
group,
num_bytes=num_bytes,
num_max_tokens_per_rank=num_max_tokens_per_rank,
hidden=hidden,
num_topk=num_topk,
)
return _elastic_buffer

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

import torch
import torch.distributed as dist
from typing import Optional

from deep_ep import ElasticBuffer

# Communication buffer (will allocate at runtime)
_buffer: Optional[ElasticBuffer] = None

# Number of SMs to use for communication kernels (will be set at buffer creation)
_num_comm_sms: int = 0


def get_buffer(group: dist.ProcessGroup,
               num_max_tokens_per_rank: int,
               hidden: int,
               num_topk: int,
               num_experts: int,
               use_fp8_dispatch: bool = False) -> ElasticBuffer:
    """Initialize or retrieve the ElasticBuffer for EP communication."""
    global _buffer, _num_comm_sms

    # Check if we can reuse the existing buffer
    required_bytes = ElasticBuffer.get_buffer_size_hint(
        group, num_max_tokens_per_rank, hidden,
        num_topk=num_topk, use_fp8_dispatch=use_fp8_dispatch,
    )
    if _buffer is not None and _buffer.group == group and _buffer.num_bytes >= required_bytes:
        return _buffer

    # Allocate a new buffer with MoE settings
    # NOTES: V2 buffer size consumption is larger than V1
    _buffer = ElasticBuffer(
        group,
        num_max_tokens_per_rank=num_max_tokens_per_rank,
        hidden=hidden,
        num_topk=num_topk,
        use_fp8_dispatch=use_fp8_dispatch,
    )

    # V2 analytically calculates the optimal SM count — no more auto-tuning needed
    # You may also specify `num_sms` manually in dispatch/combine calls to override
    _num_comm_sms = _buffer.get_theoretical_num_sms(num_experts, num_topk)

    return _buffer

The demo code in DeepEP github include _buffer.get_theoretical_num_sms, why not use this here?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

We only pass a manually configured num_sms when it is explicitly set. If it is unset, the default value is 0, which lets DeepEP v2 automatically
resolve the SM count by invoking get_theoretical_num_sms(...) internally:
https://github.com/deepseek-ai/DeepEP/blob/01dc3aaac82068020353dce2c302e38153c0bfaa/deep_ep/buffers/elastic.py#L928



class FusedDispatch(torch.autograd.Function):
"""Fused dispatch operation for MoE routing combining computation and communication."""

Expand Down Expand Up @@ -267,6 +309,184 @@ def set_deepep_num_sms(num_sms):
set_deepep_num_sms = None


class DeepepV2Dispatch(torch.autograd.Function):
"""Dispatch operation using the DeepEP v2 ElasticBuffer backend."""

@staticmethod
def forward(
ctx,
buffer,
x,
token_indices,
token_probs,
num_experts,
num_max_tokens_per_rank,
expert_alignment,
num_sms,
async_finish=False,
allocate_on_comm_stream=False,
):
"""Forward pass of dispatch using the DeepEP v2 ElasticBuffer backend."""
# Capture the current stream for the communication stream to wait on when
# DeepEP v2 allocates output tensors on the communication stream.
previous_event = buffer.capture() if async_finish and allocate_on_comm_stream else None
# Process the dispatch and keep the handle for the subsequent combine call.
recv_x, recv_token_indices, recv_token_probs, handle, event = buffer.dispatch(
x,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

could support do_expand=True ? @Autumn1998

@Autumn1998 Autumn1998 Sep 2, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

DeepEP support dp_expand=True at deepseek-ai/DeepEP#674, now we will change to the new do_expand style in another PR

topk_idx=token_indices,
topk_weights=token_probs,
num_experts=num_experts,
num_max_tokens_per_rank=num_max_tokens_per_rank,
expert_alignment=expert_alignment,
num_sms=num_sms,
previous_event=previous_event,
async_with_compute_stream=async_finish,
allocate_on_comm_stream=allocate_on_comm_stream,
)

if async_finish:
event.current_stream_wait()

ctx.buffer = buffer
ctx.handle = handle
ctx.num_sms = handle.num_sms
ctx.async_finish = async_finish
ctx.allocate_on_comm_stream = allocate_on_comm_stream
tokens_per_expert = torch.tensor(handle.num_recv_tokens_per_expert_list)

return (recv_x, recv_token_indices, recv_token_probs, tokens_per_expert, handle)

@staticmethod
def backward(
ctx, grad_output, grad_token_indices, grad_token_probs, grad_tokens_per_expert, grad_handle
):
"""Backward pass of dispatch using the DeepEP v2 ElasticBuffer backend."""
# The backward pass of dispatch is a combine over the dispatch handle.
previous_event = (
ctx.buffer.capture() if ctx.async_finish and ctx.allocate_on_comm_stream else None
)
grad_x, grad_token_probs, event = ctx.buffer.combine(
grad_output.contiguous(),
handle=ctx.handle,
topk_weights=grad_token_probs.float(),
num_sms=ctx.num_sms,
previous_event=previous_event,
async_with_compute_stream=ctx.async_finish,
allocate_on_comm_stream=ctx.allocate_on_comm_stream,
)
if ctx.async_finish:
event.current_stream_wait()
return None, grad_x, None, grad_token_probs, None, None, None, None, None, None


class DeepepV2Combine(torch.autograd.Function):
"""DeepEP v2 elastic combine with autograd support."""

@staticmethod
def forward(ctx, buffer, x, handle, num_sms, async_finish=False, allocate_on_comm_stream=False):
"""Forward pass of DeepEP v2 elastic combine."""
previous_event = buffer.capture() if async_finish and allocate_on_comm_stream else None
combined_x, combined_token_probs, event = buffer.combine(
x,
handle=handle,
num_sms=num_sms,
previous_event=previous_event,
async_with_compute_stream=async_finish,
allocate_on_comm_stream=allocate_on_comm_stream,
)
if async_finish:
event.current_stream_wait()

ctx.buffer = buffer
ctx.handle = handle
ctx.num_sms = handle.num_sms if num_sms == 0 else num_sms
ctx.async_finish = async_finish
ctx.allocate_on_comm_stream = allocate_on_comm_stream
return combined_x, combined_token_probs

@staticmethod
def backward(ctx, grad_output, grad_combined_token_probs):
"""Backward pass of DeepEP v2 elastic combine."""
previous_event = (
ctx.buffer.capture() if ctx.async_finish and ctx.allocate_on_comm_stream else None
)
grad_x, _, _, _, event = ctx.buffer.dispatch(
grad_output.contiguous(),
Comment thread
guihong-nv marked this conversation as resolved.
Resolved
handle=ctx.handle,
num_sms=ctx.num_sms,
previous_event=previous_event,
async_with_compute_stream=ctx.async_finish,
allocate_on_comm_stream=ctx.allocate_on_comm_stream,
)
if ctx.async_finish:
event.current_stream_wait()
return None, grad_x, None, None, None, None


if HAVE_DEEP_EP_V2:

def deepepv2_dispatch(
buffer,
x,
token_indices,
token_probs,
num_experts,
num_max_tokens_per_rank,
expert_alignment=1,
num_sms=0,
async_finish=False,
allocate_on_comm_stream=False,
):
"""Perform dispatch using the DeepEP v2 ElasticBuffer backend.

Args:
buffer (ElasticBuffer):
DeepEP v2 buffer used for all-to-all communication.
x (torch.Tensor):
Input hidden states to dispatch.
token_indices (torch.Tensor):
Top-k expert indices for each token.
token_probs (torch.Tensor):
Top-k routing probabilities for each token.
num_experts (int):
Total number of experts across the communication group.
num_max_tokens_per_rank (int):
Maximum number of input tokens on each rank.
expert_alignment (int):
Alignment applied to per-expert token counts.
num_sms (int):
Number of SMs used by the dispatch API.
async_finish (bool):
Whether to use asynchronous communication completion.
allocate_on_comm_stream (bool):
Whether to allocate DeepEP output buffers on the communication stream.
"""
return DeepepV2Dispatch.apply(
buffer,
x.contiguous(),
token_indices,
token_probs,
num_experts,
num_max_tokens_per_rank,
expert_alignment,
num_sms,
async_finish,
allocate_on_comm_stream,
)

def deepepv2_combine(
buffer, x, handle, num_sms=0, async_finish=False, allocate_on_comm_stream=False
):
"""Perform DeepEP v2 elastic combine."""
return DeepepV2Combine.apply(
buffer, x.contiguous(), handle, num_sms, async_finish, allocate_on_comm_stream
)

else:
deepepv2_dispatch = None
deepepv2_combine = None


try:
from deep_ep import HybridEPBuffer

Expand Down
Loading
Loading