Repository navigation
🚨 deepgemm_megamoe EP implementation for DeepGEMM Mega MoE - #49606
Conversation
…ers into unify-resolve-plan
This reverts commit 3f1e4ab.
|
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: |
passthrough expert-parallel strategy for DeepGEMM Mega MoEdeepgemm_megamoe expert-parallel strategy for DeepGEMM Mega MoE
1bfd600 to
6ca9df4
Compare
deepgemm_megamoe expert-parallel strategy for DeepGEMM Mega MoEdeepgemm_megamoe EP implementation for DeepGEMM Mega MoE
…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
…_megamoe_buffers()` Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
deepgemm_megamoe EP implementation for DeepGEMM Mega MoEdeepgemm_megamoe EP implementation for DeepGEMM Mega MoE
# 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
left a comment
There was a problem hiding this comment.
Looking much better overall, I have a few smaller comments
| 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" |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
we assume experts is just an nn.Module which might not be decorated by the use_experts_implementation decorator
There was a problem hiding this comment.
ah fair enough, it does look a bit weird tho
There was a problem hiding this comment.
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. |
There was a problem hiding this comment.
Let's be slightly more explicit and add the deepgemm?
There was a problem hiding this comment.
you mean rename it as DeepGemmMegaMoe ?
There was a problem hiding this comment.
yep just to be super explicit(?)
There was a problem hiding this comment.
went with the docstring for now: "DeepGEMM Mega MoE experts (experts_implementation="deepgemm_megamoe")"
There was a problem hiding this comment.
did you mean renaming the whole class ?
| 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: |
There was a problem hiding this comment.
should we not raise against training if detected? or is it done somewhere down the line?
There was a problem hiding this comment.
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. |
There was a problem hiding this comment.
not on you but can we consider it legacy because TP only would benefit from this anyways
| 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, {}) |
There was a problem hiding this comment.
why not directly make it a defaultdict?
| # 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: |
| _SYMM_BUFFERS: dict[str, dict] = {} | ||
|
|
||
|
|
||
| def destroy_megamoe_buffers(): |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
agreed, same as deepep's buffers for now
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( |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
even tho it's not a kernel ?
There was a problem hiding this comment.
before it was per_token_cast_to_fp8 right? Feel like it just is better as helper within the kernel
There was a problem hiding this comment.
yes it was per_token_cast_to_fp8, which seems non-traceable in this path
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>
|
[For maintainers] Suggested jobs to run (before merge) run-slow: finegrained_fp8 |
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_routerandmegamoe_expertsstyles. On the defaultep_dispatch_expertsplan, which DeepSeek V4 ships, loading withexperts_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 withexperts_implementation="deepgemm_megamoe", since they can only run through it; another explicit implementation raises. It requiresep_size == tp_size, like the old styles.🚨 Breaking: the
megamoe_routerandmegamoe_expertsparallel styles are removed. A plan that names them should useep_dispatch_expertson the experts and drop the router rule; loading withexperts_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.
Example with 4 tokens on 2 ranks:
Changes
distributed/expert_parallel.pyMegaMoeEP, registered as"deepgemm_megamoe". It passes the EP group to the experts asprocess_group.AutoEPbuilds it for Mega MoE experts.integrations/deepgemm.pyprocess_group.group_name) and shape, shared by every layer.destroy_megamoe_buffers()frees them, like DeepEP'sdestroy_deepep_buffers()(#49638).integrations/tensor_parallel.py,integrations/finegrained_fp8.pymegamoe_routerandmegamoe_expertsstyles, and the FP8 plan rewrites to them."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 theep_dispatch_expertsplan fails at the first forward, so main runs these experts through theall_reduceimplementation 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):deepgemm_megamoeeagerall_reduceeagerdeepgemm_megamoeCUDA graphall_reduceCUDA graphThe 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 thedeep-gemmHub 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
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.🤖 Generated with Claude Code