Skip to content

🚨 deepgemm_megamoe EP implementation for DeepGEMM Mega MoE - #49606

Merged
IlyasMoutawwakil merged 66 commits into
mainfrom
ep-passthrough-strategy
Nov 12, 2026
Merged

IlyasMoutawwakil merged 66 commits into
mainfrom
ep-passthrough-strategy

Conversation

@IlyasMoutawwakil

@IlyasMoutawwakil IlyasMoutawwakil commented Oct 14, 2026 •

Copy link
Copy Markdown
Member

🤗 Transformers CI

Depends on #49429.

DeepGEMM Mega MoE fuses the token dispatch, the experts and the combine in one kernel. It needs global expert ids, unmasked routing weights and the EP process group. Until now it only got them through the megamoe_router and megamoe_experts styles. On the default ep_dispatch_experts plan, which DeepSeek V4 ships, loading with experts_implementation="deepgemm_megamoe" failed at the first forward (DeepGEMM Mega MoE requires a process_group).

This PR adds a "deepgemm_megamoe" EP implementation. "auto" runs it for experts loaded with experts_implementation="deepgemm_megamoe", since they can only run through it; another explicit implementation raises. It requires ep_size == tp_size, like the old styles.

🚨 Breaking: the megamoe_router and megamoe_experts parallel styles are removed. A plan that names them should use ep_dispatch_experts on the experts and drop the router rule; loading with experts_implementation="deepgemm_megamoe" selects the implementation.

How it runs

The kernel treats each rank's rows as that rank's own tokens. Here every rank holds the same batch.

  • Each rank hands the kernel an equal slice of the batch. The last slice is padded with skipped slots.
  • The slices' outputs are all-gathered back, so every token goes through the experts once.
  • The symmetric-memory buffers are kept per EP group and shared by every layer. Before, each experts module allocated its own.
  • A buffer grows to the batch it needs, not the next power of two, releasing the old one first so its memory is reused; warming up at the largest batch allocates it once.

Example with 4 tokens on 2 ranks:

GPU                    0                      1
batch           [t0, t1, t2, t3]       [t0, t1, t2, t3]
kernel input        [t0, t1]               [t2, t3]
kernel output       [y0, y1]               [y2, y3]
after all-gather         [y0, y1, y2, y3] on both ranks

Changes

File Change
distributed/expert_parallel.py MegaMoeEP, registered as "deepgemm_megamoe". It passes the EP group to the experts as process_group. AutoEP builds it for Mega MoE experts.
integrations/deepgemm.py The Mega MoE forward keeps its symmetric buffers per EP group (process_group.group_name) and shape, shared by every layer. destroy_megamoe_buffers() frees them, like DeepEP's destroy_deepep_buffers() (#49638).
integrations/tensor_parallel.py, integrations/finegrained_fp8.py Removed: the megamoe_router and megamoe_experts styles, and the FP8 plan rewrites to them.
Docs A "deepgemm_megamoe" row in the EP implementation table. The two styles leave the parallel styles page.

Performance

On main, loading experts_implementation="deepgemm_megamoe" on the ep_dispatch_experts plan fails at the first forward, so main runs these experts through the all_reduce implementation with DeepGEMM's grouped FP8×FP4 kernel. Against that, on the same FP4 weights and the same batch on every rank (B200, EP 2, 64 experts, hidden 4096, intermediate 2048, top_k 6; median per call of the slowest rank; outputs agree to cosine ≥ 0.9989):

Tokens deepgemm_megamoe eager all_reduce eager Speedup deepgemm_megamoe CUDA graph all_reduce CUDA graph Speedup
1 0.718 ms 1.871 ms 2.6x 0.102 ms 0.314 ms 3.1x
8 0.665 ms 1.886 ms 2.8x 0.154 ms 0.515 ms 3.3x
64 0.651 ms 1.880 ms 2.9x 0.182 ms 0.615 ms 3.4x
512 0.671 ms 1.886 ms 2.8x 0.221 ms 1.033 ms 4.7x
4096 0.873 ms 5.396 ms 6.2x 0.551 ms 4.790 ms 8.7x
16384 2.018 ms 17.849 ms 8.8x 1.905 ms 17.402 ms 9.1x

The Mega MoE kernel alone takes 0.076 ms at 1 token and 1.234 ms at 16384, before the all-gather. Most of the rest is DeepGEMM's per_token_cast_to_fp8, a PyTorch reference of about a dozen kernels; a fused cast is going into the deep-gemm Hub kernel. Against a dense fp32 reference built from every expert's dequantized weights the lowest cosine is 0.988–0.992 at 1, 7, 64 and 129 tokens, and 0.9991–0.9998 once the reference also quantizes its activations to FP8 as the kernel does.

The symmetric buffer takes about 1 MiB per token of capacity per rank at DeepSeek-V4 sizes (EP 8, 256 experts, hidden 7168, top_k 8), and its capacity is the largest batch seen, aligned to DeepGEMM's 384-token block. Growing it releases the old one first, so device memory follows the current buffer. The symmetric-memory pool keeps its high-water mark: destroy_megamoe_buffers() releases the buffers, not the pool.

Tests

Test Result
tests/expert_parallel, 2 ranks on gloo. The new Mega MoE test checks that "auto" runs it and "all_to_all" is refused, the padded slices, global ids, the EP group and the gathered output; the DeepGEMM kernel tests check the buffers are cached per EP group. 8 passed
TP and EP model tests of Mixtral, Qwen3-MoE, GPT-OSS and DeepSeek-V3, on CPU 273 passed
The DeepGEMM Mega MoE tests pass the cache and check the buffer lands in it. 2 passed

🤖 Generated with Claude Code

@HuggingFaceDocBuilderDev

HuggingFaceDocBuilderDev commented Oct 14, 2026 •

Copy link
Copy Markdown

The docs for this PR live here. All of your documentation changes will be reflected on that endpoint. The docs are available until 30 days after the last update.

Pages changed in this PR:

@IlyasMoutawwakil IlyasMoutawwakil changed the title passthrough expert-parallel strategy for DeepGEMM Mega MoE deepgemm_megamoe expert-parallel strategy for DeepGEMM Mega MoE Oct 14, 2026
@IlyasMoutawwakil
IlyasMoutawwakil force-pushed the ep-passthrough-strategy branch 2 times, most recently from 1bfd600 to 6ca9df4 Compare October 16, 2026 06:51
@IlyasMoutawwakil IlyasMoutawwakil changed the title deepgemm_megamoe expert-parallel strategy for DeepGEMM Mega MoE deepgemm_megamoe EP implementation for DeepGEMM Mega MoE Oct 16, 2026
IlyasMoutawwakil and others added 3 commits November 9, 2026 18:41
…face registry, doc notes

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…y-rows case in `AllToAllEP`

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…o ep-passthrough-strategy

# Conflicts:
#	docs/source/en/expert_parallelism.md
#	src/transformers/distributed/expert_parallel.py
Base automatically changed from ep-masked-when-shared-batch to main November 12, 2026 10:33
…_megamoe_buffers()`

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@IlyasMoutawwakil IlyasMoutawwakil changed the title deepgemm_megamoe EP implementation for DeepGEMM Mega MoE 🚨 deepgemm_megamoe EP implementation for DeepGEMM Mega MoE Nov 12, 2026
IlyasMoutawwakil and others added 4 commits November 12, 2026 11:45
# Conflicts:
#	docs/source/en/expert_parallelism.md
#	src/transformers/distributed/configuration_utils.py
#	src/transformers/distributed/expert_parallel.py
#	tests/expert_parallel/test_expert_parallel.py
#	tests/quantization/finegrained_fp8/test_fp8.py
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…o longer rewrites `ep_implementation`

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@vasqu vasqu left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Looking much better overall, I have a few smaller comments

Comment on lines +367 to +369
def _uses_megamoe(experts: nn.Module) -> bool:
"""Mega MoE experts exchange the tokens inside their kernel, so only `MegaMoeEP` can run them."""
return getattr(getattr(experts, "config", None), "_experts_implementation", None) == "deepgemm_megamoe"

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

imo useful publicly + are the getattr really that necessary? Imo everything should exist and this is overly cautious no?

Also what about VLMs where things are nested?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

we assume experts is just an nn.Module which might not be decorated by the use_experts_implementation decorator

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

ah fair enough, it does look a bit weird tho

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

vlms are fine: the experts get the text config, and setting _experts_implementation on the top config propagates to the sub configs. i'd keep it private until something outside ep needs it

back to the host, so decode captures in a CUDA graph.
The default. It runs, in order:

- `MegaMoeEP` for Mega MoE experts, which only run through it.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Let's be slightly more explicit and add the deepgemm?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

you mean rename it as DeepGemmMegaMoe ?

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

yep just to be super explicit(?)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

went with the docstring for now: "DeepGEMM Mega MoE experts (experts_implementation="deepgemm_megamoe")"

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

did you mean renaming the whole class ?

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

no just docs is enough imo

self.megamoe = MegaMoeEP(experts, ep_mesh, tp_mesh) if _uses_megamoe(experts) else None

def __call__(self, hidden_states, top_k_index, top_k_weights):
if self.megamoe is not None:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

should we not raise against training if detected? or is it done somewhere down the line?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

good catch, nothing did: fp8 counts as trainable, so gradients were silently dropped. the megamoe forward now raises when the inputs need grads

# Legacy masked EP, or Mega MoE dispatching inside its kernel: the EP group is the TP group, every
# rank keeps every token.
if {"ep_router", "moe_tp_experts"}.issubset(ep_plan.values()):
# Legacy masked EP: the EP group is the TP group, every rank keeps every token.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

not on you but can we consider it legacy because TP only would benefit from this anyways

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

yes, #49615 removes it

self.symm_buffer = deepgemm.get_symm_buffer_for_mega_moe(
# Lazily (re)allocate the symmetric buffer for this shape when the cached one is too small. It is sized to the next
# power of two of the batch, so a growing batch reallocates (and rendezvouses) a few times rather than on every size.
symm_buffers = _SYMM_BUFFERS.setdefault(process_group.group_name, {})

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

why not directly make it a defaultdict?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

done

Comment on lines +914 to +917
# Lazily (re)allocate the symmetric buffer for this shape when the cached one is too small. It is sized to the next
# power of two of the batch, so a growing batch reallocates (and rendezvouses) a few times rather than on every size.
buffer_key = (hidden_dim, num_top_k, num_global_experts, intermediate_hidden)
if buffer_key not in symm_buffers or symm_buffers[buffer_key].num_max_tokens_per_rank < num_tokens:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

liking this much more!

_SYMM_BUFFERS: dict[str, dict] = {}


def destroy_megamoe_buffers():

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

ig it still has to be done manually, at some point it would be nice to think of a cleanup strategy but its not super important for now

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

agreed, same as deepep's buffers for now

IlyasMoutawwakil and others added 5 commits November 12, 2026 13:36
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ckpoints

The test's MiniMax-M2 FP8 checkpoint has plain float32 scales, which DeepGEMM has no path for on SM100 (it takes
UE8M0 only) and refuses with `NotImplementedError`, so the `deepgemm` case failed on B200, on main as well.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… the batch, pad only the rank's slice

- The tokens are cast to FP8 with packed UE8M0 group-32 scales straight into the buffer (bit for bit DeepGEMM's
  `per_token_cast_to_fp8`, without its padded copy, fp32 temporaries and the host sync in its packing check), and the
  top-k ids and weights staged with them, in one helper.
- The buffer grows to the batch it needs (DeepGEMM aligns it to its token block) instead of the next power of two, which
  could double it (4097 tokens per rank took 8448 rows instead of 4224, about 4 GB per rank at DeepSeek-V4 sizes), and
  the old one is released first, after every rank is done with it, so its memory is reused instead of stacking up.
- `MegaMoeEP` pads only a slice that runs past the batch, not the whole batch.

B200, EP 2, 64 experts, hidden 4096, top_k 6: 7-13% faster eager and 4-8% under CUDA graphs (1 token: 0.687 -> 0.596
ms eager, 0.096 -> 0.088 ms replayed), outputs unchanged against a dense reference.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The staging is one 32-wide reduction and its pointwise ops, which `torch.compile` fuses bit for bit the same. It is
compiled on first use (and once more when the batch size first changes), and left to the outer compile when the model
itself is compiled.

B200, EP 2, 64 experts, hidden 4096, top_k 6, the whole `MegaMoeEP` call against the previous commit's eager staging:
1 token 0.088 -> 0.061 ms in a CUDA graph, 16384 tokens 1.815 -> 1.331 ms.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
_SYMM_BUFFERS.clear()


def _fill_megamoe_buffer(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

sorry to intervene but I'd rather move this to kernels side than here and we can add proper compile / cuda graph support afterwards then

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

even tho it's not a kernel ?

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

before it was per_token_cast_to_fp8 right? Feel like it just is better as helper within the kernel

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

yes it was per_token_cast_to_fp8, which seems non-traceable in this path

IlyasMoutawwakil and others added 2 commits November 12, 2026 05:58
Compiling the model fuses the staging (one reduction and its pointwise ops, bit for bit the same); the integration no
longer compiles it on its own.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The fused cast moves into the `deep-gemm` Hub kernel instead; until then the forward keeps DeepGEMM's
`per_token_cast_to_fp8` and copies its outputs into the symmetric buffer. The buffer sizing and the slice-only padding
stay.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@IlyasMoutawwakil
IlyasMoutawwakil added this pull request to the merge queue Nov 12, 2026
@IlyasMoutawwakil
IlyasMoutawwakil removed this pull request from the merge queue due to a manual request Nov 12, 2026
@github-actions

Copy link
Copy Markdown
Contributor

[For maintainers] Suggested jobs to run (before merge)

run-slow: finegrained_fp8

@IlyasMoutawwakil
IlyasMoutawwakil enabled stacked auto-merge November 12, 2026 15:02
@IlyasMoutawwakil
IlyasMoutawwakil added this pull request to the merge queue Nov 12, 2026
Merged via the queue into main with commit f5d8e7d Nov 12, 2026
124 checks passed
@IlyasMoutawwakil
IlyasMoutawwakil deleted the ep-passthrough-strategy branch November 12, 2026 15:44
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants