-
Notifications
You must be signed in to change notification settings - Fork 4.4k
Add DeepEP v2 flex dispatcher backend #5153
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Autumn1998
wants to merge
8
commits into
NVIDIA:main
Choose a base branch
from
Autumn1998:tongliu/deepepv2-flex-dispatcher-main
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
2566921
Add DeepEP v2 flex dispatcher backend
Autumn1998 fefb564
Make DeepEP v2 manager inherit DeepEP manager
Autumn1998 c3cfcb9
Restore DispatchManager base interface
Autumn1998 9985ab3
Clarify DeepEP v2 dispatch comments
Autumn1998 be17dd5
Fix DeepEP v2 combine backward defaults
Autumn1998 d3114d1
Simplify DeepEP v2 SM default handling
Autumn1998 30e602f
Use DeepEP v2 automatic SM default
Autumn1998 5f78fea
Merge remote-tracking branch 'origin/main' into tongliu/deepepv2-flex…
Autumn1998 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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 | ||
|
|
||
| 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: | ||
|
|
@@ -68,6 +84,32 @@ def get_buffer(group: torch.distributed.ProcessGroup, hidden_bytes: int): | |
| return _buffer | ||
|
|
||
|
|
||
| def get_elastic_buffer( | ||
| 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( | ||
| 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 | ||
|
|
||
|
|
||
| class FusedDispatch(torch.autograd.Function): | ||
| """Fused dispatch operation for MoE routing combining computation and communication.""" | ||
|
|
||
|
|
@@ -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, | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. could support |
||
| 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(), | ||
| 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 | ||
|
|
||
|
|
||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Wondering why do we have this buffer reuse mechanism for DeepEPv2, seems it is still full eager execution (shape is reading during the runtime). Also is it safe to have different layer/mb to reuse the same buffer
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think it is the recommended way to use DeepEP v2:https://nvidia.slack.com/archives/C03V462SAMS/p1779421202250149