Skip to content

[Common][PyTorch] Add FusedMoE with EP dispatch/combine and GEMM overlap - #3906

Open
phu0ngng wants to merge 13 commits into
NVIDIA:mainfrom
phu0ngng:feat/moe-overlap-ops-main
Open

phu0ngng wants to merge 13 commits into
NVIDIA:mainfrom
phu0ngng:feat/moe-overlap-ops-main

Conversation

@phu0ngng

@phu0ngng phu0ngng commented Nov 20, 2026 •

Copy link
Copy Markdown
Collaborator

Description

Adds FusedMoE, a fused MoeDispatch -> GroupedLinear -> ScaledSwiGLU -> GroupedLinear -> MoeCombine op. The NCCL EP dispatch overlaps FC1 and the combine overlaps FC2, in forward and backward. Weight gradients are computed inside the backward calls. Supports BF16 and MXFP8 (E4M3) on Blackwell (SM 10.0, 10.3) and Rubin (SM 10.7), with fixed-capacity CUDA graphs and eager receive sizing.

Type of change

  • Documentation change (change only to the documentation, either a fix or a new content)
  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • Infra/Build change
  • Code refactoring

Changes

  • Common: new C API ep_gemm.h (nvte_ep_dispatch_gemm_fwd/bwd, nvte_ep_combine_gemm_fwd/bwd, workspace query). Readiness flags are one per alignment rows for the dispatch and one per 1024 hidden columns (or the whole row) for the combine, wired to the NCCL EP signal API (needs NCCL EP >= 0.3.0). A single reset kernel prepares each call's scratch.
  • CuTeDSL adapters: common/CuTeDSL/ep_gemm loads the grouped GEMMs from the directory in NVTE_MOE_OVERLAP, an external kernel tree meant to move into cuDNN. Requires NVTE_ENABLE_CUTEDSL_BACKEND=1 and NVTE_WITH_CUTEDSL=1 at build time.
  • PyTorch: tex.ep_*_gemm_* bindings, which check that all operands are CUDA tensors on the current device, and ops/fused/moe_overlap.py, registered with the fuser. One forward serves both recipes through small per-recipe operand classes. A frozen FC1 or FC2 weight skips its weight-gradient preparation and saved inputs. With the overlap enabled, a window that cannot be fused raises with the reason instead of silently running unfused.
  • Docs and example: NVTE_MOE_OVERLAP in docs/envvars.rst, and examples/pytorch/ep/bench/bench_moe_overlap.py for fwd/bwd timing.

Dependencies:

  • NCCL EP submodule needs to be bumped
  • cuDNN version needs to be added.

Checklist:

  • I have read and followed the contributing guidelines
  • The functionality is complete
  • I have commented my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works
  • New and existing unit tests pass locally with my changes

@greptile-apps

greptile-apps Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 4/5 · Fix the unsupported alignment passes before merging so the EP suite can pass with overlap enabled.RetriggerView in GreptileConfidence Score: 4/5

[Medium impact] The changes add a specialized overlapped path to PyTorch expert-parallel MoE workflows.

Fix the unsupported alignment passes before merging so the EP suite can pass with overlap enabled.

Findings

  1. P1 Overlap tests request unsupported alignments ▶
  2. P2 Setup names unused kernel directory ▶

Summary

Adds FusedMoE with expert communication overlapped with grouped GEMMs, plus backward weight gradients.

  • Expert-parallel dispatch and combine now overlap with grouped GEMM work.
  • Compatible MoE layers run as one fused forward and backward operation.

The three earlier unnumbered findings are addressed: MXFP8 graph replay is covered, workspace sizing skips unsupported output variants, and caller-provided buffers now raise instead of being silently ignored.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart LR
  A[Input tokens] --> B[Dispatch overlaps FC1 and SwiGLU]
  B --> C[FC2 overlaps combine]
  C --> D[Output tokens]
  D --> E[Backward dispatch overlaps FC2 gradient]
  E --> F[FC1 gradient and backward combine]
  E --> G[FC2 weight gradient]
  F --> H[FC1 weight gradient]
Loading

Reviews (8) · Last reviewed commit: "[pre-commit.ci] auto fixes from pre-comm..." · Reviewed by Greptile

Comment thread tests/pytorch/distributed/run_ep.py Resolved
@phu0ngng
phu0ngng force-pushed the feat/moe-overlap-ops-main branch from 82d9201 to 7c92f4a Compare November 20, 2026 17:15
@phu0ngng phu0ngng added the 3.0 label Nov 20, 2026
@phu0ngng
phu0ngng force-pushed the feat/moe-overlap-ops-main branch from 7c92f4a to 6e27c25 Compare November 21, 2026 00:20
@phu0ngng
phu0ngng marked this pull request as draft November 21, 2026 03:38
@phu0ngng
phu0ngng force-pushed the feat/moe-overlap-ops-main branch from ff21bae to be1df76 Compare November 23, 2026 18:43
@phu0ngng
phu0ngng force-pushed the feat/moe-overlap-ops-main branch from be1df76 to a279351 Compare November 24, 2026 05:01
@phu0ngng phu0ngng changed the title [Common][PyTorch] EP Gemm Overlap [Common][PyTorch] Add FusedMoE with EP dispatch/combine and GEMM overlap Nov 24, 2026
@phu0ngng
phu0ngng marked this pull request as ready for review November 24, 2026 05:05
dinodeep added a commit to dinodeep/TransformerEngine that referenced this pull request Nov 25, 2026
The overlap path no longer rejects TE checkpoint names. The forward tags the
residuals of the fused dispatch+FC1 call (routing state, received tokens and
their MXFP8 scales, received routing weights, per-expert counts, the FC1
output and, for BF16, the SwiGLU output) with checkpoint_name; the wo name
tags nothing because the overlap backward does not read FC2's output. Under a
names-based remat policy JAX rebuilds unsaved residuals by re-running only the
fused dispatch+FC1 call; FC2+combine is never re-run (no separate recompute
path).

A re-run dispatch can place the received rows in a different order, so mixing
saved and rebuilt residuals corrupts the gate and input gradients (measured:
relative error ~1). Every fused-call residual therefore carries all given
names (dispatch, wi_0, wi_1), nested, and is saved when the policy saves any
of them: a mixed policy saves all of them, otherwise all are rebuilt.

_MoEBlock gains wi_0/wi_1/wo_checkpoint_name (forwarded to moe()).

Tests (tests/jax/test_te_ep_moe.py, 4x GB300, EP2xFSDP2, unfused mode):
test_ep_remat_policy over BF16/MXFP8 x policies {wo saved (MaxText custom
remat), nothing saved, dispatch+wo, wi+wo}: overlap loss and gradients match
the un-rematerialized flag-off step; compiled HLO has 2x
te_ep_dispatch_gemm_fwd_ffi when no fused-call name is saved (1x otherwise)
and 1x each other overlap call. The flag-off path is checked only with
everything rematerialized: with saved residuals and a re-run dispatch it shows
the same row-order mismatch (pre-existing, not changed here).
`-k "overlap or remat or checkpoint"`: 63 passed, 29 skipped.

DeepSeek-V3 MaxText proxy (4x GB300, EP4, 1 dense + 4 MoE layers, FP8 dense
+ MXFP8 MoE, pdb 6 x seq 4096, GA 2, custom remat: dispatch and moe_mlpwi
remat, moe_mlpwo saved): the compiled train step has
te_ep_dispatch_gemm_fwd_ffi x16, te_ep_combine_gemm_fwd_ffi x8 and each
backward call x8 (4 layers x 2 microbatches: dispatch+FC1 re-run once per
layer, FC2+combine not re-run). With the overlap on (+ native layouts) vs
off: step 0.991 vs 1.090 s (-9.0%), LHS estimate 98.2 vs 107.7 GiB, peak
159.5 vs 169.7 GiB, losses within 0.004 over 24 steps.

Depends on upstream PR NVIDIA#3906.

Signed-off-by: Deep Patel <deepatel@nvidia.com>
dinodeep added a commit to dinodeep/TransformerEngine that referenced this pull request Nov 25, 2026
NCCL EP allocates a group's handle scan scratch lazily, on the first handle
init or import. In a MaxText train step (XLA command buffers with
CUSTOM_CALL) the first overlap call that imports a handle ran inside a CUDA
graph capture, and the allocation failed: "EP combine_gemm_fwd failed: CUDA
error nccl_ep.cc:4370 'operation not permitted when stream is capturing'".

nvte_ep_overlap_compile, which already runs at trace time once per layer
configuration, now opens and closes a handle for the layer configuration
(EPBackend::warm_handle_scratch) so the scratch exists before any captured
call. No behaviour change otherwise.

Measured (4x GB300, DeepSeek-V3 proxy, 1 dense + 4 MoE layers, EP4, FP8 +
MXFP8 MoE, pdb 6, GA 2, command buffers incl. CUSTOM_CALL): before, arm B
failed at the first step; after, it runs (step 0.983 s, same as with
CUSTOM_CALL removed from the command buffers).

Depends on upstream PR NVIDIA#3906.

Signed-off-by: Deep Patel <deepatel@nvidia.com>
Comment thread docs/api/pytorch.rst Resolved
Comment thread docs/envvars.rst
.. envvar:: NVTE_MOE_OVERLAP

:Type: ``str`` (directory)
:Default: unset (overlap off)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Why having default off? If the NCCL EP version and the cuDNN version is right, we should try to default to the overlap, no?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Because there is no IB support yet in TE 3.0.
I would prefer to have it off by default for now, until the support matrix is completed.

Comment thread docs/envvars.rst
Comment on lines +165 to +166
TODO(phuonguyen): once the CuTeDSL kernels are upstreamed into cuDNN, this should take a plain
0/1 (or false/true) toggle instead of a directory path.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Leaving a comment here as well to make sure that this TODO is not forgotten.

Comment thread tests/pytorch/test_ep_gemm.py Resolved
Comment on lines +7 to +10
When the copy used in the forward is quantized differently from the operand the backward weight
gradient needs, this re-quantizes the received rows into that backward layout. Unlike
``nvte_group_requantize``, it writes the columnwise operand with scales swizzled per expert. Only
MXFP8 (rowwise to columnwise) is supported.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

We should not introduce a completely new file here, but rather improve the group_requantize to provide that. I thought that this was already done @phu0ngng ?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

This is the legacy quantize kernel coupled with signalling we had for the previous bwd schedule.
In a later experiment, we found a better schedule that no longer needs to overlap requant with dispatch; thus, no signalling is needed for requant. I will remove this kernel.

Comment thread tests/pytorch/distributed/run_ep.py Resolved
Comment thread transformer_engine/pytorch/ep.py Outdated

shape = (_BOOTSTRAP_SETTINGS["max_tokens_per_rank"], _BOOTSTRAP_SETTINGS["hidden_dim"])
data_bytes = round_up_to_nearest_multiple(math.prod(shape), 256)
scale_shape = MXFP8Quantizer(DType.kFloat8E4M3).get_scale_shape(shape, False)

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.

Can we accept the quantizer to this function. We are creating it creating it in the quantize_for_dispatch function. Would allow us to keep this function generic.

Also general question why do we need symmetric memory only in case of mxfp8. why not for bf16?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Done: the function now takes the quantizer and raises for non-MXFP8, and it is created once and reused.
Symm-mem is only for MXFP8 because TE owns that quantized buffer and can write it straight into the window, so there is no staging copy. The BF16 input is the caller's tensor, and we can't guarantee it is in symm-mem without a copy.

Comment thread transformer_engine/pytorch/ep.py Resolved
Comment thread transformer_engine/pytorch/ep.py Resolved
Comment on lines +46 to +83
DLTensorWrapper wrap_data(const NVTEBasicTensor& data, bool flatten_2d) {
return DLTensorWrapper(data, flatten_2d, transformer_engine::cuda::current_device());
}

DLTensorWrapper wrap_rowwise(NVTETensor t, bool flatten_2d) {
return wrap_data(NVTEBasicTensor{nvte_tensor_data(t), nvte_tensor_type(t), nvte_tensor_shape(t)},
flatten_2d);
}

DLTensorWrapper wrap_raw(void* ptr, NVTEDType dtype, size_t count) {
NVTEShape shape{};
shape.ndim = 1;
shape.data[0] = count;
return wrap_data(NVTEBasicTensor{ptr, dtype, shape}, false);
}

// Columnwise data of an MXFP8 operand.
DLTensorWrapper wrap_columnwise(NVTETensor t, bool flatten_2d) {
const NVTEBasicTensor data = nvte_get_tensor_param(t, kNVTEColumnwiseData);
NVTE_CHECK(data.data_ptr != nullptr, "MXFP8 operand without columnwise data");
return wrap_data(data, flatten_2d);
}

// E8M0 scales of a [rows, cols] MXFP8 operand, rowwise or columnwise.
DLTensorWrapper wrap_scales(NVTETensor t, bool columnwise, size_t rows, size_t cols) {
const NVTEBasicTensor scales =
nvte_get_tensor_param(t, columnwise ? kNVTEColumnwiseScaleInv : kNVTERowwiseScaleInv);
size_t count = 1;
for (size_t i = 0; i < scales.shape.ndim; ++i) {
count *= scales.shape.data[i];
}
NVTE_CHECK(scales.data_ptr != nullptr && count == rows * cols / 32, "expected ", rows * cols / 32,
columnwise ? " columnwise" : " rowwise", " MXFP8 scales, got ", count);
return wrap_raw(scales.data_ptr, kNVTEFloat8E8M0, count);
}

bool is_mxfp8(NVTETensor t) {
return transformer_engine::is_mxfp8_scaling(nvte_tensor_scaling_mode(t));

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.

I think these utilities need to reside in a more common place than ep_gemm cpp file.

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.

Including check_mxfp8, check_mxfp8_dims function below

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

I moved the general helpers (wrap_*, is_mxfp8, check_mxfp8, check_vector) to common/util/tensor_utils.h. The EP-specific ones stay in ep_gemm_utils.h, and I renamed them with an ep prefix (ep_overlap_scaling_mode, check_ep_mxfp8_dims, check_ep_expert_token_offsets).

del grouped_dy
if isinstance(grouped_x, GroupedTensor):
self.update(
wgrad_input=grouped_x.columnwise_data.view(torch.float8_e4m3fn).view(

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.

Do we need these kind of complications to execute wgrad? Given that wgrad is not going to be delayed in this case. Cant we simply pass wgrad input output as arugments.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

I simplified it to a three-line callback that records the wgrad input, output and accumulate flag. I kept it so FusedMoE reuses the main_grad/accumulate logic in _compute_grad_params. Passing them directly needs a prepare/finish split of that shared function, which I'd do as a follow-up.

num_tokens = grad_result.shape[0]
grad_result, grad_result_scale, symm_input = _quantize_for_dispatch(grad_result, device)

def fp8_rows(cols):

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.

Can we use quantizer.make_empty and create normal MXFP8Tensor. If we change the tex API below to handle MXFPETensorStorage instead of data, scales being passed individually, then it would all fit nicely.

raise RuntimeError("FusedMoE: the weight-gradient GEMM function was not called.")


class _MxFp8Weight(NamedTuple):

@vthumbe1503 vthumbe1503 Nov 26, 2026 •

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.

We have MXFP8TensorStorage already for this

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

The operands are already MXFP8TensorStorages; _MxFp8WeightOperands only pairs the rowwise (forward) and columnwise (backward) ones. I renamed it and its builder to say so.

phu0ngng and others added 12 commits November 30, 2026 20:27
…) with in-call weight gradients for BF16 and MXFP8

Signed-off-by: Phuong Nguyen <phuonguyen@nvidia.com>
…les as combine chunks

Signed-off-by: Phuong Nguyen <phuonguyen@nvidia.com>
Signed-off-by: Phuong Nguyen <phuonguyen@nvidia.com>
… overlap support check internal

Signed-off-by: Phuong Nguyen <phuonguyen@nvidia.com>
…dients

Signed-off-by: Phuong Nguyen <phuonguyen@nvidia.com>
…requirements into the call docstrings

Signed-off-by: Phuong Nguyen <phuonguyen@nvidia.com>
… share the weight-gradient tile counter

Signed-off-by: Phuong Nguyen <phuonguyen@nvidia.com>
… tile and MXFP8 constants

Signed-off-by: Phuong Nguyen <phuonguyen@nvidia.com>
…ze 32 and check runtime settings at execution

Signed-off-by: Phuong Nguyen <phuonguyen@nvidia.com>
…interleave_size None cases

Signed-off-by: Phuong Nguyen <phuonguyen@nvidia.com>
…pert layout

Signed-off-by: Phuong Nguyen <phuonguyen@nvidia.com>
@phu0ngng
phu0ngng force-pushed the feat/moe-overlap-ops-main branch from a5a8c31 to 6ffa5d3 Compare December 1, 2026 04:30
Comment on lines +179 to +183
for align in 128 64; do
NVTE_EP_OVERLAP_ALIGNMENT=${align} run_pass "overlap_a${align}" 0 0 0 1 0 1
NVTE_EP_OVERLAP_ALIGNMENT=${align} run_pass "overlap_a${align}_eager" 0 1 0 1 0 1
NVTE_EP_OVERLAP_ALIGNMENT=${align} NVTE_EP_TOKENS_PER_RANK=288 \
NVTE_EP_TEST_FILTER=test_moe_overlap run_pass "overlap_a${align}_t288" 0 0 0 1 0 1

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.

P1 Overlap tests request unsupported alignments

The launcher schedules six passes with expert alignment 64 or 128, but FusedMoE now accepts only 256. With overlap enabled and working kernels, the BF16 numerical tests reach fusion and raise “the EP alignment must be one of (256,)”. The EP suite therefore fails on a working setup.

Remove these passes until the kernels support smaller alignments, or turn them into tests that expect rejection.

Comment thread docs/envvars.rst
Comment on lines +178 to +180
sequence that cannot run fused raises an error. The directory is the ``gemm/``
tree of the EPCompOverlap kernel sources (with ``blackwell/``, ``rubin/`` and
``utils/``); its modules are imported by name and their version is not checked.

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.

P2 Setup names unused kernel directory

These instructions say NVTE_MOE_OVERLAP points to an external kernel directory. The loader never reads that path; it imports from the installed cudnn.gemm.cutedsl.grouped package. A user can supply the documented directory and still fail to load the kernels.

Document the installed package requirement and describe this variable as the enable switch it currently is.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants