From 2c7b93047a4afa9f20bd0c4dfdd98248b1ca495b Mon Sep 17 00:00:00 2001 From: Phuong Nguyen Date: Mon, 23 Nov 2026 20:39:10 -0800 Subject: [PATCH 01/67] [Common][PyTorch] Add MoE EP communication/GEMM overlap ops (FusedMoE) with in-call weight gradients for BF16 and MXFP8 Signed-off-by: Phuong Nguyen --- docs/api/pytorch.rst | 11 +- docs/envvars.rst | 18 + .../pytorch/ep/bench/bench_moe_overlap.py | 269 ++++ tests/pytorch/distributed/run_ep.py | 831 +++++++++++- tests/pytorch/distributed/run_test_ep.sh | 61 +- tests/pytorch/test_ep_gemm.py | 420 ++++++ transformer_engine/common/CMakeLists.txt | 4 +- transformer_engine/common/CuTeDSL/__init__.py | 30 + .../common/CuTeDSL/ep_gemm/__init__.py | 13 + .../common/CuTeDSL/ep_gemm/_loader.py | 343 +++++ .../common/CuTeDSL/ep_gemm/combine_gemm.py | 232 ++++ .../common/CuTeDSL/ep_gemm/dispatch_gemm.py | 401 ++++++ .../common/CuTeDSL/ep_gemm/requantize.py | 331 +++++ .../common/CuTeDSL/ep_gemm/wgrad_gemm.py | 337 +++++ transformer_engine/common/CuTeDSL/utils.py | 6 + transformer_engine/common/ep/ep_api.cpp | 35 +- transformer_engine/common/ep/ep_backend.cpp | 165 ++- transformer_engine/common/ep/ep_backend.h | 45 +- transformer_engine/common/ep/ep_gemm_api.cpp | 1116 ++++++++++++++++ transformer_engine/common/ep/ep_gemm_config.h | 319 +++++ .../common/ep/ep_overlap_workspace.cu | 75 ++ .../common/ep/ep_overlap_workspace.h | 47 + .../common/ep/nccl_ep_provider.cpp | 12 + .../common/ep/nccl_ep_provider.h | 3 + .../common/include/transformer_engine/ep.h | 20 +- .../include/transformer_engine/ep_gemm.h | 246 ++++ transformer_engine/common/tvm_ffi_bridge.h | 6 + transformer_engine/common/util/cuda_runtime.h | 3 + transformer_engine/common/util/utils.cu | 51 + transformer_engine/pytorch/csrc/extensions.h | 4 +- .../pytorch/csrc/extensions/ep.cpp | 586 ++++++++- transformer_engine/pytorch/ep.py | 151 ++- transformer_engine/pytorch/ops/__init__.py | 1 + .../pytorch/ops/fused/__init__.py | 5 + .../pytorch/ops/fused/moe_overlap.py | 1138 +++++++++++++++++ transformer_engine/pytorch/ops/fuser.py | 13 +- 36 files changed, 7259 insertions(+), 89 deletions(-) create mode 100644 examples/pytorch/ep/bench/bench_moe_overlap.py create mode 100644 tests/pytorch/test_ep_gemm.py create mode 100644 transformer_engine/common/CuTeDSL/ep_gemm/__init__.py create mode 100644 transformer_engine/common/CuTeDSL/ep_gemm/_loader.py create mode 100644 transformer_engine/common/CuTeDSL/ep_gemm/combine_gemm.py create mode 100644 transformer_engine/common/CuTeDSL/ep_gemm/dispatch_gemm.py create mode 100644 transformer_engine/common/CuTeDSL/ep_gemm/requantize.py create mode 100644 transformer_engine/common/CuTeDSL/ep_gemm/wgrad_gemm.py create mode 100644 transformer_engine/common/ep/ep_gemm_api.cpp create mode 100644 transformer_engine/common/ep/ep_gemm_config.h create mode 100644 transformer_engine/common/ep/ep_overlap_workspace.cu create mode 100644 transformer_engine/common/ep/ep_overlap_workspace.h create mode 100644 transformer_engine/common/include/transformer_engine/ep_gemm.h create mode 100644 transformer_engine/pytorch/ops/fused/moe_overlap.py diff --git a/docs/api/pytorch.rst b/docs/api/pytorch.rst index e770cf24fc9..37d739a7b3a 100644 --- a/docs/api/pytorch.rst +++ b/docs/api/pytorch.rst @@ -148,13 +148,20 @@ NCCL-based dispatch and combine for experts sharded across ranks. See ``MoeDispatch`` and ``MoeCombine`` can wrap the local expert operations in a ``transformer_engine.pytorch.ops.Sequential``. They share an ``EpConfig`` and -an ``EpBuffer``; the guide shows how to connect the per-expert counts and -routing weights through the sequence's extra-tensor channels. +an ``EpBuffer``. A buffer holds the routing state of one call until its backward has run, so +several calls in flight (for example pipeline microbatches) each need their own ``EpBuffer`` and +op instance. The guide shows how to connect the per-expert counts and routing weights through the +sequence's extra-tensor channels. ``moe_overlap_supported`` tells whether such a sequence runs as +one fused op. .. autoapiclass:: transformer_engine.pytorch.ops.MoeDispatch .. autoapiclass:: transformer_engine.pytorch.ops.MoeCombine +.. autoapifunction:: transformer_engine.pytorch.ops.moe_overlap_supported + +.. autoapifunction:: transformer_engine.pytorch.ops.moe_overlap_unsupported_reason + .. autoapiclass:: transformer_engine.pytorch.ep.EpConfig .. autoapifunction:: transformer_engine.pytorch.ep.ep_bootstrap diff --git a/docs/envvars.rst b/docs/envvars.rst index aa5d011794f..93d5233dd9e 100644 --- a/docs/envvars.rst +++ b/docs/envvars.rst @@ -161,6 +161,24 @@ General ``WARN`` emits a warning explaining why CuTeDSL kernels are unavailable and falls back to CUDA kernels. ``ERROR`` raises an error and fails instead. Only effective when the CuTeDSL backend is enabled (see :envvar:`NVTE_ENABLE_CUTEDSL_BACKEND`). +.. + 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. + +.. envvar:: NVTE_MOE_OVERLAP + + :Type: ``str`` (directory) + :Default: unset (overlap off) + :Description: Directory of the CuTeDSL grouped GEMMs that overlap the NCCL EP dispatch and + combine with the expert GEMMs (``ep_gemm.h``, used by the fused + :class:`transformer_engine.pytorch.ops.MoeDispatch` expert MLP). The overlap is + off unless this is set together with ``NVTE_ENABLE_CUTEDSL_BACKEND=1``; then + ``ep_bootstrap`` defaults to 24 communication SMs unless ``max_num_sms`` is + given. If unset, the unfused ops run; if set, a dispatch, grouped MLP and combine + 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. + .. envvar:: NVTE_GROUPED_TENSOR_HANDLE_POOL_SIZE_MB :Type: ``int`` (positive integer) diff --git a/examples/pytorch/ep/bench/bench_moe_overlap.py b/examples/pytorch/ep/bench/bench_moe_overlap.py new file mode 100644 index 00000000000..bde9400fc38 --- /dev/null +++ b/examples/pytorch/ep/bench/bench_moe_overlap.py @@ -0,0 +1,269 @@ +# Copyright (c) 2022-2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# See LICENSE for license information. + +"""Timing harness for the overlapped MoE op (FusedMoE), forward and backward, in eager and +CUDA-graph modes. Launch with torchrun, one process per GPU: + + torchrun --standalone --nproc-per-node=4 bench_moe_overlap.py --precision bf16 + +The op fuses an MoE MLP (dispatch, GroupedLinear, ScaledSwiGLU, GroupedLinear, combine) so the +NCCL EP dispatch and combine overlap the expert GEMMs. Requires SM 10.0 or 10.3, an EP group +within one NVLink domain, NVTE_ENABLE_CUTEDSL_BACKEND=1 and NVTE_MOE_OVERLAP. The defaults match +the DeepSeek-V3 EP4 shape. +""" + +import argparse +import os +import statistics + +import torch +import torch.distributed as dist + +import transformer_engine.pytorch as te +from transformer_engine.pytorch import ops as te_ops +from transformer_engine.common.recipe import MXFP8BlockScaling +from transformer_engine.pytorch.ep import EpBuffer, EpConfig, ep_bootstrap, ep_finalize + + +def _parse_args(): + p = argparse.ArgumentParser(description="FusedMoE forward+backward perf bench") + p.add_argument("--precision", choices=("bf16", "mxfp8"), default="bf16") + p.add_argument("--mode", choices=("eager", "graph", "both"), default="both") + p.add_argument("--tokens-per-rank", type=int, default=4096) + p.add_argument("--hidden-dim", type=int, default=7168) + p.add_argument("--ffn", type=int, default=2048) + p.add_argument("--top-k", type=int, default=8) + p.add_argument("--num-local-experts", type=int, default=64) + p.add_argument("--alignment", type=int, default=256) + p.add_argument("--recv-capacity-per-rank", type=int, default=131072) + p.add_argument( + "--comm-sms", + default="32,32,32,32", + help="SMs the EP keeps for dispatch_fwd,combine_fwd,dispatch_bwd,combine_bwd", + ) + p.add_argument("--iters", type=int, default=50) + p.add_argument("--warmup", type=int, default=10) + args = p.parse_args() + if args.iters < 1 or args.warmup < 0: + p.error("--iters must be positive and --warmup nonnegative") + return args + + +def _build(args): + recipe = MXFP8BlockScaling() if args.precision == "mxfp8" else None + dist.init_process_group(backend="nccl") + torch.cuda.set_device(int(os.environ["LOCAL_RANK"])) + device = torch.device("cuda", torch.cuda.current_device()) + ep_size = dist.get_world_size() + num_experts = args.num_local_experts * ep_size + ep_group = dist.new_group(ranks=list(range(ep_size)), backend="nccl") + + sms = [int(s) for s in args.comm_sms.split(",")] + ep_bootstrap( + ep_group, + num_experts=num_experts, + max_tokens_per_rank=args.tokens_per_rank, + hidden_dim=args.hidden_dim, + num_topk=args.top_k, + recv_capacity_per_rank=args.recv_capacity_per_rank, + max_num_sms=max(sms), + dispatch_fwd_num_sms=sms[0], + combine_fwd_num_sms=sms[1], + dispatch_bwd_num_sms=sms[2], + combine_bwd_num_sms=sms[3], + ) + + config = EpConfig( + top_k=args.top_k, + max_tokens_per_rank=args.tokens_per_rank, + hidden_dim=args.hidden_dim, + num_local_experts=args.num_local_experts, + recv_capacity_per_rank=args.recv_capacity_per_rank, + ep_group=ep_group, + alignment=args.alignment, + dispatch_fwd_quant_recipe=recipe, + combine_bwd_quant_recipe=recipe, + ) + buffer = EpBuffer( + top_k=config.top_k, + max_tokens_per_rank=config.max_tokens_per_rank, + hidden_dim=config.hidden_dim, + num_local_experts=config.num_local_experts, + recv_capacity_per_rank=config.recv_capacity_per_rank, + alignment=config.alignment, + payload_dtype=config.payload_dtype, + dispatch_fwd_quant_recipe=config.dispatch_fwd_quant_recipe, + combine_bwd_quant_recipe=config.combine_bwd_quant_recipe, + ) + return recipe, num_experts, device, te_ops.Sequential(*_moe_ops(args, config, buffer, device)) + + +def _moe_ops(args, config, buffer, device): + """MoeDispatch, GroupedLinear, ScaledSwiGLU, GroupedLinear and MoeCombine with the routing + channels connected: the dispatch forwards the expert counts and routing weights to the GEMMs + and the activation, so the sequence fuses into one FusedMoE.""" + gen = torch.Generator(device=device).manual_seed(5) + linear_kwargs = { + "bias": False, + "dtype": torch.bfloat16, + "single_grouped_weight": True, + "split_alignment": args.alignment, + } + dispatch = te_ops.MoeDispatch(config, buffer) + fc1 = te_ops.GroupedLinear( + args.num_local_experts, args.hidden_dim, 2 * args.ffn, device=device, **linear_kwargs + ) + fc2 = te_ops.GroupedLinear( + args.num_local_experts, args.ffn, args.hidden_dim, device=device, **linear_kwargs + ) + act = te_ops.ScaledSwiGLU(glu_interleave_size=32) + combine = te_ops.MoeCombine(config, buffer) + with torch.no_grad(): + for fc in (fc1, fc2): + for w in fc.parameters(): + w.copy_((torch.rand(w.shape, device=device, generator=gen) - 0.5) * 0.1) + dispatch.set_extra_output_channel(0, "tokens_per_expert", output_to_caller=False) + dispatch.set_extra_output_channel(1, "routing_weights", output_to_caller=False) + fc1.set_extra_input_channel(0, "tokens_per_expert") + act.set_extra_input_channel(0, "routing_weights") + fc2.set_extra_input_channel(0, "tokens_per_expert") + return dispatch, fc1, act, fc2, combine + + +def _inputs(args, num_experts, device): + gen = torch.Generator(device=device).manual_seed(2026 + dist.get_rank()) + tokens = ( + torch.randn(args.tokens_per_rank, args.hidden_dim, generator=gen, device=device) * 0.25 + ).to(torch.bfloat16) + logits = torch.randn(args.tokens_per_rank, num_experts, generator=gen, device=device) + topk_logits, topk_idx = torch.topk(logits, args.top_k, dim=-1) + topk_w = torch.softmax(topk_logits, dim=-1) + grad_out = torch.randn(tokens.shape, generator=gen, device=device).to(torch.bfloat16) + return topk_idx, tokens.requires_grad_(True), topk_w.requires_grad_(True), grad_out + + +def _autocast(recipe): + return te.autocast(enabled=recipe is not None, recipe=recipe) + + +def _assert_fused(args, recipe, num_experts, device, model): + from transformer_engine.pytorch.ops.fused import moe_overlap + + topk_idx, x, topk_w, _ = _inputs(args, num_experts, device) + with _autocast(recipe): + model(x, topk_idx, topk_w, topk_idx) + torch.cuda.synchronize() + fused = any( + isinstance(op, moe_overlap.FusedMoE) + for group in model._module_groups + for op, _ in getattr(group, "_forward_ops", []) + ) + if not fused: + raise RuntimeError("FusedMoE did not fuse; the measurement would be the unfused path") + + +def _run_eager(args, recipe, num_experts, device, model): + topk_idx, x, topk_w, grad_out = _inputs(args, num_experts, device) + for _ in range(args.warmup): + x.grad = topk_w.grad = None + with _autocast(recipe): + y = model(x, topk_idx, topk_w, topk_idx) + y.backward(grad_out) + torch.cuda.synchronize() + + fwd_t, bwd_t, tot_t = [], [], [] + ev = [torch.cuda.Event(enable_timing=True) for _ in range(3)] + for _ in range(args.iters): + x.grad = topk_w.grad = None + ev[0].record() + with _autocast(recipe): + y = model(x, topk_idx, topk_w, topk_idx) + ev[1].record() + y.backward(grad_out) + ev[2].record() + torch.cuda.synchronize() + fwd_t.append(ev[0].elapsed_time(ev[1])) + bwd_t.append(ev[1].elapsed_time(ev[2])) + tot_t.append(ev[0].elapsed_time(ev[2])) + return statistics.median(fwd_t), statistics.median(bwd_t), statistics.median(tot_t) + + +def _run_graph(args, recipe, num_experts, device, model): + topk_idx, x, topk_w, grad_out = _inputs(args, num_experts, device) + # Warm up on a side stream before capture. + s = torch.cuda.Stream() + s.wait_stream(torch.cuda.current_stream()) + with torch.cuda.stream(s): + for _ in range(args.warmup): + x.grad = topk_w.grad = None + with _autocast(recipe): + y = model(x, topk_idx, topk_w, topk_idx) + y.backward(grad_out) + torch.cuda.current_stream().wait_stream(s) + torch.cuda.synchronize() + + # Two graphs timed with events outside replay: full fwd+bwd, and fwd-only. bwd = total - fwd. + # Events recorded inside a captured graph give cudaErrorInvalidValue on elapsed_time. + g_full = torch.cuda.CUDAGraph() + x.grad = topk_w.grad = None + with torch.cuda.graph(g_full): + with _autocast(recipe): + y = model(x, topk_idx, topk_w, topk_idx) + y.backward(grad_out) + g_fwd = torch.cuda.CUDAGraph() + with torch.cuda.graph(g_fwd): + with _autocast(recipe): + model(x, topk_idx, topk_w, topk_idx) + torch.cuda.synchronize() + + def _time(graph): + ev = [torch.cuda.Event(enable_timing=True) for _ in range(2)] + ts = [] + for _ in range(args.iters): + ev[0].record() + graph.replay() + ev[1].record() + torch.cuda.synchronize() + ts.append(ev[0].elapsed_time(ev[1])) + return statistics.median(ts) + + tot = _time(g_full) + fwd = _time(g_fwd) + return fwd, tot - fwd, tot + + +def main(): + """Build the FusedMoE sequence and report its forward/backward timings.""" + args = _parse_args() + recipe, num_experts, device, model = _build(args) + is_rank0 = dist.get_rank() == 0 + _assert_fused(args, recipe, num_experts, device, model) + if is_rank0: + print( + f"\n=== FusedMoE fwd+bwd bench [{args.precision}] T/rank={args.tokens_per_rank} " + f"H={args.hidden_dim} FFN={args.ffn} top_k={args.top_k} E={num_experts} " + f"SMs={args.comm_sms} ===", + flush=True, + ) + + if args.mode in ("eager", "both"): + fwd, bwd, tot = _run_eager(args, recipe, num_experts, device, model) + if is_rank0: + print(f"EAGER fwd {fwd:.3f} ms | bwd {bwd:.3f} ms | fwd+bwd {tot:.3f} ms", flush=True) + + if args.mode in ("graph", "both"): + fwd, bwd, tot = _run_graph(args, recipe, num_experts, device, model) + if is_rank0: + print( + f"GRAPH fwd {fwd:.3f} ms | bwd {bwd:.3f} ms (total - fwd) | fwd+bwd {tot:.3f} ms", + flush=True, + ) + + dist.barrier() + ep_finalize() + dist.destroy_process_group() + + +if __name__ == "__main__": + main() diff --git a/tests/pytorch/distributed/run_ep.py b/tests/pytorch/distributed/run_ep.py index 310d9a29c4a..b2ec1199238 100644 --- a/tests/pytorch/distributed/run_ep.py +++ b/tests/pytorch/distributed/run_ep.py @@ -3,11 +3,14 @@ # See LICENSE for license information. """Multi-process PyTorch EP tests, launched via torchrun (one process per GPU).""" -from contextlib import nullcontext from dataclasses import replace +import contextlib +from contextlib import nullcontext +import itertools import os import sys import unittest +from unittest import mock import numpy as np import torch @@ -41,10 +44,25 @@ # Fused prepare+dispatch (caller-supplied recv buffers) is opt-in on the C++ side; the tests # that exercise it only run when the same env var is set so they match the active dispatch path. FUSED_COUNT = os.environ.get("NVTE_EP_FUSED_PREPARE_DISPATCH", "0") == "1" +# Overlapped MoE ops (ep_gemm.h): only the tests marked _overlap_test run, with NVTE_EP_MXFP8_PASS. +OVERLAP = os.environ.get("NVTE_EP_OVERLAP", "0") == "1" +if not OVERLAP: + # The other passes keep the MoE ops unfused, which the fuser rejects while the overlap is on. + os.environ.pop("NVTE_MOE_OVERLAP", None) +# Per-expert alignment of the overlap tests: 256, 128 or 64 (BF16 only; MXFP8 cases skip). +OVERLAP_ALIGNMENT = int(os.environ.get("NVTE_EP_OVERLAP_ALIGNMENT", "256")) +# Below alignment 256 the unfused ops do not fuse into the grouped MLP, so single results of the +# fused op may round to other values than theirs. +UNFUSED_MLP_REFERENCE = OVERLAP_ALIGNMENT % 256 != 0 # Must come after the transformer_engine import so libtransformer_engine.so is loaded. import transformer_engine_torch as tex # noqa: F401 +# SM 10.7 has no BF16 grouped MLP fusion, so there the BF16 unfused ops never fuse into it. +UNFUSED_BF16_MLP_REFERENCE = UNFUSED_MLP_REFERENCE or ( + torch.cuda.is_available() and torch.cuda.get_device_capability() == (10, 7) +) + NUM_LOCAL_EXPERTS = 2 # MXFP8 dispatch needs HIDDEN_DIM % 512 == 0 and TOKENS_PER_RANK % 32 == 0. Defaults # satisfy both so the MXFP8 tests run by default; override via NVTE_EP_HIDDEN_DIM / @@ -52,6 +70,12 @@ HIDDEN_DIM = int(os.environ.get("NVTE_EP_HIDDEN_DIM", "512")) TOP_K = 2 TOKENS_PER_RANK = int(os.environ.get("NVTE_EP_TOKENS_PER_RANK", "32")) +OVERLAP_COMM_SMS = 16 # SMs the dispatch keeps; the overlapped GEMM runs on the rest +# SMs of the forward dispatch, forward combine, backward dispatch and backward combine +# (NVTE_EP_COMM_SMS=12,20,24,16); 0 inherits as ep_bootstrap documents. +COMM_SMS = tuple(int(sms) for sms in os.environ.get("NVTE_EP_COMM_SMS", "0,0,0,0").split(",")) +if len(COMM_SMS) != 4: + raise ValueError(f"NVTE_EP_COMM_SMS needs 4 comma-separated counts, got {COMM_SMS}") def _zero_copy_test_include(fn): @@ -84,6 +108,26 @@ def _mxfp8_align_test(fn): return fn +def _overlap_test(fn): + """Mark a test of the overlapped MoE ops; it runs only in the overlap pass.""" + fn._overlap_test = True + return fn + + +def _mxfp8_overlap_min_alignment() -> int: + """Smallest expert alignment of FusedMoE under MXFP8: SM 10.7 has no MXFP8 tail tiles.""" + return 256 if torch.cuda.get_device_capability() == (10, 7) else 128 + + +def _mxfp8_overlap() -> bool: + """Whether the overlap tests run their MXFP8 cases: shapes and alignment FusedMoE takes.""" + return ( + HIDDEN_DIM % 512 == 0 + and TOKENS_PER_RANK % 32 == 0 + and OVERLAP_ALIGNMENT >= _mxfp8_overlap_min_alignment() + ) + + class _StageToSymm(torch.autograd.Function): """Identity op that stages ``src`` into a symm-mem buffer; grad passes through. Lets a test feed a symm-mem-backed, autograd-tracked tensor into ep_combine. @@ -128,6 +172,22 @@ def _build_ep_group(): return dist.new_group(ranks=ranks, backend="nccl") +def _gate_up_rows(t): + """Per-expert FC1 rows [experts, 2 * ffn, ...] of the 32-wide interleaved GLU layout in the + gate-then-up layout (glu_interleave_size=None).""" + return t.reshape(t.shape[0], -1, 2, 32, *t.shape[2:]).transpose(1, 2).reshape(t.shape) + + +def _assert_close_in_norm(actual, expected, rtol): + """``actual`` is within ``rtol`` of ``expected`` in norm, per expert of a grouped weight.""" + rows = expected.shape[0] if expected.dim() == 3 else 1 + actual = actual.float().reshape(rows, -1) + expected = expected.float().reshape(rows, -1) + err, ref = (actual - expected).norm(dim=1), expected.norm(dim=1) + if not bool((err <= rtol * ref).all()): + raise AssertionError(f"error norms {err.tolist()} exceed {rtol} x {ref.tolist()}") + + def _make_identity_inputs(rank, ep_size, device="cuda"): """Per-rank identity routing + uniform weights so combine matches tokens.""" T = TOKENS_PER_RANK @@ -218,8 +278,9 @@ def _make_cfg() -> _Cfg: cfg.recv_capacity_per_rank = NUM_LOCAL_EXPERTS * max(T * cfg.ep_size * TOP_K, 16) * overconc * 2 if OVERFLOW: # Undersize recv capacity so identity routing overflows a rank's budget; - # HT requires capacity >= max_tokens_per_rank. - cfg.recv_capacity_per_rank = TOKENS_PER_RANK + # HT requires capacity >= max_tokens_per_rank. Each expert pads to 256 rows, so one slab + # fits and the second overflows. + cfg.recv_capacity_per_rank = 256 if OVERLAP else TOKENS_PER_RANK cfg.device = torch.device("cuda", torch.cuda.current_device()) return cfg @@ -229,38 +290,57 @@ class _EpTestCase(unittest.TestCase): cfg: _Cfg ep_group: dist.ProcessGroup + # Why this pass's EP group could not be created, if so; every test class then skips. + bootstrap_skip = None @classmethod def setUpClass(cls): # unittest invokes this fixture for each concrete subclass, but EP is process-global. if hasattr(_EpTestCase, "cfg"): + if _EpTestCase.bootstrap_skip: + raise unittest.SkipTest(_EpTestCase.bootstrap_skip) return if _device_sm() < 90: raise unittest.SkipTest(f"NCCL EP requires SM>=90 (got SM{_device_sm()})") _EpTestCase.cfg = _make_cfg() _EpTestCase.ep_group = _build_ep_group() - ep_bootstrap( - cls.ep_group, - num_experts=cls.cfg.num_experts, - max_tokens_per_rank=TOKENS_PER_RANK, - hidden_dim=HIDDEN_DIM, - num_topk=TOP_K, - # Omit recv_capacity_per_rank to select eager mode. - recv_capacity_per_rank=None if EAGER else cls.cfg.recv_capacity_per_rank, - zero_copy=ZERO_COPY, - drop_on_overflow=OVERFLOW, - ) + try: + ep_bootstrap( + cls.ep_group, + num_experts=cls.cfg.num_experts, + max_tokens_per_rank=TOKENS_PER_RANK, + hidden_dim=HIDDEN_DIM, + num_topk=TOP_K, + # Omit recv_capacity_per_rank to select eager mode. + recv_capacity_per_rank=None if EAGER else cls.cfg.recv_capacity_per_rank, + zero_copy=ZERO_COPY, + drop_on_overflow=OVERFLOW, + max_num_sms=OVERLAP_COMM_SMS if OVERLAP else 0, + dispatch_fwd_num_sms=COMM_SMS[0], + combine_fwd_num_sms=COMM_SMS[1], + dispatch_bwd_num_sms=COMM_SMS[2], + combine_bwd_num_sms=COMM_SMS[3], + ) + except RuntimeError as err: + # A backward count other than the forward one needs NCCL EP backward budgets. + if "built against an NCCL EP with dispatch_bwd_num_sms" not in str(err): + raise + _EpTestCase.bootstrap_skip = "NCCL EP has no backward SM budgets" + raise unittest.SkipTest(_EpTestCase.bootstrap_skip) from err def setUp(self): # alignment=256 MXFP8 tests run only in the dedicated MXFP8 pass; everything else skips # there (and the MXFP8 tests skip outside it) since the backend pins one alignment/process. is_mxfp8_align = getattr(getattr(self, self._testMethodName), "_mxfp8_align_test", False) + is_overlap = getattr(getattr(self, self._testMethodName), "_overlap_test", False) + if OVERLAP != is_overlap: + self.skipTest("overlapped MoE tests run only in the overlap pass") if MXFP8_PASS and not is_mxfp8_align: self.skipTest("only alignment=256 MXFP8 tests run in the MXFP8 pass") if not MXFP8_PASS and is_mxfp8_align: self.skipTest("alignment=256 MXFP8 tests run in the dedicated MXFP8 pass") - # MXFP8 quantization requires Blackwell (SM 10.0) or newer. - if is_mxfp8_align and torch.cuda.get_device_capability() < (10, 0): + # MXFP8 quantization requires Blackwell (SM 10.0) or newer; the BF16 overlap tests do not. + if is_mxfp8_align and not is_overlap and torch.cuda.get_device_capability() < (10, 0): self.skipTest("MXFP8 EP tests require Blackwell (SM 10.0) or newer") # Only the zero-copy-capable tests run in the zero-copy pass. if ZERO_COPY and not getattr( @@ -299,6 +379,14 @@ def _make_config( combine_bwd_quant_recipe=combine_bwd_quant_recipe, ) + def _overlap_config(self, recipe=None): + """EpConfig of the overlapped MoE tests; ``recipe`` is the EP transport recipe.""" + return self._make_config( + alignment=OVERLAP_ALIGNMENT, + dispatch_fwd_quant_recipe=recipe, + combine_bwd_quant_recipe=recipe, + ) + def _make_buffer_from_config(self, config): """Build the NCCL EP buffer that a config describes, recipes included.""" return EpBuffer( @@ -334,6 +422,8 @@ def _require_mxfp8_shapes(self): "MXFP8 needs HIDDEN_DIM % 512 == 0 and TOKENS_PER_RANK % 32 == 0 " "(set NVTE_EP_HIDDEN_DIM / NVTE_EP_TOKENS_PER_RANK)" ) + if OVERLAP and OVERLAP_ALIGNMENT < _mxfp8_overlap_min_alignment(): + self.skipTest("FusedMoE runs MXFP8 with alignment 128 or 256 (256 on SM 10.7)") class TestEP(_EpTestCase): @@ -377,6 +467,52 @@ def _weighted(recv_tokens, recv_w): mask = (recv_w != 0).to(torch.float32).unsqueeze(-1) return (recv_tokens.float() * recv_w.unsqueeze(-1).float() * mask).to(recv_tokens.dtype) + def _moe_ops( + self, + config, + buffer, + glu_interleave_size=32, + accumulate_into_main_grad=False, + *, + ffn=HIDDEN_DIM, + activation=None, + fc_kwargs=({}, {}), + **linear_kwargs, + ): + """MoeDispatch, GroupedLinear, ``activation`` (default ScaledSwiGLU), GroupedLinear and + MoeCombine over ``buffer``, with the routing channels connected and fixed weights (BF16 + unless ``linear_kwargs`` change the GroupedLinear settings; ``fc_kwargs`` adds settings + of the first and of the second GroupedLinear).""" + device = self.cfg.device + gen = torch.Generator(device=device).manual_seed(5) + linear_kwargs = { + "bias": False, + "dtype": torch.bfloat16, + "single_grouped_weight": True, + "split_alignment": OVERLAP_ALIGNMENT, + "accumulate_into_main_grad": accumulate_into_main_grad, + **linear_kwargs, + } + dispatch = te_ops.MoeDispatch(config, buffer) + fc1 = te_ops.GroupedLinear( + NUM_LOCAL_EXPERTS, HIDDEN_DIM, 2 * ffn, device=device, **linear_kwargs, **fc_kwargs[0] + ) + fc2 = te_ops.GroupedLinear( + NUM_LOCAL_EXPERTS, ffn, HIDDEN_DIM, device=device, **linear_kwargs, **fc_kwargs[1] + ) + act = activation or te_ops.ScaledSwiGLU(glu_interleave_size=glu_interleave_size) + combine = te_ops.MoeCombine(config, buffer) + with torch.no_grad(): + for fc in (fc1, fc2): + for w in fc.parameters(): + w.copy_((torch.rand(w.shape, device=device, generator=gen) - 0.5) * 0.1) + dispatch.set_extra_output_channel(0, "tokens_per_expert", output_to_caller=False) + dispatch.set_extra_output_channel(1, "routing_weights", output_to_caller=False) + fc1.set_extra_input_channel(0, "tokens_per_expert") + act.set_extra_input_channel(0, "routing_weights") + fc2.set_extra_input_channel(0, "tokens_per_expert") + return dispatch, fc1, act, fc2, combine + def _moe_step(self, buffer, topk_idx, tokens, w): recv_t, recv_w_out, _tc = ep_dispatch(buffer, tokens, topk_idx, w) expert_out = self._weighted(recv_t, recv_w_out) @@ -491,6 +627,645 @@ def test_primitive_dispatch_combine_identity(self): torch.cuda.synchronize() torch.testing.assert_close(result.float(), tokens.float(), atol=5e-2, rtol=5e-2) + # Overlapped MoE + + @_eager_test_include + @_overflow_test_include + @_mxfp8_align_test + @_overlap_test + def test_moe_overlap_op(self): + """The fused MoE op matches the same ops run unfused: output and every + gradient, also when tokens overflow the capacity and are dropped. Skipped where the + overlapped GEMMs cannot run.""" + self._check_moe_overlap_op(None) + + @_eager_test_include + @_overflow_test_include + @_mxfp8_align_test + @_overlap_test + def test_moe_overlap_op_mxfp8(self): + """Under MXFP8 with MXFP8 EP transport the fused op matches the unfused ops, with weight + scales that differ across blocks in both directions. The fused op dispatches x and dY in + place from the EP dispatch window. An unset config transport runs MXFP8.""" + self._require_mxfp8_shapes() + recipe = MXFP8BlockScaling() + with mock.patch.object( + tex, "ep_dispatch_gemm_fwd", wraps=tex.ep_dispatch_gemm_fwd + ) as fwd, mock.patch.object( + tex, "ep_combine_gemm_bwd", wraps=tex.ep_combine_gemm_bwd + ) as bwd: + self._check_moe_overlap_op(recipe, recipe) + for call in fwd.call_args_list + bwd.call_args_list: + self.assertEqual(call.kwargs["symm_input"], tex.ep_zero_copy_supported()) + # MXFP8 FusedMoE quantizes the EP transport itself, so an unset config transport fuses. + config = self._overlap_config() + model = te_ops.Sequential(*self._moe_ops(config, self._make_buffer_from_config(config))) + topk_idx, tokens, w = _make_identity_inputs(self.cfg.rank, self.cfg.ep_size) + with te.autocast(recipe=recipe): + model(tokens, topk_idx, w, topk_idx) + self.assertTrue(self._moe_overlap_selected(model)) + + @_eager_test_include + @_overflow_test_include + @_mxfp8_align_test + @_overlap_test + def test_moe_overlap_op_variants(self): + """The fused op matches the unfused ops, in BF16 and, where the overlap tests run MXFP8, in + MXFP8, also: without input and routing-weight gradients (no dispatch backward), with + MXFP8 weight parameters, with accumulate_into_main_grad and both GLU layouts, with an FFN + size other than the hidden size, and with FP32 weight parameters cast by + ``Module.to(torch.bfloat16)``.""" + # (recipe, _check_moe_overlap_op settings) + cases = [ + (None, {"input_grad": False}), + # ffn != hidden, so a transposed weight layout cannot pass. + (None, {"ffn": HIDDEN_DIM // 2}), + (None, {"main_grad": True, "glu_interleave_size": None}), + (None, {"params_to_bf16": True}), + (None, {"params_to_bf16": True, "glu_interleave_size": None}), + (None, {"params_to_bf16": True, "main_grad": True}), + (None, {"frozen": (1,)}), + (None, {"frozen": (3,)}), + (None, {"frozen": (1, 3), "main_grad": True}), + ] + if _mxfp8_overlap(): + recipe = MXFP8BlockScaling() + cases += [ + (recipe, {"input_grad": False}), + (recipe, {"params_to_bf16": True}), + (recipe, {"quantized_weights": True}), + (recipe, {"frozen": (1,)}), + (recipe, {"frozen": (3,)}), + (recipe, {"frozen": (1, 3), "glu_interleave_size": None}), + ] + cases += [ + (recipe, {"quantized_weights": q, "glu_interleave_size": glu, "main_grad": True}) + for q, glu in itertools.product((False, True), (32, None)) + ] + for recipe, settings in cases: + with self.subTest(recipe=recipe, **settings): + self._check_moe_overlap_op(recipe, recipe, **settings) + + def _assert_glu_none_matches(self, got, want, got_grads, want_grads): + """The outputs and FC1, FC2 weight gradients of the fused op with glu_interleave_size=None + match those of the 32-wide layer, the FC1 rows mapped between the layouts.""" + for g, w in zip(got[:2], want[:2]): + self.assertTrue(torch.equal(g, w)) + if OVERLAP_ALIGNMENT >= 256 and HIDDEN_DIM <= 512: + self.assertTrue(torch.equal(got[2], want[2])) + else: + # The routing-weight gradient adds more than two column tiles, or tail tiles, in + # arrival order, which changes the FP32 sums by up to about 1e-6 of the largest one. + torch.testing.assert_close( + got[2], want[2], rtol=1.3e-6, atol=1e-6 * float(want[2].abs().amax()) + ) + fc1_shape = (NUM_LOCAL_EXPERTS, -1, HIDDEN_DIM) + # The rows of an expert may arrive in another order, which changes the FP32 wgrad sums by + # up to about 1e-6 of the expert's largest one, then by a BF16 rounding. + for g, w in ( + (got_grads[0].reshape(fc1_shape), _gate_up_rows(want_grads[0].reshape(fc1_shape))), + (got_grads[1], want_grads[1]), + ): + for ge, we in zip(g.reshape(NUM_LOCAL_EXPERTS, -1), w.reshape(NUM_LOCAL_EXPERTS, -1)): + torch.testing.assert_close(ge, we, rtol=1e-2, atol=1e-6 * float(we.abs().amax())) + + def _check_moe_overlap_op( + self, recipe, transport=None, quantized_weights=False, glu_interleave_size=32, + main_grad=False, input_grad=True, params_to_bf16=False, ffn=HIDDEN_DIM, frozen=(), + ): # fmt: skip + from transformer_engine.pytorch.ops.fused import moe_overlap + + device = self.cfg.device + config = self._overlap_config(transport) + # Where FusedMoE cannot run, the overlap raises, so there is nothing to compare. + if not moe_overlap.FusedMoE.is_supported() or ( + recipe is not None + and not (moe_overlap.GroupedMLP_CuTeGEMMGLU.is_supported() and transport is not None) + ): + self.skipTest("FusedMoE is not supported here") + # SM 10.7 runs the MXFP8 weight gradients into main_grad only above 256 receive rows. + if ( + main_grad + and recipe is not None + and torch.cuda.get_device_capability() == (10, 7) + and config.recv_capacity_per_rank == 256 + ): + self.skipTest( + "SM 10.7 MXFP8 main_grad weight gradients need more than 256 receive rows" + ) + with te.quantized_model_init(enabled=quantized_weights, recipe=recipe): + buffer = self._make_buffer_from_config(config) + ops = self._moe_ops( + config, + buffer, + glu_interleave_size, + main_grad, + ffn=ffn, + dtype=torch.float32 if params_to_bf16 else torch.bfloat16, + ) + gen = torch.Generator(device=device).manual_seed(6) + if recipe is not None: + # Power-of-two factors per row and column give every scale block its own exponent. + with torch.no_grad(): + for fc in (ops[1], ops[3]): + for w in fc.parameters(): + rows = torch.randint( + -3, 4, (*w.shape[:-1], 1), device=device, generator=gen + ) + cols = torch.randint(-3, 4, w.shape[-1:], device=device, generator=gen) + values = torch.rand(w.shape, device=device, generator=gen) - 0.5 + w.copy_(values * 0.1 * torch.exp2((rows + cols).float())) + if glu_interleave_size is None: + # The layer of glu_interleave_size=32 with its FC1 rows mapped to gate then up. + with torch.no_grad(): + ops[1].weight.copy_(_gate_up_rows(ops[1].weight * 1)) + if params_to_bf16: + for op in ops: + op.to(torch.bfloat16) + # The weights of the GroupedLinear ops at these positions (1: FC1, 3: FC2) are frozen. + for idx in frozen: + ops[idx].weight.requires_grad_(False) + topk_idx, tokens, w = _make_identity_inputs(self.cfg.rank, self.cfg.ep_size) + grad_out = torch.randn(tokens.shape, device=device, generator=gen).to(torch.bfloat16) + + def run(fused): + if not fused and params_to_bf16: + # The BF16 grouped MLP fusion reads the weight data as stored, so this reference + # runs the GroupedLinear ops, which cast it, and not FusedMoE. + ctx = contextlib.ExitStack() + ctx.enter_context( + mock.patch.object( + moe_overlap.GroupedMLP_CuTeGEMMGLUBf16, "is_supported", return_value=False + ) + ) + ctx.enter_context(self._moe_fusion(False)) + elif not fused: + ctx = self._moe_fusion(False) + elif input_grad: + ctx = contextlib.nullcontext() + else: + ctx = mock.patch.object( + moe_overlap.tex, "ep_dispatch_gemm_bwd", side_effect=AssertionError("called") + ) + if fused: + # The fused op uses its own counts and recv total, not the reference's. + buffer.tokens_per_expert_i32.fill_(-1) + buffer.total_recv_tokens_i32.fill_(-1) + buffer.total_recv_tokens.fill_(-1) + # Paged stashing pages the tensors that carry a token count. + stashable = [] + num_tokens = [] + + def pack(tensor): + if hasattr(tensor, "grouped_tensor_num_tokens"): + stashable.append((tensor.dtype, tensor.shape, tensor.nbytes)) + n = tensor.grouped_tensor_num_tokens + num_tokens.append(n.clone() if torch.is_tensor(n) else n) + return tensor + + with ctx, te.autocast( + enabled=recipe is not None, recipe=recipe + ), torch.autograd.graph.saved_tensors_hooks(pack, lambda tensor: tensor): + model = te_ops.Sequential(*ops) + x = tokens.clone().requires_grad_(input_grad) + topk_w = w.clone().requires_grad_(input_grad) + for p in model.parameters(): + p.grad = None + if main_grad: + p.main_grad = torch.full(p.shape, 0.5, dtype=torch.float32, device=device) + p.grad_added_to_main_grad = False + y = model(x, topk_idx, topk_w, topk_idx) + y.backward(grad_out) + torch.cuda.synchronize() + fused_ops = self._moe_overlap_selected(model) + trained = [p for p in model.parameters() if p.requires_grad] + if main_grad: + self.assertTrue(all(p.grad_added_to_main_grad for p in trained)) + grads = [(p.main_grad if main_grad else p.grad).clone() for p in trained] + counts = [int(n) for n in num_tokens] + return y.detach(), x.grad, topk_w.grad, grads, bool(fused_ops), stashable, counts + + ref = run(False) + out = run(True) + self.assertFalse(ref[4]) + self.assertTrue(out[4], "fusion selection") + # The launcher requires this line from every rank of an overlap pass. + print(f"OVERLAP_EXECUTED rank={self.cfg.rank}", flush=True) + supported = te_ops.moe_overlap_supported( + config, ffn, params_dtype=torch.bfloat16, + glu_interleave_size=glu_interleave_size, single_grouped_weight=True, recipe=recipe, + primary_weights_in_fp8=quantized_weights, + ) # fmt: skip + self.assertTrue(supported, "moe_overlap_supported matches the fuser") + # Row tensors saved: recv tokens (and their scales), the FC1 output and the routing + # weights, plus the SwiGLU output in BF16. A frozen weight leaves out the input of its + # weight gradient: the recv tokens and scales for FC1, the SwiGLU output (BF16) for FC2. + fc1_inputs, fc2_inputs = (2, 0) if recipe is not None else (1, 1) + stashed = 4 - (fc1_inputs if 1 in frozen else 0) - (fc2_inputs if 3 in frozen else 0) + self.assertEqual(len(out[5]), stashed, "the fused op saves the stashable tensors") + # Their token count is the number of received rows kept. + kept = int(buffer.tokens_per_expert_i32.sum()) + self.assertEqual(out[6], [kept] * stashed, "stashed token counts") + # The fused op publishes that kept total to the buffer counter paged stashing reads. + self.assertEqual(int(buffer.total_recv_tokens.item()), kept, "published recv total") + if recipe is not None: + # The FC2 dgrad recomputes the SwiGLU output, so no [rows, ffn] tensor is saved: + # the recv tokens and scales, the FC1 output and the recv routing weights. + rows = next(shape[0] for dtype, shape, _ in out[5] if dtype == torch.float32) + saved = sum(nbytes for _, _, nbytes in out[5]) + ffn = ops[3].in_features + recv_bytes = 0 if 1 in frozen else HIDDEN_DIM + HIDDEN_DIM // 32 + self.assertEqual(saved, rows * (recv_bytes + 2 * ffn * 2 + 4), "saved bytes") + # Where the unfused ops compute the SwiGLU output in their own kernel, single elements may + # round to another value, so those results are compared in norm. The unfused MXFP8 ops also + # round the FC2 dgrad and the SwiGLU backward output to BF16 before quantizing them, so + # outputs and weight gradients may differ by up to the E4M3 epsilon. + norm_rtol = 2e-2 if recipe is None else 1 / 32 + unfused_reference = glu_interleave_size is None or ( + UNFUSED_BF16_MLP_REFERENCE if recipe is None else UNFUSED_MLP_REFERENCE + ) + outputs_in_norm = unfused_reference or params_to_bf16 + outputs_rtol = 1 / 16 if recipe is not None and unfused_reference else norm_rtol + if not input_grad: + self.assertTrue(all(g is None for g in out[1:3] + ref[1:3])) + for got, want in zip(out[: 3 if input_grad else 1], ref[:3]): + if outputs_in_norm: + _assert_close_in_norm(got, want, rtol=outputs_rtol) + else: + torch.testing.assert_close(got, want, rtol=2e-2, atol=2e-2) + for g, g_ref in zip(out[3], ref[3]): + if ( + recipe is None + and glu_interleave_size is not None + and not (UNFUSED_BF16_MLP_REFERENCE or params_to_bf16) + ): + torch.testing.assert_close(g, g_ref, rtol=2e-2, atol=2e-2) + else: + _assert_close_in_norm(g, g_ref, rtol=outputs_rtol) + + @_eager_test_include + @_mxfp8_align_test + @_overlap_test + def test_moe_overlap_cpu_offload(self): + """Under CPU offload the tensors the fused op saves come back bitwise, and its output and + gradients match those without offload.""" + from transformer_engine.pytorch import cpu_offload + + self._require_moe_overlap() + tokens, topk_idx, w, grad_out = self._moe_calls(1)[0] + for recipe in [None] + ([MXFP8BlockScaling()] if _mxfp8_overlap() else []): + config = self._overlap_config(recipe) + ops = self._moe_ops(config, self._make_buffer_from_config(config)) + results = [] + for offload in (False, True): + saved = [] + for p in ops[1].parameters(): + p.grad = None + for p in ops[3].parameters(): + p.grad = None + with te.autocast(enabled=recipe is not None, recipe=recipe): + model = te_ops.Sequential(*ops) + x = tokens.clone().requires_grad_(True) + topk_w = w.clone().requires_grad_(True) + if offload: + ctx, sync, controller = cpu_offload.get_cpu_offload_context( + enabled=True, model_layers=1, manual_synchronization=True + ) + sync_state = ctx.offload_synchronizer + push, pop = sync_state.push_tensor, sync_state.pop_tensor + + def push_tensor(tensor, push=push): + saved.append([tensor.detach().reshape(-1).view(torch.uint8).cpu()]) + return len(saved) - 1, push(tensor) + + def pop_tensor(packed, pop=pop): + tensor = pop(packed[1]) + saved[packed[0]].append(tensor.detach().reshape(-1).view(torch.uint8)) + return tensor + + with mock.patch.object( + sync_state, "push_tensor", push_tensor + ), mock.patch.object(sync_state, "pop_tensor", pop_tensor): + with ctx: + y = model(x, topk_idx, topk_w, topk_idx) + y = sync(y) + controller.start_offload_layer(0) + controller.release_activation_forward_gpu_memory(0) + controller.start_reload_layer(0) + else: + y = model(x, topk_idx, topk_w, topk_idx) + y.backward(grad_out) + torch.cuda.synchronize() + self.assertTrue(self._moe_overlap_selected(model)) + self.assertEqual(bool(saved), offload, "offloaded tensors") + for before, after in saved: + self.assertTrue(torch.equal(before, after.cpu()), "a saved tensor changed") + grads = [p.grad.clone() for p in model.parameters()] + results.append([y.detach(), x.grad, topk_w.grad, *grads]) + with self.subTest(recipe=recipe): + for i, (got, want) in enumerate(zip(*results)): + if recipe is not None and i >= 3: + _assert_close_in_norm(got, want, rtol=1 / 32) + else: + torch.testing.assert_close(got, want, rtol=2e-2, atol=2e-2) + + def _require_moe_overlap(self): + from transformer_engine.pytorch.ops.fused import moe_overlap + + if not moe_overlap.FusedMoE.is_supported(): + self.skipTest( + "FusedMoE needs SM 10.0, 10.3 or 10.7, NVTE_ENABLE_CUTEDSL_BACKEND=1," + " NVTE_MOE_OVERLAP and the BF16 cuDNN grouped GEMM kernels" + ) + + @staticmethod + def _moe_fusion(fused): + """Context in which the fuser may select FusedMoE, or keeps the MoE ops unfused.""" + from transformer_engine.pytorch.ops.fused import moe_overlap + + if fused: + return contextlib.nullcontext() + return mock.patch.object(moe_overlap, "_moe_overlap_available", return_value=False) + + @staticmethod + def _moe_overlap_selected(model): + """The FusedMoE ops of the plan ``model`` ran last.""" + from transformer_engine.pytorch.ops.fused import moe_overlap + + return [ + op + for group in model._module_groups + for op, _ in getattr(group, "_forward_ops", []) + if isinstance(op, moe_overlap.FusedMoE) + ] + + def _moe_calls(self, num_calls): + """(tokens, topk_idx, topk_weights, grad_output) of calls that each route differently.""" + gen = torch.Generator(device=self.cfg.device).manual_seed(8) + topk_idx, tokens, w = _make_identity_inputs(self.cfg.rank, self.cfg.ep_size) + return [ + ( + tokens.roll(i, 0), + (topk_idx + i) % self.cfg.num_experts, + w, + torch.randn(tokens.shape, device=self.cfg.device, generator=gen).to(torch.bfloat16), + ) + for i in range(num_calls) + ] + + @staticmethod + def _moe_call(model, tokens, topk_idx, w, grad, *, tokens_grad=True, weights_grad=True): + """Forward, then backward when ``grad`` is given: (output, tokens grad, topk_weights + grad). Parameter gradients accumulate on the parameters.""" + x = tokens.clone().requires_grad_(tokens_grad) + topk_w = w.clone().requires_grad_(weights_grad) + y = model(x, topk_idx, topk_w, topk_idx) + if grad is not None: + y.backward(grad) + return y.detach(), x.grad, topk_w.grad + + @staticmethod + def _param_grads(model): + return [None if p.grad is None else p.grad.clone() for p in model.parameters()] + + def _assert_moe_close( + self, got, ref, in_norm=UNFUSED_BF16_MLP_REFERENCE, outputs_in_norm=True, rtol=2e-2 + ): + """Fused and unfused MoE results, nested in lists, agree within ``rtol``; with in_norm the + grouped weight gradients in norm, and with outputs_in_norm as well the outputs and input + gradients.""" + if isinstance(ref, (list, tuple)): + self.assertEqual(len(got), len(ref)) + for g, r in zip(got, ref): + self._assert_moe_close(g, r, in_norm, outputs_in_norm, rtol) + elif ref is None: + self.assertIsNone(got) + elif in_norm and (outputs_in_norm or ref.dim() == 3): + _assert_close_in_norm(got, ref, rtol=rtol) + else: + torch.testing.assert_close(got, ref, rtol=rtol, atol=rtol) + + @_mxfp8_align_test + @_overlap_test + def test_moe_overlap_wgrad(self): + """With accumulate_into_main_grad, the fused op writes the weight gradients of two calls + into an FP32 or BF16 main_grad, accumulated or overwritten, as the unfused ops do.""" + self._require_moe_overlap() + config = self._overlap_config() + calls = self._moe_calls(2) + ops = self._moe_ops( + config, self._make_buffer_from_config(config), accumulate_into_main_grad=True + ) + weights = (ops[1].weight, ops[3].weight) + for dtype, overwrite in itertools.product((torch.float32, torch.bfloat16), (False, True)): + results = [] + for fused in (False, True): + for p in weights: + p.grad = None + p.main_grad = torch.full(p.size(), 0.5, dtype=dtype, device=self.cfg.device) + p.overwrite_main_grad = overwrite + p.grad_added_to_main_grad = False + with self._moe_fusion(fused): + model = te_ops.Sequential(*ops) + outs = [self._moe_call(model, *call) for call in calls] + torch.cuda.synchronize() + self.assertEqual(bool(self._moe_overlap_selected(model)), fused) + for p in weights: + self.assertTrue(p.grad_added_to_main_grad) + results.append((outs, [p.main_grad.clone() for p in weights])) + with self.subTest(dtype=dtype, overwrite=overwrite): + self._assert_moe_close(results[1], results[0]) + + @_eager_test_include + @_mxfp8_align_test + @_overlap_test + def test_moe_overlap_rank_without_tokens(self): + """Every token picks the first expert of ranks 0 and 1, so the other ranks and the other + experts of ranks 0 and 1 receive no tokens. The fused op matches the unfused ops, and + the weight gradients of the experts without tokens are zero. The fused op with + glu_interleave_size=None and the FC1 rows mapped matches it.""" + self._require_moe_overlap() + if self.cfg.ep_size < 3: + self.skipTest("needs a rank that receives no tokens") + config = self._overlap_config() + ops = self._moe_ops(config, self._make_buffer_from_config(config)) + tokens, _, w, grad = self._moe_calls(1)[0] + topk_idx = torch.tensor([0, NUM_LOCAL_EXPERTS], device=self.cfg.device).repeat( + TOKENS_PER_RANK, 1 + ) + results = [] + for fused in (False, True): + for p in ops[1].parameters(): + p.grad = None + for p in ops[3].parameters(): + p.grad = None + with self._moe_fusion(fused): + model = te_ops.Sequential(*ops) + out = self._moe_call(model, tokens, topk_idx, w, grad) + torch.cuda.synchronize() + self.assertEqual(bool(self._moe_overlap_selected(model)), fused) + results.append((out, self._param_grads(model))) + self._assert_moe_close(results[1], results[0]) + has_tokens = self.cfg.rank < 2 + for g in results[1][1]: + per_expert = g.view(NUM_LOCAL_EXPERTS, -1) + self.assertEqual(int(per_expert[int(has_tokens) :].count_nonzero()), 0) + if has_tokens: + self.assertGreater(int(per_expert[0].count_nonzero()), 0) + + ops_none = self._moe_ops(config, self._make_buffer_from_config(config), None) + shape = (NUM_LOCAL_EXPERTS, ops[1].out_features, ops[1].in_features) + with torch.no_grad(): + ops_none[1].weight.rowwise_data.view(shape).copy_( + _gate_up_rows(ops[1].weight.rowwise_data.view(shape)) + ) + model = te_ops.Sequential(*ops_none) + out = self._moe_call(model, tokens, topk_idx, w, grad) + torch.cuda.synchronize() + self.assertTrue(self._moe_overlap_selected(model)) + self._assert_glu_none_matches(out, results[1][0], self._param_grads(model), results[1][1]) + + @_mxfp8_align_test + @_overlap_test + def test_moe_overlap_cuda_graph(self): + """The fused forward and backward, captured in a CUDA graph after warmup and replayed with + new routing, tokens, topk_weights and output gradient, match the unfused ops; in BF16 and, + where the overlap tests run MXFP8, under MXFP8 transport (its shared dispatch window, + requantization and weight gradients captured and replayed).""" + self._require_moe_overlap() + for recipe in [None] + ([MXFP8BlockScaling()] if _mxfp8_overlap() else []): + with self.subTest(recipe=recipe): + self._run_moe_overlap_cuda_graph(recipe) + + def _run_moe_overlap_cuda_graph(self, recipe): + """Capture and replay the fused MoE under ``recipe`` (None for BF16) and match the unfused + ops run under the same autocast.""" + if recipe is not None: + self._require_mxfp8_shapes() + device = self.cfg.device + config = self._overlap_config(recipe) + ops = self._moe_ops(config, self._make_buffer_from_config(config)) + ref_ops = self._moe_ops(config, self._make_buffer_from_config(config)) + if recipe is not None: + # Power-of-two row and column factors give every scale block its own exponent. Both + # models share the weights. + gen = torch.Generator(device=device).manual_seed(6) + with torch.no_grad(): + for fc, ref_fc in ((ops[1], ref_ops[1]), (ops[3], ref_ops[3])): + for w_fused, w_ref in zip(fc.parameters(), ref_fc.parameters()): + shape = w_fused.shape + rows = torch.randint(-3, 4, (*shape[:-1], 1), device=device, generator=gen) + cols = torch.randint(-3, 4, shape[-1:], device=device, generator=gen) + values = torch.rand(shape, device=device, generator=gen) - 0.5 + w_fused.copy_(values * 0.1 * torch.exp2((rows + cols).float())) + w_ref.copy_(w_fused) + gen = torch.Generator(device=device).manual_seed(9) + random_idx, random_tokens, random_w = _make_moe_inputs(self.cfg.rank, self.cfg.ep_size) + replays = [ + ( + random_tokens, + random_idx, + random_w, + torch.randn(random_tokens.shape, device=device, generator=gen).to(torch.bfloat16), + ), + self._moe_calls(1)[0], + ] + # Static inputs, holding the captured call's values first. + tokens, topk_idx, w, grad = (t.clone() for t in self._moe_calls(2)[1]) + x = tokens.requires_grad_(True) + topk_w = w.requires_grad_(True) + model = te_ops.Sequential(*ops) + params = list(model.parameters()) + out = {} + + def step(): + for t in (x, topk_w, *params): + t.grad = None + with te.autocast(enabled=recipe is not None, recipe=recipe): + out["y"] = model(x, topk_idx, topk_w, topk_idx) + out["y"].backward(grad) + + graph = self._capture(step) + self.assertTrue(self._moe_overlap_selected(model)) + results = [] + for call in replays: + with torch.no_grad(): + for static, value in zip((x, topk_idx, topk_w, grad), call): + static.copy_(value) + graph.replay() + got = ( + (out["y"].detach().clone(), x.grad.clone(), topk_w.grad.clone()), + [p.grad.clone() for p in params], + ) + ref_model = te_ops.Sequential(*ref_ops) + for p in ref_model.parameters(): + p.grad = None + with self._moe_fusion(False), te.autocast(enabled=recipe is not None, recipe=recipe): + ref = (self._moe_call(ref_model, *call), self._param_grads(ref_model)) + torch.cuda.synchronize() + results.append((got, ref)) + # Compare once every rank has run every replay, so a mismatch on one rank leaves no rank + # waiting in a later replay. + for got, ref in results: + if recipe is None: + self._assert_moe_close(got, ref) + else: + # The unfused MXFP8 ops round the SwiGLU output and requantize to E4M3, so compare + # outputs and gradients in norm at the E4M3 tolerance. + self._assert_moe_close(got, ref, in_norm=True, outputs_in_norm=True, rtol=1 / 16) + + @_mxfp8_align_test + @_overlap_test + def test_moe_overlap_instances(self): + """Weights created in inference mode, which have no version counter, run in the fused op + with the FC1 rows reordered at each call. Two FusedMoE instances, each with its own + EpBuffer, interleave safely: the second instance's forward and backward between the first + instance's forward and backward leave the first instance's output and gradients identical + to running it alone. One buffer and op instance per outstanding call.""" + self._require_moe_overlap() + config = self._overlap_config() + with torch.inference_mode(): + ops = self._moe_ops(config, self._make_buffer_from_config(config), None) + model = te_ops.Sequential(*ops) + topk_idx, tokens, w = _make_identity_inputs(self.cfg.rank, self.cfg.ep_size) + model(tokens, topk_idx, w, topk_idx) + torch.cuda.synchronize() + self.assertTrue(self._moe_overlap_selected(model)) + + # Separate instances and buffers; _moe_ops seeds identical weights. + model_a = te_ops.Sequential(*self._moe_ops(config, self._make_buffer_from_config(config))) + model_b = te_ops.Sequential(*self._moe_ops(config, self._make_buffer_from_config(config))) + call_a, call_b = self._moe_calls(2) + + def forward(model, call): + for p in model.parameters(): + p.grad = None + x = call[0].clone().requires_grad_(True) + topk_w = call[2].clone().requires_grad_(True) + return x, topk_w, model(x, call[1], topk_w, call[1]) + + def backward(model, x, topk_w, y, grad): + y.backward(grad) + torch.cuda.synchronize() + return [y.detach(), x.grad, topk_w.grad] + self._param_grads(model) + + # Each call run alone, as the serial reference. + xa, wa, ya = forward(model_a, call_a) + alone_a = backward(model_a, xa, wa, ya, call_a[3]) + self.assertTrue(self._moe_overlap_selected(model_a)) + xb, wb, yb = forward(model_b, call_b) + alone_b = backward(model_b, xb, wb, yb, call_b[3]) + self.assertTrue(self._moe_overlap_selected(model_b)) + + # Interleaved: the second instance's whole call lands between the first's forward and + # backward; separate buffers keep each call's routing state intact. + xa, wa, ya = forward(model_a, call_a) + xb, wb, yb = forward(model_b, call_b) + inter_b = backward(model_b, xb, wb, yb, call_b[3]) + inter_a = backward(model_a, xa, wa, ya, call_a[3]) + self._assert_moe_close(inter_a, alone_a, UNFUSED_MLP_REFERENCE, outputs_in_norm=False) + self._assert_moe_close(inter_b, alone_b, UNFUSED_MLP_REFERENCE, outputs_in_norm=False) + # Autograd @_zero_copy_test_include @@ -1252,6 +2027,30 @@ def _run_dispatch_combine_identity(self, *, mxfp8): torch.testing.assert_close(output, tokens, atol=5e-2, rtol=5e-2) self.assertEqual(tokens_per_expert.data_ptr(), buffer.tokens_per_expert.data_ptr()) + @_eager_test_include + @_mxfp8_align_test + @_overlap_test + def test_unfused_ops_on_overlap_group(self): + """On an overlap-pass group, MoeDispatch and MoeCombine run unfused and form an identity, + forward and backward.""" + config = self._overlap_config() + buffer = self._make_buffer_from_config(config) + dispatch = te_ops.MoeDispatch(config, buffer) + combine = te_ops.MoeCombine(config, buffer) + topk_idx, tokens, topk_weights = _make_identity_inputs(self.cfg.rank, self.cfg.ep_size) + x = tokens.clone().requires_grad_(True) + w = topk_weights.clone().requires_grad_(True) + recv_tokens, _tokens_per_expert, recv_weights = dispatch(x, topk_idx, w) + output = combine(recv_tokens * recv_weights.unsqueeze(-1).to(torch.bfloat16), topk_idx) + gen = torch.Generator(device=self.cfg.device).manual_seed(8) + grad_out = torch.randn(tokens.shape, device=self.cfg.device, generator=gen) + output.backward(grad_out.to(torch.bfloat16)) + torch.cuda.synchronize() + torch.testing.assert_close(output, tokens, atol=5e-2, rtol=5e-2) + torch.testing.assert_close(x.grad.float(), grad_out, atol=5e-2, rtol=5e-2) + grad_w_ref = (tokens.float() * grad_out).sum(-1, keepdim=True).expand_as(w) + torch.testing.assert_close(w.grad.float(), grad_w_ref, atol=5e-1, rtol=5e-2) + @_eager_test_include def test_dispatch_combine_identity_bf16(self): """MoeDispatch and MoeCombine basic ops form an identity in BF16.""" diff --git a/tests/pytorch/distributed/run_test_ep.sh b/tests/pytorch/distributed/run_test_ep.sh index a23809ad108..b8a5bc86128 100755 --- a/tests/pytorch/distributed/run_test_ep.sh +++ b/tests/pytorch/distributed/run_test_ep.sh @@ -49,12 +49,16 @@ run_pass() { local overflow="${4:-0}" local mxfp8="${5:-0}" local fused="${6:-0}" + local overlap="${7:-0}" local log="stdout_ep_${label}.txt" - echo "=== Running ${SCRIPT} [${label}] on ${NUM_RANKS} GPUs (timeout=${TEST_TIMEOUT_S}s) ===" + # The overlap passes compile CuTeDSL GEMMs on first use and need a longer timeout. + local timeout_s="${TEST_TIMEOUT_S}" + if [ "${overlap}" = "1" ] && [ "${timeout_s}" -lt 600 ]; then timeout_s=600; fi + echo "=== Running ${SCRIPT} [${label}] on ${NUM_RANKS} GPUs (timeout=${timeout_s}s) ===" # setsid + kill-after so SIGKILL takes down the whole process group, not just torchrun. NVTE_EP_ZERO_COPY="${zc}" NVTE_EP_EAGER="${eager}" NVTE_EP_OVERFLOW="${overflow}" \ - NVTE_EP_MXFP8_PASS="${mxfp8}" NVTE_EP_FUSED_PREPARE_DISPATCH="${fused}" \ - setsid timeout --foreground --kill-after=10 --signal=TERM "${TEST_TIMEOUT_S}" \ + NVTE_EP_MXFP8_PASS="${mxfp8}" NVTE_EP_FUSED_PREPARE_DISPATCH="${fused}" NVTE_EP_OVERLAP="${overlap}" \ + setsid timeout --foreground --kill-after=10 --signal=TERM "${timeout_s}" \ torchrun --standalone --nnodes=1 --nproc-per-node="${NUM_RANKS}" \ "${SCRIPT}" 2>&1 | tee "${log}" local rc=${PIPESTATUS[0]} @@ -68,6 +72,20 @@ run_pass() { echo "[${label}] ERROR: no test summary — likely hang or early crash" RET=1 fi + # An overlap pass in which a rank never ran the fused ops covers nothing: tests that skip, or + # that fall back to the unfused ops, do not report. Every rank reports from a numerical test. + if [ "${overlap}" = "1" ]; then + local executed + executed=$(grep -oE "OVERLAP_EXECUTED rank=[0-9]+" "${log}" | sort -u | wc -l) + # A pass skipped for lack of backward SM budgets in NCCL EP executed nothing, by design. + if grep -q "NCCL EP has no backward SM budgets" "${log}"; then + echo "[${label}] SKIPPED: NCCL EP has no backward SM budgets" + elif [ "${executed}" -lt "${NUM_RANKS}" ]; then + echo "[${label}] ERROR: the fused overlap ops ran on ${executed} of ${NUM_RANKS} ranks;" \ + "set NVTE_ENABLE_CUTEDSL_BACKEND=1 and NVTE_MOE_OVERLAP" + RET=1 + fi + fi if [ -z "${KEEP_EP_LOGS:-}" ]; then rm -f "${log}"; fi } @@ -109,4 +127,41 @@ run_pass "fused" 0 0 0 0 1 run_pass "fused_overflow" 0 0 1 0 1 run_pass "fused_mxfp8" 0 0 0 1 1 +# Overlapped MoE ops (ep_gemm.h, te.ops FusedMoE): alignment 256, capacity and eager IO. Run only +# when the overlap is available (NVTE_ENABLE_CUTEDSL_BACKEND=1, NVTE_MOE_OVERLAP and SM 10.x). +PROBE_ERR=$(mktemp) +OVERLAP_AVAILABLE=$(python3 -c \ + "import transformer_engine.pytorch.ep as ep; print(int(ep._moe_overlap_available()))" 2>"${PROBE_ERR}") +if [ $? -ne 0 ]; then + cat "${PROBE_ERR}" + OVERLAP_AVAILABLE=0 + # A failed probe is not "unsupported": when the overlap was requested it is a failure. + if [ -n "${NVTE_MOE_OVERLAP:-}" ]; then + echo "ERROR: the overlap availability probe failed with NVTE_MOE_OVERLAP set" + RET=1 + fi +fi +rm -f "${PROBE_ERR}" +if [ "${OVERLAP_AVAILABLE}" != "1" ]; then + echo "Overlapped MoE ops unavailable (needs NVTE_ENABLE_CUTEDSL_BACKEND=1, NVTE_MOE_OVERLAP, SM 10.x); SKIPPING overlap passes." +else + run_pass "overlap" 0 0 0 1 0 1 + run_pass "overlap_eager" 0 1 0 1 0 1 + run_pass "overlap_overflow" 0 0 1 1 0 1 + # Per-direction SM counts (dispatch fwd, combine fwd, dispatch bwd, combine bwd). The backward + # split skips when Transformer Engine was built against an NCCL EP without backward SM budgets. + NVTE_EP_COMM_SMS=12,20,0,0 run_pass "overlap_split" 0 0 0 1 0 1 + NVTE_EP_COMM_SMS=12,20,24,16 run_pass "overlap_split_bwd" 0 0 0 1 0 1 + # A hidden size that 1024 does not divide: the combine waits on whole rows. + NVTE_EP_HIDDEN_DIM=1536 run_pass "overlap_h1536" 0 0 0 1 0 1 + # Expert alignments below 256 (MXFP8 cases skip at 64): an expert's last GEMM tile holds fewer + # rows. With 288 tokens per rank each expert also fills a whole tile; only the fused op tests run. + 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 + done +fi + exit $RET diff --git a/tests/pytorch/test_ep_gemm.py b/tests/pytorch/test_ep_gemm.py new file mode 100644 index 00000000000..b5d6b257bff --- /dev/null +++ b/tests/pytorch/test_ep_gemm.py @@ -0,0 +1,420 @@ +# Copyright (c) 2022-2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# See LICENSE for license information. + +"""Signal-aware grouped GEMM that follows the EP dispatch, loaded through TVM-FFI.""" + +# pylint: disable=wrong-import-position + +import ctypes +import os + +import pytest +import torch + +# The optional CuTeDSL dependencies are imported only when the overlap is requested, where a +# missing one fails the module. +if not os.environ.get("NVTE_MOE_OVERLAP"): + pytest.skip("NVTE_MOE_OVERLAP is not set", allow_module_level=True) + +import tvm_ffi + +from transformer_engine.common.CuTeDSL.ep_gemm import ( + combine_gemm, + dispatch_gemm, + requantize, + wgrad_gemm, +) + +pytestmark = [ + pytest.mark.skipif( + not torch.cuda.is_available() + or torch.cuda.get_device_capability() not in ((10, 0), (10, 3), (10, 7)), + reason="the kernels need SM 10.0, 10.3 or 10.7", + ), +] + +TILE = dispatch_gemm.ROWS_PER_TILE +# SM 10.7 has no MXFP8 tail tiles. +MXFP8_TAILS = torch.cuda.is_available() and torch.cuda.get_device_capability() != (10, 7) + + +def _unit_e8m0(count, device): + """``count`` unit E8M0 scales (127), which read the same in any scale layout.""" + return torch.full((count,), 127, dtype=torch.uint8, device=device).view(torch.float8_e8m0fnu) + + +def _run_gemm(rows_per_expert, rows_alignment, mxfp8, tail_clusters, device_layout): + """Launch the forward GEMM with every row tile ready, and with ``tail_clusters`` a second + launch behind it on the same workspace; return (a, b, alpha, prob, c, d, claims) with MXFP8 + operands at unit scales in float32, the MXFP8 ``d`` dequantized and the final claim counter. + ``device_layout``: the row ends follow expert 0's offset, as the dispatch writes them.""" + device = torch.device("cuda") + hidden, n, experts = 1024, 1024, len(rows_per_expert) + rows = sum(rows_per_expert) + TILE # spare tile: the capacity exceeds the rows in use + scaling_mode = dispatch_gemm.MXFP8_1D_SCALING if mxfp8 else dispatch_gemm.DELAYED_TENSOR_SCALING + cfg = dispatch_gemm.DispatchGemmConfig( + rows, + hidden, + n, + experts, + num_clusters=8, + scaling_mode=scaling_mode, + rows_alignment=rows_alignment, + device_layout=device_layout, + ) + launches = [] + for num_clusters in (cfg.num_clusters, tail_clusters): + if num_clusters == 0: + continue + name = ( + f"test_ep_gemm_{rows}_{rows_alignment}_{int(mxfp8)}_{num_clusters}" + f"_{int(device_layout)}" + ) + assert dispatch_gemm.get_ep_dispatch_gemm_function( + name, + rows, + hidden, + n, + experts, + num_clusters, + False, + mxfp8, + rows_alignment, + device_layout, + ) + launches.append(tvm_ffi.get_global_func(name)) + + gen = torch.Generator(device=device).manual_seed(0) + dtype = torch.float8_e4m3fn if mxfp8 else torch.bfloat16 + a = torch.rand(rows, hidden, device=device, generator=gen).to(dtype) + b = (torch.rand(experts, n, hidden, device=device, generator=gen) * 2 * hidden**-0.5).to(dtype) + # Powers of two: alpha and prob cost no tolerance. + alpha = torch.pow(2.0, (torch.arange(experts, device=device) % 5 - 2).float()) + prob = torch.pow(2.0, (torch.arange(rows, device=device) % 3 - 1).float()) + ends = torch.tensor(rows_per_expert, device=device).cumsum(0).to(torch.int32) + if device_layout: + # Offsets then the total: expert 0's offset is the word before the 16-byte aligned ends. + layout = torch.zeros(4 + experts, dtype=torch.int32, device=device) + layout[4:] = ends + ends = layout[4:] + d_cols = n // 2 + c = torch.zeros(rows, n, dtype=torch.bfloat16, device=device) + d = torch.zeros(rows, d_cols, dtype=dtype, device=device) + ws_bytes = dispatch_gemm.workspace_layout(cfg)[0] + workspace = torch.zeros(ws_bytes, dtype=torch.uint8, device=device) + _, counter_offset, signal_offset, _ = dispatch_gemm.workspace_layout(cfg) + words = workspace.view(torch.int32) + # Slot s is ready once signal[s] == s. + words[signal_offset // 4 :][: cfg.signal_capacity] = torch.arange( + cfg.signal_capacity, dtype=torch.int32, device=device + ) + counter = words[counter_offset // 4] + stream = ctypes.c_void_p(torch.cuda.current_stream().cuda_stream) + if not mxfp8: + for gemm in launches: + gemm(a, b, c, d, ends, alpha, prob, workspace, stream) + torch.cuda.synchronize() + return a.float(), b.float(), alpha, prob, c, d.float(), counter.item() + + # The forward takes no prob. + sfd = torch.zeros(rows * d_cols // 32, dtype=torch.uint8, device=device) + norm_const = torch.ones(1, dtype=torch.float32, device=device) + for gemm in launches: + gemm( + a, b, _unit_e8m0(experts * n * hidden // 32, device), + _unit_e8m0(rows * hidden // 32, device), c, d, + sfd.view(torch.float8_e8m0fnu), ends, alpha, norm_const, workspace, stream, + ) # fmt: skip + torch.cuda.synchronize() + # GEMM-swizzled scales of [rows, d_cols]: 128 x 4 atoms, rows 32 apart interleaved. + scale_cols = d_cols // 32 + scales = sfd.view(rows // 128, scale_cols // 4, 32, 4, 4).permute(0, 3, 2, 1, 4) + scales = torch.pow(2.0, scales.reshape(rows, scale_cols).float() - 127) + d_float = d.float() * scales.repeat_interleave(32, dim=1) + return a.float(), b.float(), alpha, torch.ones_like(prob), c, d_float, counter.item() + + +@pytest.mark.parametrize( + "rows_alignment,mxfp8,rows_per_expert", + [ + (TILE, False, [2 * TILE, TILE, 0, 3 * TILE]), + (TILE, True, [2 * TILE, TILE, 0, 3 * TILE]), + # Tail tiles: an expert of only a tail, a tail after full tiles, an empty expert. + (128, False, [128, 2 * TILE + 128, 0, TILE]), + pytest.param( + 128, + True, + [128, 2 * TILE + 128, 0, TILE], + marks=pytest.mark.skipif(not MXFP8_TAILS, reason="no MXFP8 tail tiles on SM 10.7"), + ), + # Every tail height, and the tails that run inside the last full tile of their expert. + (64, False, [64, 128, 192, 2 * TILE + 64, 2 * TILE + 128, 0, TILE]), + ], +) +@pytest.mark.parametrize("tail_clusters", [0, 4]) +@pytest.mark.parametrize("device_layout", [False, True]) +def test_dispatch_gemm_matches_reference( + rows_alignment, mxfp8, rows_per_expert, tail_clusters, device_layout +): + """Grouped GEMM over padded slabs matches a float32 reference, also with experts padded to + fewer rows than a tile, with a tail launch sharing the tiles and with the dispatch-written + layout; rows past the last expert stay 0.""" + a, b, alpha, prob, c, d, claims = _run_gemm( + rows_per_expert, rows_alignment, mxfp8, tail_clusters, device_layout + ) + if tail_clusters: + # The tail's schedulers claimed from the counter they share with the base's. + assert claims > _run_gemm(rows_per_expert, rows_alignment, mxfp8, 0, device_layout)[-1] + used = sum(rows_per_expert) + ref_c = torch.zeros(a.shape[0], b.shape[1], dtype=torch.float32, device=a.device) + start = 0 + for e, count in enumerate(rows_per_expert): + ref_c[start : start + count] = a[start : start + count] @ b[e].t() * alpha[e] + start += count + col = torch.arange(b.shape[1] // 2, device=a.device) + gate = 64 * (col // 32) + col % 32 + ref_d = ref_c[:, gate + 32] * torch.nn.functional.silu(ref_c[:, gate]) * prob[:, None] + # BF16 outputs round once; the MXFP8 d may round to either neighbor of its E4M3 value. + for got, ref, tol in ((c, ref_c, 2.0**-8), (d, ref_d, 2.0**-3 if mxfp8 else 2.0**-8)): + err = (got[:used].float() - ref[:used]).abs() / ref[:used].abs().clamp_min(1e-6) + assert err.max() <= tol + assert torch.count_nonzero(got[used:]) == 0 + + +def _run_combine(rows_per_expert, rows_alignment, mxfp8, backward): + """Launch the combine GEMM over padded slabs and return (a, b, alpha, prob, d, used) with + MXFP8 operands at unit scales in float32. The forward weight is [E, n, k], backward [E, k, n]; + ``d`` [rows, n] is BF16 in both recipes. Rows past the last expert stay 0.""" + device = torch.device("cuda") + k, n, experts = 1024, 1024, len(rows_per_expert) + rows = sum(rows_per_expert) + TILE # spare tile: the capacity exceeds the rows in use + name = f"test_ep_combine_gemm_{rows}_{rows_alignment}_{int(mxfp8)}_{int(backward)}" + assert combine_gemm.get_ep_combine_gemm_function( + name, rows, k, n, experts, 8, 0, False, backward, mxfp8, rows_alignment + ) + gemm = tvm_ffi.get_global_func(name) + + gen = torch.Generator(device=device).manual_seed(0) + dtype = torch.float8_e4m3fn if mxfp8 else torch.bfloat16 + w_shape = (experts, k, n) if backward else (experts, n, k) + a = torch.rand(rows, k, device=device, generator=gen).to(dtype) + b = (torch.rand(w_shape, device=device, generator=gen) * 2 * k**-0.5).to(dtype) + # Powers of two: alpha and prob cost no tolerance. + alpha = torch.pow(2.0, (torch.arange(experts, device=device) % 5 - 2).float()) + prob = torch.pow(2.0, (torch.arange(rows, device=device) % 3 - 1).float()) + ends = torch.tensor(rows_per_expert, device=device).cumsum(0).to(torch.int32) + d = torch.zeros(rows, n, dtype=torch.bfloat16, device=device) + ws_bytes = combine_gemm.get_ep_combine_gemm_workspace_layout( + rows, k, n, experts, 8, 0, False, backward, mxfp8, rows_alignment + )[0] + workspace = torch.zeros(ws_bytes, dtype=torch.uint8, device=device) + stream = ctypes.c_void_p(torch.cuda.current_stream().cuda_stream) + if mxfp8: + gemm( + a, b, _unit_e8m0(experts * n * k // 32, device), + _unit_e8m0(rows * k // 32, device), d, ends, alpha, prob, workspace, stream, + ) # fmt: skip + else: + gemm(a, b, d, ends, alpha, prob, workspace, stream) + torch.cuda.synchronize() + return a.float(), b.float(), alpha, prob, d, sum(rows_per_expert) + + +@pytest.mark.parametrize( + "backward,mxfp8,rows_alignment,rows_per_expert", + [ + (False, False, TILE, [2 * TILE, TILE, 0, 3 * TILE]), + (False, True, TILE, [2 * TILE, TILE, 0, 3 * TILE]), + (True, False, TILE, [2 * TILE, TILE, 0, 3 * TILE]), + (True, True, TILE, [2 * TILE, TILE, 0, 3 * TILE]), + # Tail tiles: an expert of only a tail, a tail after full tiles, an empty expert. + (False, False, 128, [128, 2 * TILE + 128, 0, TILE]), + ], +) +def test_combine_gemm_matches_reference(backward, mxfp8, rows_alignment, rows_per_expert): + """Grouped combine GEMM over padded slabs, per expert ``d = (a @ weight) * alpha * prob``, + matches a float32 reference; rows past the last expert stay 0.""" + a, b, alpha, prob, d, used = _run_combine(rows_per_expert, rows_alignment, mxfp8, backward) + ref = torch.zeros(a.shape[0], b.shape[2] if backward else b.shape[1], device=a.device) + start = 0 + for e, count in enumerate(rows_per_expert): + sl = slice(start, start + count) + weight = b[e] if backward else b[e].t() + ref[sl] = a[sl] @ weight * alpha[e] * prob[sl, None] + start += count + # BF16 output rounds once, whether the operands are BF16 or MXFP8. + err = (d[:used].float() - ref[:used]).abs() / ref[:used].abs().clamp_min(1e-6) + assert err.max() <= 2.0**-8 + assert torch.count_nonzero(d[used:]) == 0 + + +def _run_wgrad(rows_per_expert, mxfp8, fp32_out, accumulate): + """Launch the weight gradient over padded slabs and return (grad, x, init, weight_grad) with + MXFP8 operands at unit scales in float32. ``weight_grad[e] = grad[e]^T @ x[e]``, written or + added to ``init``.""" + device = torch.device("cuda") + m, n, experts = 256, 512, len(rows_per_expert) + rows = sum(rows_per_expert) + TILE # spare tile: the capacity exceeds the rows in use + routed = max(sum(rows_per_expert) // experts, 1) + args = (rows, m, n, experts, 8, fp32_out, accumulate, False, 0, mxfp8, False, TILE, routed) + name = f"test_ep_wgrad_{rows}_{int(mxfp8)}_{int(fp32_out)}_{int(accumulate)}" + assert wgrad_gemm.get_ep_wgrad_function(name, *args) + launches = [tvm_ffi.get_global_func(name)] + if mxfp8 and wgrad_gemm.get_ep_wgrad_reads_descriptors(*args): + # A descriptors-only launch writes the per-expert descriptors the GEMM launch reads. + desc = (rows, m, n, experts, 1, fp32_out, accumulate, False, 0, mxfp8, True, TILE, routed) + assert wgrad_gemm.get_ep_wgrad_function(name + "_desc", *desc) + launches.insert(0, tvm_ffi.get_global_func(name + "_desc")) + + gen = torch.Generator(device=device).manual_seed(0) + dtype = torch.float8_e4m3fn if mxfp8 else torch.bfloat16 + # Powers of two keep every product and sum exact in float32; signs on grad add cancellation. + signs = 1 - 2 * torch.randint(0, 2, (rows, m), device=device, generator=gen) + grad = ( + signs + * torch.pow(2.0, -torch.randint(0, 2, (rows, m), device=device, generator=gen).float()) + ).to(dtype) + x = torch.pow(2.0, -torch.randint(0, 2, (rows, n), device=device, generator=gen).float()).to( + dtype + ) + out_dtype = torch.float32 if fp32_out else torch.bfloat16 + init = torch.pow(2.0, (torch.arange(experts * m * n, device=device) % 3 - 1).float()).reshape( + experts, m, n + ) + weight_grad = (init if accumulate else torch.zeros_like(init)).to(out_dtype, copy=True) + ends = torch.tensor(rows_per_expert, device=device).cumsum(0).to(torch.int32) + ws_bytes = wgrad_gemm.get_ep_wgrad_workspace_layout(*args)[0] + workspace = torch.zeros(ws_bytes, dtype=torch.uint8, device=device) + stream = ctypes.c_void_p(torch.cuda.current_stream().cuda_stream) + for gemm in launches: + if mxfp8: + gemm( + grad, x, _unit_e8m0(rows * m // 32, device), _unit_e8m0(rows * n // 32, device), + weight_grad, ends, workspace, stream, + ) # fmt: skip + else: + gemm(grad, x, weight_grad, ends, workspace, stream) + torch.cuda.synchronize() + base = init if accumulate else torch.zeros_like(init) + return grad.float(), x.float(), base, weight_grad.float() + + +@pytest.mark.parametrize( + "mxfp8,fp32_out,accumulate,rows_per_expert", + [ + (False, False, False, [2 * TILE, TILE, 0, 3 * TILE]), # BF16 written + (False, True, False, [2 * TILE, TILE, 0, 3 * TILE]), # FP32 written + (False, False, True, [TILE, 0, 2 * TILE, TILE]), # BF16 accumulated + (True, False, False, [2 * TILE, TILE, 0, 3 * TILE]), # MXFP8 operands + (True, True, False, [2 * TILE, TILE, 0, 3 * TILE]), # MXFP8, FP32 written + (True, False, True, [TILE, 0, 2 * TILE, TILE]), # MXFP8, BF16 accumulated + (True, True, True, [TILE, 0, 2 * TILE, TILE]), # MXFP8, FP32 accumulated + ], +) +def test_wgrad_gemm_matches_reference(mxfp8, fp32_out, accumulate, rows_per_expert): + """Grouped weight gradient matches a float32 reference; empty experts keep their input.""" + grad, x, base, weight_grad = _run_wgrad(rows_per_expert, mxfp8, fp32_out, accumulate) + ref = base.clone() + start = 0 + for e, count in enumerate(rows_per_expert): + sl = slice(start, start + count) + ref[e] += grad[sl].t() @ x[sl] + start += count + # A written FP32 gradient is exact; a BF16 one rounds once. + tol = 2.0**-16 if fp32_out else 2.0**-8 + err = (weight_grad - ref).abs() / ref.abs().clamp_min(1e-6) + assert err.max() <= tol + + +def _read_col_scales(words, rows_per_expert, cols, device): + """Columnwise E8M0 scale per row and column from the GEMM-swizzled per-expert scale words.""" + scale = torch.ones(sum(rows_per_expert), cols, device=device) + col = torch.arange(cols, device=device) + start = 0 + for count in rows_per_expert: + if count: + r = torch.arange(start, start + count, device=device) + group = r // 128 - start // 128 + index = ( + start * (cols // 128) + + (col // 128) * count + + group[:, None] * 128 + + (col % 32)[None, :] * 4 + + ((col // 32) % 4)[None, :] + ) + block = (r // 32) % 4 + e8m0 = (words[index] >> (8 * block[:, None])) & 0xFF + scale[start : start + count] = torch.pow(2.0, e8m0.float() - 127) + start += count + return scale + + +def _run_requant(rows_per_expert, cols, ready_slot_rows=0, nan_scale=None): + """Launch the MXFP8 rowwise-to-columnwise requant and return (codes, col_codes, scale words, + used). Row scales are unit, so the rowwise values are the codes themselves. With + ``ready_slot_rows``, the rows and then their dispatch flags arrive late, on another stream. + ``nan_scale`` is a (row, 32-column block) whose rowwise scale is the E8M0 NaN.""" + device = torch.device("cuda") + experts = len(rows_per_expert) + # Spare rows, a whole slot: the capacity exceeds the rows in use. + rows = sum(rows_per_expert) + max(128, ready_slot_rows) + name = f"test_ep_requant_{rows}_{cols}_{ready_slot_rows}" + assert requantize.get_ep_requant_function(name, rows, cols, experts, ready_slot_rows) + fn = tvm_ffi.get_global_func(name) + + gen = torch.Generator(device=device).manual_seed(0) + # Powers of two: the columnwise requant represents them exactly, so it costs no tolerance. + exps = torch.randint(-2, 2, (rows, cols), device=device, generator=gen).float() + signs = 1 - 2 * torch.randint(0, 2, (rows, cols), device=device, generator=gen) + codes = (signs * torch.pow(2.0, exps)).to(torch.float8_e4m3fn) + row_scales = _unit_e8m0(rows * cols // 32, device) + if nan_scale is not None: + row_scales.view(torch.uint8)[nan_scale[0] * (cols // 32) + nan_scale[1]] = 255 + col_codes = torch.zeros(rows, cols, dtype=torch.float8_e4m3fn, device=device) + col_scales = _unit_e8m0(rows * cols // 32, device) + ends = torch.tensor(rows_per_expert, device=device).cumsum(0).to(torch.int32) + stream = ctypes.c_void_p(torch.cuda.current_stream().cuda_stream) + if ready_slot_rows: + received = torch.zeros_like(codes) + signal = torch.full((rows // ready_slot_rows,), -1, dtype=torch.int32, device=device) + # Enqueued first, so a run that serializes kernels does not hang. + arrival = torch.cuda.Stream() + arrival.wait_stream(torch.cuda.current_stream()) + with torch.cuda.stream(arrival): + torch.cuda._sleep(10**7) + received.copy_(codes) + signal.fill_(0) + fn(received, row_scales, col_codes, col_scales, ends, signal, stream) + else: + fn(codes, row_scales, col_codes, col_scales, ends, stream) + torch.cuda.synchronize() + words = col_scales.view(torch.uint8).view(torch.int32) + return codes.float(), col_codes.float(), words, sum(rows_per_expert) + + +@pytest.mark.parametrize("ready_slot_rows", [0, 128, 256]) +@pytest.mark.parametrize( + "cols,rows_per_expert", + [ + (256, [128, 256, 0, 128]), + (512, [256, 0, 128, 128]), + ], +) +def test_requantize_matches_reference(cols, rows_per_expert, ready_slot_rows): + """MXFP8 rowwise-to-columnwise requant reproduces the dequantized rows exactly for power-of-two + values; rows past the last expert stay 0. With ``ready_slot_rows``, it waits for rows that + arrive after its launch.""" + codes, col_codes, words, used = _run_requant(rows_per_expert, cols, ready_slot_rows) + scale = _read_col_scales(words, rows_per_expert, cols, codes.device) + assert torch.equal(col_codes[:used] * scale, codes[:used]) + assert torch.count_nonzero(col_codes[used:]) == 0 + + +def test_requantize_nan_scale(): + """A rowwise E8M0 scale of 255 makes its 32 values NaN and leaves every other value finite.""" + cols, row, block = 256, 5, 2 + _, col_codes, _, used = _run_requant([128], cols, nan_scale=(row, block)) + expected = torch.zeros(used, cols, dtype=torch.bool, device=col_codes.device) + expected[row, block * 32 : (block + 1) * 32] = True + assert torch.equal(col_codes[:used].isnan(), expected) diff --git a/transformer_engine/common/CMakeLists.txt b/transformer_engine/common/CMakeLists.txt index 26bd44c0156..426abd2f45d 100644 --- a/transformer_engine/common/CMakeLists.txt +++ b/transformer_engine/common/CMakeLists.txt @@ -629,6 +629,8 @@ target_link_libraries(transformer_engine PUBLIC ${NCCL_LIB}) target_sources(transformer_engine PRIVATE ep/ep_backend.cpp ep/ep_api.cpp + ep/ep_gemm_api.cpp + ep/ep_overlap_workspace.cu ep/nccl_ep_provider.cpp) target_compile_definitions(transformer_engine PRIVATE NVTE_WITH_NCCL_EP) @@ -636,7 +638,7 @@ message(STATUS "NCCL EP enabled (runtime-loaded library): ${NCCL_EP_SHARED_LIB}" message(STATUS "NCCL EP include: ${NCCL_EP_INCLUDE_DIR}") else() # NCCL EP off: ep_api.cpp's #else branch exports throwing nvte_ep_* stubs. - target_sources(transformer_engine PRIVATE ep/ep_api.cpp) + target_sources(transformer_engine PRIVATE ep/ep_api.cpp ep/ep_gemm_api.cpp) message(STATUS "NCCL EP disabled (NVTE_WITH_NCCL_EP=OFF) - using nvte_ep_* stubs") endif() diff --git a/transformer_engine/common/CuTeDSL/__init__.py b/transformer_engine/common/CuTeDSL/__init__.py index e5a37354528..4243d6b418f 100644 --- a/transformer_engine/common/CuTeDSL/__init__.py +++ b/transformer_engine/common/CuTeDSL/__init__.py @@ -8,6 +8,8 @@ They should provide a string function name which can be used to retrieve the corresponding CuTeDSL kernel function via TVM-FFI. """ +import logging + import tvm_ffi from transformer_engine.common.CuTeDSL.cast.mxfp8.dequantize_mxfp8 import ( @@ -21,6 +23,33 @@ get_mxfp8_requantization_function, ) +logger = logging.getLogger("transformer_engine.cutedsl") + + +def _register_ep_backends(): + """Register the EP grouped GEMM backends; a failure leaves the other backends registered.""" + try: + from transformer_engine.common.CuTeDSL.ep_gemm import ( # pylint: disable=import-outside-toplevel + dispatch_gemm, + combine_gemm, + requantize, + wgrad_gemm, + ) + + for function in ( + dispatch_gemm.get_ep_dispatch_gemm_function, + dispatch_gemm.get_ep_dispatch_gemm_workspace_layout, + combine_gemm.get_ep_combine_gemm_function, + combine_gemm.get_ep_combine_gemm_workspace_layout, + wgrad_gemm.get_ep_wgrad_function, + wgrad_gemm.get_ep_wgrad_workspace_layout, + wgrad_gemm.get_ep_wgrad_reads_descriptors, + requantize.get_ep_requant_function, + ): + tvm_ffi.register_global_func(function.__name__, function, override=True) + except Exception as e: # pylint: disable=broad-exception-caught + logger.warning("EP grouped GEMM CuTeDSL backends are unavailable: %s", e) + def register_cutedsl_backends(): """Register all available CuTeDSL backends for on-demand compilation via TVM-FFI. @@ -33,3 +62,4 @@ def register_cutedsl_backends(): get_mxfp8_requantization_function, ): tvm_ffi.register_global_func(entrypoint.__name__, entrypoint, override=True) + _register_ep_backends() diff --git a/transformer_engine/common/CuTeDSL/ep_gemm/__init__.py b/transformer_engine/common/CuTeDSL/ep_gemm/__init__.py new file mode 100644 index 00000000000..2e9e21a1314 --- /dev/null +++ b/transformer_engine/common/CuTeDSL/ep_gemm/__init__.py @@ -0,0 +1,13 @@ +# Copyright (c) 2022-2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# See LICENSE for license information. + +"""Grouped GEMMs overlapped with EP communication, loaded through TVM-FFI. + +dispatch_gemm: reads row tiles as a dispatch delivers them (FC1 forward, FC2 data gradient). +combine_gemm: publishes column chunks for a combine to send (FC2 forward, FC1 data gradient). +wgrad_gemm: weight gradients chained behind the backward GEMMs. +requantize: columnwise MXFP8 operands of the weight gradients from received rowwise rows. +""" + +from . import dispatch_gemm, combine_gemm, requantize, wgrad_gemm diff --git a/transformer_engine/common/CuTeDSL/ep_gemm/_loader.py b/transformer_engine/common/CuTeDSL/ep_gemm/_loader.py new file mode 100644 index 00000000000..bfaa5c1789d --- /dev/null +++ b/transformer_engine/common/CuTeDSL/ep_gemm/_loader.py @@ -0,0 +1,343 @@ +# Copyright (c) 2022-2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# See LICENSE for license information. + +"""Loading of the EP grouped GEMMs: kernel tree, fake operands and TVM-FFI registration. + +The kernels are loaded from ``NVTE_MOE_OVERLAP`` (a ``gemm/`` tree with ``blackwell/``, +``rubin/`` and ``utils/``), compiled once per configuration and registered under a name chosen by +C++. +""" + +import functools +import importlib +import logging +import os +import sys +from dataclasses import dataclass +from typing import Optional + +import tvm_ffi + +from ..utils import device_compute_capability, tvm_ffi_function + +logger = logging.getLogger(__name__) + +# Points at an external CuTeDSL kernel tree the GEMMs are imported from. +# TODO(phuonguyen): drop this kernel-root path once the kernels are upstreamed into cuDNN. +GEMM_PATH_ENV = "NVTE_MOE_OVERLAP" +MMA_TILER_MN = (256, 256) +CLUSTER_MN = (2, 1) +# Rows per M tile. A smaller expert alignment ends an expert in a tail tile. +ROWS_PER_TILE = MMA_TILER_MN[0] // 2 * CLUSTER_MN[0] +# Values per MXFP8 E8M0 scale. +SF_VEC_SIZE = 32 +# Operand scaling modes (NVTEScalingMode): BF16 operands carry the delayed default, MXFP8 the 1D. +DELAYED_TENSOR_SCALING = 0 +MXFP8_1D_SCALING = 1 + + +@dataclass(frozen=True) +class GemmArch: + """The kernels of one architecture: their subdirectories of the GEMM path, searched in order, + and the BF16 kernels as ``module.Class``.""" + + subdirs: tuple + dispatch_fwd: str # FC1 + SwiGLU + dispatch_bwd: str # FC2 data gradient + SwiGLU backward + combine: str # FC2, FC1 data gradient + mxfp8_tail_tiles: bool # MXFP8 kernels for experts padded to fewer rows than a tile + mxfp8_modules: tuple # modules of the MXFP8 kernels + + +_SM100 = GemmArch( + subdirs=("blackwell",), + dispatch_fwd="moe_grouped_gemm_glu_sm100.MoEGroupedGemmGluBiasBf16Kernel", + dispatch_bwd="moe_grouped_gemm_dglu_dbias.MoEGroupedGemmDgluDbiasBf16Kernel", + combine="moe_grouped_gemm_sm100.MoEGroupedGemmBf16Kernel", + mxfp8_tail_tiles=True, + mxfp8_modules=( + "moe_blockscaled_grouped_gemm_quant_sm100", + "moe_blockscaled_grouped_gemm_dglu_dbias", + "moe_blockscaled_grouped_gemm_wgrad", + "moe_blockscaled_grouped_gemm_wgrad_dense", + "moe_blockscaled_grouped_gemm_wgrad_reuse", + ), +) +# The SM 10.7 kernels build on the SM 10.0 ones. +_SM107 = GemmArch( + subdirs=("rubin", "blackwell"), + dispatch_fwd="moe_grouped_gemm_glu_sm107.MoEGroupedGemmGluBiasBf16Kernel", + dispatch_bwd="moe_grouped_gemm_sm107.MoEGroupedGemmDgluDbiasBf16Kernel", + combine="moe_grouped_gemm_sm107.MoEGroupedGemmBf16Kernel", + mxfp8_tail_tiles=False, + mxfp8_modules=( + "moe_blockscaled_grouped_gemm_quant_rubin", + "moe_blockscaled_grouped_gemm_dglu_rubin", + "moe_blockscaled_grouped_gemm_glu_rubin", + "moe_blockscaled_grouped_gemm_wgrad_rubin", + "moe_blockscaled_grouped_gemm_wgrad_reuse_rubin", + ), +) +# Kernels by compute capability; other architectures run the unfused ops. +GEMM_ARCHS = {(10, 0): _SM100, (10, 3): _SM100, (10, 7): _SM107} + + +def gemm_arch(): + """The kernels of the current device (the SM 10.0 ones on an unsupported device).""" + return GEMM_ARCHS.get(device_compute_capability(), _SM100) + + +def is_sm107(): + """Whether the current device runs the SM 10.7 kernels.""" + return gemm_arch() is _SM107 + + +_LOADED_ROOT: list = [] + +# What TE reads from the kernel tree, module by module (dotted names are nested attributes). +_SHARED_INTERFACE = { + "moe_utils": ("MoEWeightMode.DENSE", "WGradInputOrder.Tensor2D", "WgradTileClaim.COUNTER"), + "moe_tail_tiles": ("FUSED_TAIL_MAX_ROWS",), + "moe_signal_helpers": ("signal_workspace_offsets",), + "moe_streaming_output_chunk_tile_scheduler": ( + "OutputNotifyConfig", + "OutputNotifyMode.N_CHUNK", + "output_notify_capacity", + "output_notify_offsets", + ), +} +_WGRAD_CLASSES = ("MoEGroupedGemmWgradBF16Kernel", "MoEGroupedGemmWgradWideBF16Kernel") + + +def _missing(obj, dotted_names): + """The names of ``dotted_names`` that ``obj`` lacks.""" + missing = [] + for dotted in dotted_names: + target = obj + for part in dotted.split("."): + target = getattr(target, part, None) + if target is None: + missing.append(dotted) + return missing + + +@functools.lru_cache(maxsize=None) +def _gemm_interface_reason(root, capability, mxfp8): + del root, capability # The cache key: the tree and the architecture the checks ran on. + problems = [] + try: + for name, attributes in _SHARED_INTERFACE.items(): + missing = _missing(import_gemm_modules(name)[0], attributes) + if missing: + problems.append(f"{name} lacks {', '.join(missing)}") + arch = gemm_arch() + for role in ("dispatch_fwd", "dispatch_bwd", "combine"): + module_name, class_name = getattr(arch, role).split(".") + kernel = getattr(import_gemm_modules(module_name)[0], class_name, None) + if kernel is None: + problems.append(f"{module_name} lacks {class_name}") + elif role == "dispatch_fwd" and not hasattr(kernel, "FC1_TAIL_AT_SLOTS_READY"): + problems.append(f"{class_name} lacks FC1_TAIL_AT_SLOTS_READY") + if mxfp8: + for module_name in arch.mxfp8_modules: + import_gemm_modules(module_name) + names = ( + ("moe_grouped_gemm_sm107",) * 2 + if is_sm107() + else ("moe_grouped_gemm_wgrad", "moe_grouped_gemm_wgrad_wide") + ) + for module_name, class_name in zip(names, _WGRAD_CLASSES): + if getattr(import_gemm_modules(module_name)[0], class_name, None) is None: + problems.append(f"{module_name} lacks {class_name}") + except ImportError as e: + problems.append(f"cannot import {e.name or e}") + if problems: + return "the EP grouped GEMM kernel tree does not match Transformer Engine: " + "; ".join( + problems + ) + return None + + +# TODO(phuonguyen): check the kernel tree's version (cudnn-frontend release or EPCompOverlap +# commit) against a minimum once the kernels ship in a versioned package; for now the tree is +# only checked for the names TE reads. +def gemm_interface_reason(mxfp8=False) -> Optional[str]: + """Why the kernel tree at ``NVTE_MOE_OVERLAP`` lacks what the EP grouped GEMMs read, or None; + ``mxfp8`` also checks the MXFP8 kernels. Checked once per tree, architecture and recipe; the + tree's version is not otherwise identified.""" + return _gemm_interface_reason(os.environ.get(GEMM_PATH_ENV), device_compute_capability(), mxfp8) + + +def import_gemm_modules(*names): + """Import the named modules of the kernel tree (and ``moe_utils`` last) from the GEMM path.""" + root = os.environ.get(GEMM_PATH_ENV) + if not root: + raise ModuleNotFoundError( + f"{GEMM_PATH_ENV} is not set: the EP grouped GEMMs are not available" + ) + if _LOADED_ROOT and _LOADED_ROOT[0] != root: + # The modules are imported by name, so those of the first tree stay in sys.modules. + raise RuntimeError( + f"{GEMM_PATH_ENV} changed from {_LOADED_ROOT[0]} to {root} after the EP grouped GEMMs" + " were loaded; restart the process to use the other kernel tree." + ) + _LOADED_ROOT[:] = [root] + for sub in reversed(("", *gemm_arch().subdirs, "utils")): + path = os.path.join(root, sub) if sub else root + if path not in sys.path: + sys.path.insert(0, path) + importlib.invalidate_caches() + return tuple(importlib.import_module(name) for name in (*names, "moe_utils")) + + +def import_bf16_kernel(role): + """The current device's BF16 kernel class of ``role`` (a ``GemmArch`` field) and + ``moe_utils``.""" + module_name, class_name = getattr(gemm_arch(), role).split(".") + module, moe_utils = import_gemm_modules(module_name) + return getattr(module, class_name), moe_utils + + +def unsupported_device_reason(what): + """Why ``what`` cannot run on the current device, or None.""" + if device_compute_capability() in GEMM_ARCHS: + return None + supported = ", ".join(f"{major}.{minor}" for major, minor in GEMM_ARCHS) + major, minor = device_compute_capability() + return f"The {what} needs SM {supported}, got SM {major}.{minor}." + + +def device_smem_optin(): + """Opt-in shared memory per block of the current CUDA device, in bytes.""" + from cuda.bindings import runtime as cudart # pylint: disable=import-outside-toplevel + + err, device = cudart.cudaGetDevice() + assert err == cudart.cudaError_t.cudaSuccess, err + err, smem = cudart.cudaDeviceGetAttribute( + cudart.cudaDeviceAttr.cudaDevAttrMaxSharedMemoryPerBlockOptin, device + ) + assert err == cudart.cudaError_t.cudaSuccess, err + return smem + + +def fake_tensor(dtype, shape, order, align): + """A compact fake gmem tensor to compile against.""" + from cutlass import cute # pylint: disable=import-outside-toplevel + + return cute.runtime.make_fake_compact_tensor( + dtype, shape, stride_order=order, memspace=cute.AddressSpace.gmem, assumed_align=align + ) + + +def rows_view(t, rows, cols): + """Row-major [rows, cols] operand as the kernel's (rows, cols, 1) tensor.""" + from cutlass import cute # pylint: disable=import-outside-toplevel + + return cute.make_tensor( + t.iterator, cute.make_layout((rows, cols, 1), stride=(cols, 1, rows * cols)) + ) + + +def weight_view(b, n, k, experts, n_major): + """Weight [experts, n, k], or N-major [experts, k, n], as the kernel's (n, k, experts) tensor.""" + from cutlass import cute # pylint: disable=import-outside-toplevel + + stride = (1, n, k * n) if n_major else (k, 1, n * k) + return cute.make_tensor(b.iterator, cute.make_layout((n, k, experts), stride=stride)) + + +def compile_launch(launch, *fakes): + """Compile ``launch`` with TVM-FFI against fake operands and a fake stream.""" + from cutlass import cute # pylint: disable=import-outside-toplevel + + return cute.compile(launch, *fakes, cute.runtime.make_fake_stream(), options="--enable-tvm-ffi") + + +def prob_view(prob, rows): + """[rows] probabilities as the kernel's (rows, 1, 1) tensor.""" + from cutlass import cute # pylint: disable=import-outside-toplevel + + return cute.make_tensor(prob.iterator, cute.make_layout((rows, 1, 1), stride=(1, 1, 1))) + + +def fp8_fake(shape, order): + """A fake E4M3 operand.""" + import cutlass # pylint: disable=import-outside-toplevel + + return fake_tensor(cutlass.Float8E4M3FN, shape, order, 16) + + +def scale_fake(rows, cols): + """Fake E8M0 scales of a [rows, cols] MXFP8 operand, compact or GEMM-swizzled.""" + import cutlass # pylint: disable=import-outside-toplevel + + return fake_tensor(cutlass.Float8E8M0FNU, (rows * cols // SF_VEC_SIZE,), (0,), 16) + + +def blockscaled_kwargs(num_experts): + """Constructor arguments shared by the MXFP8 kernels.""" + import cutlass # pylint: disable=import-outside-toplevel + + moe_utils = import_gemm_modules()[0] + return { + "sf_vec_size": SF_VEC_SIZE, + "acc_dtype": cutlass.Float32, + "use_2cta_instrs": True, + "mma_tiler_mn": MMA_TILER_MN, + "cluster_shape_mn": CLUSTER_MN, + "vectorized_f32": False, + "expert_cnt": num_experts, + "weight_mode": moe_utils.MoEWeightMode.DENSE, + "use_dynamic_sched": True, + } + + +def tail_tile_kwargs(rows_alignment, fused=False): + """Constructor arguments for experts padded to ``rows_alignment`` rows; ``fused`` runs the + smallest tails inside their expert's last full tile (BF16 forward GEMMs).""" + if rows_alignment >= ROWS_PER_TILE: + return {} + kwargs = {"tail_rows_alignment": rows_alignment} + if fused: + tail_tiles = import_gemm_modules("moe_tail_tiles")[0] + kwargs["fused_tail_max_rows"] = tail_tiles.FUSED_TAIL_MAX_ROWS + return kwargs + + +def mxfp8_tail_tile_kwargs(rows_alignment): + """``tail_tile_kwargs`` of the MXFP8 kernels.""" + if gemm_arch().mxfp8_tail_tiles: + return tail_tile_kwargs(rows_alignment) + if rows_alignment < ROWS_PER_TILE: + raise ValueError( + f"The MXFP8 kernels of this device need experts padded to {ROWS_PER_TILE} rows." + ) + return {} + + +def tail_fakes(rows, experts, ws_bytes): + """Fake row ends, alpha, prob and workspace operands shared by every launch.""" + import cutlass # pylint: disable=import-outside-toplevel + + return ( + fake_tensor(cutlass.Int32, (experts,), (0,), 16), + fake_tensor(cutlass.Float32, (experts,), (0,), 16), + fake_tensor(cutlass.Float32, (rows,), (0,), 16), + fake_tensor(cutlass.Uint8, (ws_bytes,), (0,), 128), + ) + + +def register_function(fn_name, compile_fn, what) -> bool: + """Compile and register ``fn_name`` unless registered; return whether it is.""" + try: + if tvm_ffi.get_global_func(fn_name, allow_missing=True) is not None: + return True + if (reason := unsupported_device_reason(what)) is not None: + logger.warning("%s", reason) + return False + tvm_ffi.register_global_func(fn_name, tvm_ffi_function(compile_fn()), override=True) + return True + except Exception as e: # pylint: disable=broad-exception-caught + logger.error("The %s is not available: %s", what, e) + return False diff --git a/transformer_engine/common/CuTeDSL/ep_gemm/combine_gemm.py b/transformer_engine/common/CuTeDSL/ep_gemm/combine_gemm.py new file mode 100644 index 00000000000..cd7259029bf --- /dev/null +++ b/transformer_engine/common/CuTeDSL/ep_gemm/combine_gemm.py @@ -0,0 +1,232 @@ +# Copyright (c) 2022-2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# See LICENSE for license information. + +"""Grouped GEMM that publishes its output to the EP combine (BF16 or MXFP8, SM 10.0, 10.3 and +10.7). + + mode a b (weight) d + forward [rows,k] [E,n,k] [rows,n] BF16, scaled per row by prob + backward [rows,k] [E,k,n] (the forward weight) [rows,n] BF16, scaled per row by prob + +BF16 operands, or E4M3 with GEMM-swizzled E8M0 scales ``sfa`` and ``sfb`` for MXFP8 (the backward +reads the columnwise forward weight). Common operands: ``expert_row_ends`` [E] int32, ``alpha`` +[E] FP32, ``prob`` [rows] FP32, ``workspace`` uint8, stream. ``signal[u] = u`` once columns +``[u * n_chunk, (u + 1) * n_chunk)`` of ``d`` are final; the caller sets ``signal[]`` to -1 before +each launch. With ``n_chunk`` 0 the GEMM publishes nothing and runs in the stock tile order; its +workspace ends in one flag word the caller sets. +""" + +import functools +from dataclasses import dataclass, field + +import cutlass +from cutlass import cute +from cutlass.cute.nvgpu import OperandMajorMode + +from ._loader import ( + device_compute_capability, + CLUSTER_MN, + DELAYED_TENSOR_SCALING, + MMA_TILER_MN, + MXFP8_1D_SCALING, + ROWS_PER_TILE, + blockscaled_kwargs, + compile_launch, + fake_tensor, + fp8_fake, + import_bf16_kernel, + import_gemm_modules, + is_sm107, + mxfp8_tail_tile_kwargs, + prob_view, + register_function, + rows_view, + scale_fake, + tail_fakes, + tail_tile_kwargs, + weight_view, +) + + +@dataclass(frozen=True) +class CombineGemmConfig: + """Static configuration of one compiled EP grouped GEMM combine.""" + + rows: int # receive capacity in rows + k: int # reduction size (ffn) + n: int # output columns (hidden) + num_experts: int # local experts + num_clusters: int # persistent clusters beside the combine's SMs + n_chunk: int # columns per readiness flag, 0: no flags + dependents_at_entry: bool # the combine may start at the GEMM's entry (signaled combine only) + backward: bool = False + scaling_mode: int = DELAYED_TENSOR_SCALING # operand scaling (NVTEScalingMode) + rows_alignment: int = ROWS_PER_TILE # rows per expert slab are a multiple of it + grid_clusters: int = 0 # clusters launched (0: num_clusters), extras stop after the first chunk + # Kernels, workspace layouts and compiled functions are specific to the device architecture. + capability: tuple = field(default_factory=device_compute_capability) + + @property + def mxfp8(self) -> bool: + """Whether the operands are MXFP8 rather than BF16.""" + return self.scaling_mode == MXFP8_1D_SCALING + + +def build_kernel(cfg: CombineGemmConfig): + """Kernel for ``cfg`` that publishes finished column chunks to ``signal[]`` (none: n_chunk 0).""" + comb, moe_utils = import_gemm_modules("moe_streaming_output_chunk_tile_scheduler") + notify = None + if cfg.n_chunk: + notify = comb.OutputNotifyConfig( + comb.OutputNotifyMode.N_CHUNK, + cfg.n_chunk, + comb.output_notify_capacity(cfg.n_chunk, cfg.n), + caller_reset=True, + clusters_beside_combine=cfg.num_clusters, + ) + if cfg.mxfp8: + rubin = is_sm107() + module = import_gemm_modules( + "moe_blockscaled_grouped_gemm_quant_rubin" + if rubin + else "moe_blockscaled_grouped_gemm_quant_sm100" + )[0] + return module.BlockScaledMoEGroupedGemmQuantKernel( + generate_sfd=False, + discrete_col_sfd=False, + enable_bias=False, + output_notify=notify, + launch_dependents_at_entry=cfg.dependents_at_entry, + **({"generate_c": False} if rubin else {}), + **blockscaled_kwargs(cfg.num_experts), + **mxfp8_tail_tile_kwargs(cfg.rows_alignment), + ) + kernel_class, _ = import_bf16_kernel("combine") + return kernel_class( + acc_dtype=cutlass.Float32, + use_2cta_instrs=True, + mma_tiler_mn=MMA_TILER_MN, + cluster_shape_mn=CLUSTER_MN, + vectorized_f32=False, + generate_c=False, + enable_bias=False, + expert_cnt=cfg.num_experts, + weight_mode=moe_utils.MoEWeightMode.DENSE, + use_dynamic_sched=True, + output_notify=notify, + launch_dependents_at_entry=cfg.dependents_at_entry, + **tail_tile_kwargs(cfg.rows_alignment, fused=not cfg.backward), + ) + + +@functools.lru_cache(maxsize=None) +def workspace_layout(cfg: CombineGemmConfig): + """(total bytes, byte offset of signal[], entries of signal[]) of ``cfg``'s workspace.""" + comb = import_gemm_modules("moe_streaming_output_chunk_tile_scheduler")[0] + if not cfg.n_chunk: + signal = -(-build_kernel(cfg).get_workspace_bytes() // 4) * 4 + return signal + 4, signal, 1 + offsets = comb.output_notify_offsets(build_kernel(cfg)) + return offsets["total_bytes"], offsets["signal"], offsets["capacity"] + + +def _compile(cfg: CombineGemmConfig): + """Compile the launch wrapper of ``cfg`` with TVM-FFI.""" + kernel = build_kernel(cfg) + rows, k, n, experts = cfg.rows, cfg.k, cfg.n, cfg.num_experts + num_clusters, backward = cfg.grid_clusters or cfg.num_clusters, cfg.backward + + @cute.jit + def launch(a, b, d, expert_row_ends, alpha, prob, workspace, stream): + weight = weight_view(b, n, k, experts, n_major=backward) + d3 = rows_view(d, rows, n) + kernel( + rows_view(a, rows, k), weight, cutlass.Int32(0), cutlass.Int32(0), cutlass.Int64(0), + OperandMajorMode.K, workspace.iterator, d3, d3, expert_row_ends, alpha, None, + prob_view(prob, rows), num_clusters, stream, + ) # fmt: skip + + return compile_launch( + launch, + fake_tensor(cutlass.BFloat16, (rows, k), (1, 0), 16), + fake_tensor( + cutlass.BFloat16, (experts, k, n) if backward else (experts, n, k), (2, 1, 0), 16 + ), + fake_tensor(cutlass.BFloat16, (rows, n), (1, 0), 16), + *tail_fakes(rows, experts, workspace_layout(cfg)[0]), + ) + + +def _compile_mxfp8(cfg: CombineGemmConfig): + """Compile the MXFP8 launch wrapper of ``cfg`` with TVM-FFI.""" + kernel = build_kernel(cfg) + rows, k, n, experts = cfg.rows, cfg.k, cfg.n, cfg.num_experts + num_clusters, backward = cfg.grid_clusters or cfg.num_clusters, cfg.backward + + @cute.jit + def launch(a, b, sfb, sfa, d, expert_row_ends, alpha, prob, workspace, stream): + weight = weight_view(b, n, k, experts, n_major=backward) + d3 = rows_view(d, rows, n) + kernel( + rows_view(a, rows, k), weight, sfb, cutlass.Int32(0), cutlass.Int32(0), + cutlass.Int64(0), OperandMajorMode.K, workspace.iterator, d3, d3, sfa, None, None, + None, None, expert_row_ends, alpha, None, None, prob_view(prob, rows), None, + num_clusters, stream, + ) # fmt: skip + + @cute.jit + def launch_rubin(a, b, sfb, sfa, d, expert_row_ends, alpha, prob, workspace, stream): + # The SM 10.7 kernel takes c (not stored) ahead of d, and the bias ahead of prob. + weight = weight_view(b, n, k, experts, n_major=backward) + d3 = rows_view(d, rows, n) + kernel( + rows_view(a, rows, k), weight, sfb, cutlass.Int32(0), cutlass.Int32(0), + cutlass.Int64(0), OperandMajorMode.K, workspace.iterator, d3, d3, d3, sfa, None, None, + None, None, expert_row_ends, alpha, None, prob_view(prob, rows), num_clusters, stream, + ) # fmt: skip + + return compile_launch( + launch_rubin if is_sm107() else launch, + fp8_fake((rows, k), (1, 0)), + fp8_fake((experts, k, n) if backward else (experts, n, k), (2, 1, 0)), + scale_fake(experts * n, k), + scale_fake(rows, k), + fake_tensor(cutlass.BFloat16, (rows, n), (1, 0), 16), + *tail_fakes(rows, experts, workspace_layout(cfg)[0]), + ) + + +def _config( + rows, k, n, num_experts, num_clusters, n_chunk, dependents_at_entry, backward, scaling_mode, + rows_alignment, grid_clusters, +): # fmt: skip + """Build a CombineGemmConfig from the entry-point arguments.""" + return CombineGemmConfig( + rows, k, n, num_experts, num_clusters, n_chunk, bool(dependents_at_entry), bool(backward), + int(scaling_mode), rows_alignment, grid_clusters, + ) # fmt: skip + + +def get_ep_combine_gemm_workspace_layout( + rows, k, n, num_experts, num_clusters, n_chunk, dependents_at_entry, backward, + scaling_mode=DELAYED_TENSOR_SCALING, rows_alignment=ROWS_PER_TILE, grid_clusters=0, +): # fmt: skip + """[total bytes, signal offset, signal entries] of the workspace of this configuration.""" + return list(workspace_layout(_config( + rows, k, n, num_experts, num_clusters, n_chunk, dependents_at_entry, backward, scaling_mode, + rows_alignment, grid_clusters, + ))) # fmt: skip + + +def get_ep_combine_gemm_function( + fn_name, rows, k, n, num_experts, num_clusters, n_chunk, dependents_at_entry, backward, + scaling_mode=DELAYED_TENSOR_SCALING, rows_alignment=ROWS_PER_TILE, grid_clusters=0, +) -> bool: # fmt: skip + """Compile and register the GEMM of this configuration as ``fn_name``; return whether it is.""" + cfg = _config( + rows, k, n, num_experts, num_clusters, n_chunk, dependents_at_entry, backward, scaling_mode, + rows_alignment, grid_clusters, + ) # fmt: skip + compile_fn = _compile_mxfp8 if cfg.mxfp8 else _compile + return register_function(fn_name, lambda: compile_fn(cfg), "EP grouped GEMM combine") diff --git a/transformer_engine/common/CuTeDSL/ep_gemm/dispatch_gemm.py b/transformer_engine/common/CuTeDSL/ep_gemm/dispatch_gemm.py new file mode 100644 index 00000000000..001419e51a7 --- /dev/null +++ b/transformer_engine/common/CuTeDSL/ep_gemm/dispatch_gemm.py @@ -0,0 +1,401 @@ +# Copyright (c) 2022-2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# See LICENSE for license information. + +"""Signal-aware grouped GEMMs that follow an EP dispatch (BF16 or MXFP8, SM 10.0, 10.3 and 10.7). + +An M tile starts once each of its slots s has ``signal[s] == s``. Operands (rows = receive rows): + + mode a b (weight) outputs + fwd BF16 [rows,k] [E,n,k] c [rows,n]; d [rows,n/2] = silu(gate)*up*prob + bwd BF16 [rows,k] [E,k,n] d [rows,2n] = grad of c; dprob [rows] FP32 (added to) + fwd MXFP8 E4M3 E4M3 c BF16 [rows,n]; d E4M3 [rows,n/2] + swizzled sfd + bwd MXFP8 E4M3 columnwise E4M3 d rowwise + d_col columnwise, h [rows,n] columnwise + +Forward is FC1 (gate and up alternate in 32-column blocks of ``c``). Backward is the FC2 data +gradient with the SwiGLU backward in the epilogue; its ``c`` is the FC1 output [rows, 2n]. +Common operands: ``expert_row_ends`` [E] int32, ``alpha`` [E] FP32, ``prob`` [rows] FP32, +``workspace`` uint8, stream. With ``device_layout`` the forward also waits for the dispatch to +write ``expert_row_ends`` and the word before it (expert 0's offset), both -1 beforehand. The +kernel tree must wait until they are at least 0 (EPC fc1db0b8 or later). + +MXFP8 scales: ``sfa`` is compact (as the dispatch delivers it) and ``sfb`` swizzled. The forward +takes no ``prob`` and a ``norm_const`` [1] FP32 of 1. The backward writes ``sfd_row`` (swizzled), +``sfd_col`` and ``sfh_col`` (swizzled per expert). +""" + +import functools +from dataclasses import dataclass, field + +import cutlass +from cutlass import cute +from cutlass.cute.nvgpu import OperandMajorMode + +from ._loader import ( + device_compute_capability, + CLUSTER_MN, + DELAYED_TENSOR_SCALING, + MMA_TILER_MN, + MXFP8_1D_SCALING, + ROWS_PER_TILE, + blockscaled_kwargs, + compile_launch, + device_smem_optin, + fake_tensor, + fp8_fake, + import_bf16_kernel, + import_gemm_modules, + is_sm107, + mxfp8_tail_tile_kwargs, + prob_view, + register_function, + rows_view, + scale_fake, + tail_fakes, + tail_tile_kwargs, + weight_view, +) + +# Activation of the FC1 GLU to the activation function of its backward epilogue. +_BACKWARD_ACTIVATIONS = {"swiglu": "dswiglu"} +# A/B stages of the SM 10.7 forward GEMMs, BF16 and MXFP8 with compact scales read by TMA. +_RUBIN_FC1_AB_STAGES = 8 + + +@dataclass(frozen=True) +class DispatchGemmConfig: + """Static configuration of one compiled dispatch grouped GEMM.""" + + rows: int # receive capacity in rows, a multiple of slot_rows + k: int # reduction size + n: int # GEMM columns: forward 2 * ffn (gate and up), backward ffn + num_experts: int # local experts + num_clusters: int # persistent clusters beside the dispatch's SMs + backward: bool = False + scaling_mode: int = DELAYED_TENSOR_SCALING # operand scaling (NVTEScalingMode) + rows_alignment: int = ROWS_PER_TILE # rows per expert slab are a multiple of it + device_layout: bool = False # forward: the dispatch writes the expert row ends + activation: str = "swiglu" + # Kernels, workspace layouts and compiled functions are specific to the device architecture. + capability: tuple = field(default_factory=device_compute_capability) + + def __post_init__(self): + if self.activation not in _BACKWARD_ACTIVATIONS: + raise NotImplementedError( + f"Activation {self.activation!r} is not supported by the dispatch grouped GEMMs;" + f" supported: {sorted(_BACKWARD_ACTIVATIONS)}." + ) + + @property + def mxfp8(self) -> bool: + """Whether the operands are MXFP8 rather than BF16.""" + return self.scaling_mode == MXFP8_1D_SCALING + + @property + def slot_rows(self) -> int: + """Rows per ``signal[]`` entry: the expert alignment, at most one row tile.""" + return min(self.rows_alignment, ROWS_PER_TILE) + + @property + def signal_capacity(self) -> int: + """Entries of ``signal[]``, one per slot of the capacity.""" + return self.rows // self.slot_rows + + +def _tail_trigger(kernel_class) -> dict: + """PDL trigger of a forward kernel for its tail on the dispatch's SMs: at slots ready or at + entry, as the kernel class prefers.""" + if kernel_class.FC1_TAIL_AT_SLOTS_READY: + return {"launch_dependents_at_slots_ready": True} + return {"launch_dependents_at_entry": True} + + +def build_kernel(cfg: DispatchGemmConfig): + """Kernel for ``cfg``; row tiles wait on ``signal[]``. A forward one lets its tail launch at the + ``_tail_trigger`` point. The backward one lets the kernel behind it start at entry.""" + backward_activation = _BACKWARD_ACTIVATIONS[cfg.activation] + rubin = is_sm107() + if cfg.mxfp8: + # The TMA warp turns the received compact scales into the GEMM's layout per tile. + common = { + **blockscaled_kwargs(cfg.num_experts), + "signal_capacity": cfg.signal_capacity, + "compact_sfa_sf_warp": True, + "use_pdl": True, + **mxfp8_tail_tile_kwargs(cfg.rows_alignment), + } + if cfg.backward and rubin: + # 128-deep K tiles of one scale atom each: the TMA warp queues the compact scales ahead. + module = import_gemm_modules("moe_blockscaled_grouped_gemm_dglu_rubin")[0] + return module.BlockScaledMoEGroupedGemmDgluKernel( + discrete_col_sfd=True, + act_func=backward_activation, + fp8_k_tile=128, + compact_sfa_queue=True, + **common, + ) + if cfg.backward: + module = import_gemm_modules("moe_blockscaled_grouped_gemm_dglu_dbias")[0] + return module.BlockScaledMoEGroupedGemmDgluDbiasKernel( + discrete_col_sfd=True, + act_func=backward_activation, + **common, + ) + if rubin: + # The fused SwiGLU GEMM. Compact scale rows of whole TMA boxes load by TMA, others + # through registers with the opt-in shared memory. + module = import_gemm_modules("moe_blockscaled_grouped_gemm_glu_rubin")[0] + kernel_class = module.BlockScaledMoEGroupedGemmGluKernel + scale_rows_tma = cfg.k % 1024 == 0 + return kernel_class( + generate_sfd=True, + discrete_col_sfd=False, + act_func=cfg.activation, + enable_bias=False, + generate_c=True, + generate_sfd_col=False, + smem_capacity=None if scale_rows_tma else device_smem_optin(), + device_layout=cfg.device_layout, + max_ab_stages=_RUBIN_FC1_AB_STAGES if scale_rows_tma else None, + compact_sfa_rows=scale_rows_tma, + **_tail_trigger(kernel_class), + **{**common, "vectorized_f32": True}, + ) + module = import_gemm_modules("moe_blockscaled_grouped_gemm_quant_sm100")[0] + kernel_class = module.BlockScaledMoEGroupedGemmQuantKernel + return kernel_class( + generate_sfd=True, + discrete_col_sfd=False, + enable_bias=False, + fuse_swiglu=True, + device_layout=cfg.device_layout, + **_tail_trigger(kernel_class), + **common, + ) + common = { + "acc_dtype": cutlass.Float32, + "use_2cta_instrs": True, + "mma_tiler_mn": MMA_TILER_MN, + "cluster_shape_mn": CLUSTER_MN, + "vectorized_f32": False, + "expert_cnt": cfg.num_experts, + "use_dynamic_sched": True, + "signal_capacity": cfg.signal_capacity, + "use_pdl": True, + **tail_tile_kwargs(cfg.rows_alignment, fused=not cfg.backward), + } + if cfg.backward: + kernel_class, moe_utils = import_bf16_kernel("dispatch_bwd") + return kernel_class( + weight_mode=moe_utils.MoEWeightMode.DENSE, + act_func=backward_activation, + **common, + ) + kernel_class, moe_utils = import_bf16_kernel("dispatch_fwd") + return kernel_class( + weight_mode=moe_utils.MoEWeightMode.DENSE, + generate_c=True, + enable_bias=False, + device_layout=cfg.device_layout, + **({"max_ab_stages": _RUBIN_FC1_AB_STAGES} if rubin else {}), + **_tail_trigger(kernel_class), + **common, + ) + + +@functools.lru_cache(maxsize=None) +def workspace_layout(cfg: DispatchGemmConfig): + """Total bytes and byte offsets of the claim counter, ``signal[]`` and scheduler state.""" + helpers, _ = import_gemm_modules("moe_signal_helpers") + offsets = helpers.signal_workspace_offsets(build_kernel(cfg)) + return offsets["total_bytes"], offsets["counter"], offsets["signal"], offsets["state"] + + +def _prologue(cfg: DispatchGemmConfig): + """Kernel, (rows, k, n, experts, num_clusters) and workspace tail fakes shared by a compiler.""" + kernel = build_kernel(cfg) + dims = (cfg.rows, cfg.k, cfg.n, cfg.num_experts, cfg.num_clusters) + tail = tail_fakes(cfg.rows, cfg.num_experts, workspace_layout(cfg)[0]) + return kernel, dims, tail + + +def _compile_forward(cfg: DispatchGemmConfig): + """FC1: SwiGLU GEMM with the weight [experts, n, k], writing ``c`` and ``d``.""" + kernel, (rows, k, n, experts, num_clusters), tail = _prologue(cfg) + d_cols = n // 2 + + @cute.jit + def launch(a, b, c, d, expert_row_ends, alpha, prob, workspace, stream): + weight = weight_view(b, n, k, experts, n_major=False) + kernel( + rows_view(a, rows, k), weight, cutlass.Int32(0), cutlass.Int32(0), cutlass.Int64(0), + OperandMajorMode.K, workspace.iterator, rows_view(c, rows, n), + rows_view(d, rows, d_cols), expert_row_ends, alpha, prob_view(prob, rows), None, + num_clusters, stream, + ) # fmt: skip + + return compile_launch( + launch, + fake_tensor(cutlass.BFloat16, (rows, k), (1, 0), 16), + fake_tensor(cutlass.BFloat16, (experts, n, k), (2, 1, 0), 16), + fake_tensor(cutlass.BFloat16, (rows, n), (1, 0), 16), + fake_tensor(cutlass.BFloat16, (rows, d_cols), (1, 0), 16), + *tail, + ) + + +def _compile_backward(cfg: DispatchGemmConfig): + """FC2 data gradient with the forward weight [experts, k, n] read N-major, and SwiGLU backward + in the epilogue (unit alpha and beta).""" + kernel, (rows, k, n, experts, num_clusters), tail = _prologue(cfg) + + @cute.jit + def launch(a, b, c, d, dprob, expert_row_ends, alpha, prob, workspace, stream): + weight = weight_view(b, n, k, experts, n_major=True) + kernel( + rows_view(a, rows, k), weight, cutlass.Int32(0), cutlass.Int32(0), cutlass.Int64(0), + OperandMajorMode.K, workspace.iterator, rows_view(c, rows, 2 * n), + rows_view(d, rows, 2 * n), expert_row_ends, alpha, alpha, prob_view(prob, rows), + prob_view(dprob, rows), cutlass.Float32(0.0), None, num_clusters, stream, + ) # fmt: skip + + return compile_launch( + launch, + fake_tensor(cutlass.BFloat16, (rows, k), (1, 0), 16), + fake_tensor(cutlass.BFloat16, (experts, k, n), (2, 1, 0), 16), + fake_tensor(cutlass.BFloat16, (rows, 2 * n), (1, 0), 16), + fake_tensor(cutlass.BFloat16, (rows, 2 * n), (1, 0), 16), + fake_tensor(cutlass.Float32, (rows,), (0,), 16), + *tail, + ) + + +def _compile_forward_mxfp8(cfg: DispatchGemmConfig): + """MXFP8 FC1: SwiGLU GEMM writing the BF16 ``c`` and the E4M3 ``d`` with its scales.""" + kernel, (rows, k, n, experts, num_clusters), tail = _prologue(cfg) + d_cols = n // 2 + + @cute.jit + def launch(a, b, sfb, sfa, c, d, sfd, expert_row_ends, alpha, norm_const, workspace, stream): + weight = weight_view(b, n, k, experts, n_major=False) + d3 = rows_view(d, rows, d_cols) + kernel( + rows_view(a, rows, k), weight, sfb, cutlass.Int32(0), cutlass.Int32(0), + cutlass.Int64(0), OperandMajorMode.K, workspace.iterator, d3, d3, sfa, sfd, None, None, + norm_const, expert_row_ends, alpha, None, None, None, rows_view(c, rows, n), + num_clusters, stream, + ) # fmt: skip + + @cute.jit + def launch_rubin( + a, b, sfb, sfa, c, d, sfd, expert_row_ends, alpha, norm_const, workspace, stream + ): + # The SM 10.7 kernel takes c ahead of d and no row scale. + weight = weight_view(b, n, k, experts, n_major=False) + d3 = rows_view(d, rows, d_cols) + kernel( + rows_view(a, rows, k), weight, sfb, cutlass.Int32(0), cutlass.Int32(0), + cutlass.Int64(0), OperandMajorMode.K, workspace.iterator, rows_view(c, rows, n), d3, + d3, sfa, sfd, None, None, norm_const, expert_row_ends, alpha, None, None, num_clusters, + stream, + ) # fmt: skip + + row_ends, alpha, _, workspace = tail + return compile_launch( + launch_rubin if is_sm107() else launch, + fp8_fake((rows, k), (1, 0)), + fp8_fake((experts, n, k), (2, 1, 0)), + scale_fake(experts * n, k), + scale_fake(rows, k), + fake_tensor(cutlass.BFloat16, (rows, n), (1, 0), 16), + fp8_fake((rows, d_cols), (1, 0)), + scale_fake(rows, d_cols), + row_ends, + alpha, + fake_tensor(cutlass.Float32, (1,), (0,), 4), + workspace, + ) + + +def _compile_backward_mxfp8(cfg: DispatchGemmConfig): + """MXFP8 FC2 data gradient with the columnwise forward weight [experts, k, n] read N-major, + SwiGLU backward in the epilogue, and the forward activation recomputed columnwise.""" + kernel, (rows, k, n, experts, num_clusters), tail = _prologue(cfg) + # The SM 10.7 kernel takes the GeGLU linear offset (unused by SwiGLU) ahead of the bias. + rubin = is_sm107() + + @cute.jit + def launch( + a, b, sfb, sfa, c, d, d_col, sfd_row, sfd_col, h, sfh_col, dprob, expert_row_ends, alpha, + prob, norm_const, workspace, stream, + ): # fmt: skip + weight = weight_view(b, n, k, experts, n_major=True) + kernel( + rows_view(a, rows, k), weight, sfb, cutlass.Int32(0), cutlass.Int32(0), + cutlass.Int64(0), OperandMajorMode.K, workspace.iterator, rows_view(c, rows, 2 * n), + rows_view(d, rows, 2 * n), rows_view(d_col, rows, 2 * n), sfa, sfd_row, sfd_col, None, + norm_const, expert_row_ends, alpha, alpha, prob_view(prob, rows), + prob_view(dprob, rows), *((cutlass.Float32(1.0),) if rubin else ()), None, + rows_view(h, rows, n), sfh_col, num_clusters, stream, + ) # fmt: skip + + row_ends, alpha, prob, workspace = tail + return compile_launch( + launch, + fp8_fake((rows, k), (1, 0)), + fp8_fake((experts, k, n), (2, 1, 0)), + scale_fake(experts * n, k), + scale_fake(rows, k), + fake_tensor(cutlass.BFloat16, (rows, 2 * n), (1, 0), 16), + fp8_fake((rows, 2 * n), (1, 0)), + fp8_fake((rows, 2 * n), (1, 0)), + scale_fake(rows, 2 * n), + scale_fake(rows, 2 * n), + fp8_fake((rows, n), (1, 0)), + scale_fake(rows, n), + fake_tensor(cutlass.Float32, (rows,), (0,), 16), + row_ends, + alpha, + prob, + fake_tensor(cutlass.Float32, (1,), (0,), 4), + workspace, + ) + + +_COMPILERS = { + (False, False): _compile_forward, + (True, False): _compile_backward, + (False, True): _compile_forward_mxfp8, + (True, True): _compile_backward_mxfp8, +} + + +def _config(rows, k, n, num_experts, num_clusters, backward, scaling_mode, rows_alignment, + device_layout): # fmt: skip + """Build a DispatchGemmConfig from the entry-point arguments.""" + return DispatchGemmConfig( + rows, k, n, num_experts, num_clusters, bool(backward), int(scaling_mode), rows_alignment, + bool(device_layout), + ) # fmt: skip + + +def get_ep_dispatch_gemm_workspace_layout( + rows, k, n, num_experts, num_clusters, backward, scaling_mode=DELAYED_TENSOR_SCALING, + rows_alignment=ROWS_PER_TILE, device_layout=False, +): # fmt: skip + """[total bytes, counter, signal, state] byte offsets of the workspace of this configuration.""" + return list(workspace_layout(_config( + rows, k, n, num_experts, num_clusters, backward, scaling_mode, rows_alignment, device_layout, + ))) # fmt: skip + + +def get_ep_dispatch_gemm_function( + fn_name, rows, k, n, num_experts, num_clusters, backward, scaling_mode=DELAYED_TENSOR_SCALING, + rows_alignment=ROWS_PER_TILE, device_layout=False, +) -> bool: # fmt: skip + """Compile and register the GEMM of this configuration as ``fn_name``; return whether it is.""" + cfg = _config( + rows, k, n, num_experts, num_clusters, backward, scaling_mode, rows_alignment, device_layout, + ) # fmt: skip + compile_fn = _COMPILERS[cfg.backward, cfg.mxfp8] + return register_function(fn_name, lambda: compile_fn(cfg), "EP dispatch grouped GEMM") diff --git a/transformer_engine/common/CuTeDSL/ep_gemm/requantize.py b/transformer_engine/common/CuTeDSL/ep_gemm/requantize.py new file mode 100644 index 00000000000..2cf7b2b94a6 --- /dev/null +++ b/transformer_engine/common/CuTeDSL/ep_gemm/requantize.py @@ -0,0 +1,331 @@ +# Copyright (c) 2022-2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# See LICENSE for license information. + +"""EP weight-gradient requantizer for the received rows. + +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. + +Rowwise MXFP8 rows ([rows, cols] E4M3 data with compact E8M0 scales, one per 32 columns of a row) +become columnwise MXFP8 ([rows, cols] E4M3 data with one scale per 32 rows of a column, scales +GEMM-swizzled per expert slab), the operand layout of the MXFP8 weight gradients. Each value is +dequantized and quantized again with TE's MXFP8 rule. Operands: ``codes``, ``row_scales``, +``col_codes``, ``col_scales``, ``expert_row_ends`` [experts] int32 (every slab a multiple of 128 +rows), optional ``signal`` [rows / ready_slot_rows] int32, stream. + +A launch is one CTA per (128-row, 256-column) tile of the receive capacity, a programmatic dependent +of the kernel before it that lets the kernel behind it start at once. CTAs past the last expert row +end exit; with ``signal``, a tile starts once the dispatch has set the slots of its rows. The grid +completes after the kernel before it. +""" + +import math +from dataclasses import dataclass +from typing import Optional + +import cuda.bindings.driver as cuda +import cutlass +from cutlass import Float32, Float8E4M3FN, Int32, Int64, Uint8, Uint16, Uint32, cute +from cutlass.experimental.primitives import cvt_packfloat_f32 + +from ._loader import ( + compile_launch, + SF_VEC_SIZE, + fake_tensor, + fp8_fake, + import_gemm_modules, + register_function, +) + +# A thread's rows of a 32-row block, its bytes per row and the warps per CTA. +ROWS_PER_THREAD, VEC, NUM_WARPS = 16, 8, 2 +# Lanes that share a group of VEC columns, each with its own rows of a block. +ROW_LANES = SF_VEC_SIZE // ROWS_PER_THREAD +# Columns per tile. +TILE_COLUMNS = 32 // ROW_LANES * VEC * NUM_WARPS +# Scale blocks along the rows per tile: one 128-row scale atom. +BLOCKS_PER_TILE = 4 +# Rows per tile. +TILE_ROWS = BLOCKS_PER_TILE * SF_VEC_SIZE +# fp32(1 / 448), the reciprocal of the largest E4M3 value. +E4M3_MAX_RCP = 1.0 / 448.0 +# 2^-127, the multiplier of E8M0 0. +E8M0_ZERO_MULTIPLIER = 2.0**-127 +# Order of a thread's four column pairs. Any order gives the same bytes; this one takes 128 +# registers, which fits 8 CTAs per SM. +PAIR_ORDER = (0, 3, 1, 2) + + +@dataclass(frozen=True) +class Mxfp8RequantConfig: + """Static configuration of one compiled MXFP8 requant launch.""" + + rows: int # receive capacity in rows + cols: int # columns + num_experts: int # local experts + ready_slot_rows: int = 0 # wait until signal[] is set for every slot of a tile's rows + + +class _Mxfp8RequantKernel: + """MXFP8 requant of a ``cfg`` operand, one CTA per tile.""" + + def __init__(self, cfg: Mxfp8RequantConfig): + self.cfg = cfg + if cfg.ready_slot_rows: + scheduler = import_gemm_modules("moe_streaming_input_block_tile_scheduler")[0] + self.poll_until_at_least = scheduler._poll_until_at_least + self.wait_slots_ready = scheduler.wait_slots_ready + + @cute.jit + def __call__( + self, + codes: cute.Pointer, + row_scales: cute.Pointer, + col_codes: cute.Pointer, + col_scales: cute.Pointer, + expert_row_ends: cute.Pointer, + signal: Optional[cute.Pointer], + stream: cuda.CUstream, + ): + self.tile_kernel(codes, row_scales, col_codes, col_scales, expert_row_ends, signal).launch( + grid=[self.cfg.rows // TILE_ROWS * (self.cfg.cols // TILE_COLUMNS), 1, 1], + block=[32 * NUM_WARPS, 1, 1], + stream=stream, + use_pdl=True, + ) + + @cute.kernel + def tile_kernel( + self, + codes: cute.Pointer, + row_scales: cute.Pointer, + col_codes: cute.Pointer, + col_scales: cute.Pointer, + expert_row_ends: cute.Pointer, + signal: Optional[cute.Pointer], + ): + """Tile ``blockIdx.x`` if it ends at or before the last expert end; CTA 0 waits for the + kernel before it at exit, so the grid completes after that one.""" + num_experts = self.cfg.num_experts + cute.arch.griddepcontrol_launch_dependents() + ends = cute.make_tensor(expert_row_ends, cute.make_layout((num_experts,))) + num_tiles = ends[num_experts - 1] // TILE_ROWS * (self.cfg.cols // TILE_COLUMNS) + bidx, _, _ = cute.arch.block_idx() + if bidx < num_tiles: + if cutlass.const_expr(signal is not None): + self.wait_rows_ready(signal, Int32(bidx)) + self.tile(codes, row_scales, col_codes, col_scales, expert_row_ends, Int32(bidx)) + if bidx == 0: + cute.arch.griddepcontrol_wait() + + @cute.jit + def wait_rows_ready(self, signal: cute.Pointer, tile: Int32): + """Wait until the dispatch has set the ``signal`` slots of the rows of tile ``tile``: warp 0 + polls them relaxed, then acquires them once.""" + slot_rows = self.cfg.ready_slot_rows + num_slots = max(TILE_ROWS // slot_rows, 1) + tidx, _, _ = cute.arch.thread_idx() + if tidx < 32: + slots = signal + tile // (self.cfg.cols // TILE_COLUMNS) * TILE_ROWS // slot_rows + for j in cutlass.range_constexpr((num_slots + 31) // 32): + self.poll_until_at_least(slots + cutlass.min(tidx + j * 32, num_slots - 1), 0) + self.wait_slots_ready(slots, Int32(num_slots)) + cute.arch.sync_threads() + + @cute.jit + def tile( + self, + codes: cute.Pointer, + row_scales: cute.Pointer, + col_codes: cute.Pointer, + col_scales: cute.Pointer, + expert_row_ends: cute.Pointer, + tile: Int32, + ): + """Requantize tile ``tile`` and write its scale words.""" + # pylint: disable=too-many-locals + R, V, COLS = ROWS_PER_THREAD, VEC, self.cfg.cols + num_experts = self.cfg.num_experts + tidx, _, _ = cute.arch.thread_idx() + # A thread owns VEC columns of the tile and every ROW_LANES-th row of each 32-row block. + lane_row, lane_column = tidx % ROW_LANES, tidx // ROW_LANES + row_group = tile // (COLS // TILE_COLUMNS) + column = (tile % (COLS // TILE_COLUMNS)) * TILE_COLUMNS + lane_column * V + warp_first_column = (tile % (COLS // TILE_COLUMNS)) * TILE_COLUMNS + (tidx // 32) * (R * V) + access = cute.make_copy_atom(cute.nvgpu.CopyUniversalOp(), Uint16, num_bits_per_copy=8 * V) + r_codes = cute.make_rmem_tensor((V // 2, R), Uint16) + r_out = cute.make_rmem_tensor((V // 2, R), Uint16) + pair_row, pair_broadcast = cute.make_layout((2,)), cute.make_layout((2,), stride=(0,)) + codes_e4m3 = cute.recast_tensor(r_codes, Float8E4M3FN) + out_e4m3 = cute.recast_tensor(r_out, Float8E4M3FN) + r_values = cute.make_rmem_tensor((2, R), Float32) + r_scales = cute.make_rmem_tensor((R,), Uint8) + row_multiplier_bits = cute.make_rmem_tensor((R,), Int32) + row_multiplier = cute.recast_tensor(row_multiplier_bits, Float32) + multiplier_bits = cute.make_rmem_tensor((2,), Int32) + multiplier = cute.recast_tensor(multiplier_bits, Float32) + scaled_amax = cute.make_rmem_tensor((2,), Float32) + # One word per column pair: this lane's column of the pair, one scale byte per 32-row block. + packed = cute.make_rmem_tensor((V // 2,), Uint32) + packed.fill(0) + for block in cutlass.range(BLOCKS_PER_TILE, unroll=1): + first_row = Int64(row_group) * TILE_ROWS + block * SF_VEC_SIZE + lane_row + rows = cute.make_layout((V // 2, R), stride=(1, ROW_LANES * COLS // 2)) + offset = cute.assume(first_row * COLS + column, divby=V) + cute.copy( + access, + cute.make_tensor(cute.recast_ptr(codes + offset, dtype=Uint16), rows), + r_codes, + ) + # Prefetch the next block's codes and row scales into L2. + if block < BLOCKS_PER_TILE - 1: + next_row = Int64(row_group) * TILE_ROWS + (block + 1) * SF_VEC_SIZE + tidx % 32 + cute.arch.prefetch( + (codes + (next_row * COLS + warp_first_column)).llvm_ptr, cache_level="L2" + ) + cute.arch.prefetch( + ( + row_scales + + (next_row * (COLS // SF_VEC_SIZE) + warp_first_column // SF_VEC_SIZE) + ).llvm_ptr, + cache_level="L2", + ) + cute.autovec_copy( + cute.make_tensor( + row_scales + (first_row * (COLS // SF_VEC_SIZE) + column // SF_VEC_SIZE), + cute.make_layout((R,), stride=(ROW_LANES * (COLS // SF_VEC_SIZE),)), + ), + r_scales, + ) + # 2^(s - 127) from its bits; s = 0 gives 2^-127 and s = 255 NaN. + for i in cutlass.range_constexpr(R): + row_multiplier_bits[i] = Int32(r_scales[i]) << 23 + row_multiplier[i] = cute.arch.fmax(row_multiplier[i], E8M0_ZERO_MULTIPLIER) + row_multiplier_bits[i] = row_multiplier_bits[i] | ( + ((Int32(r_scales[i]) + 1) >> 8) << 22 + ) + for q in PAIR_ORDER: + for i in cutlass.range_constexpr(R): + pair_codes = cute.make_tensor(codes_e4m3.iterator + 2 * q + V * i, pair_row) + pair_row_multiplier = cute.make_tensor( + row_multiplier.iterator + i, pair_broadcast + ) + cute.make_tensor(r_values.iterator + 2 * i, pair_row).store( + pair_codes.load().to(Float32) * pair_row_multiplier.load() + ) + for v in cutlass.range_constexpr(2): + # The amax ignores NaN; the column's other rows sit in the neighboring lanes. + amax = Float32(0.0) + for i in cutlass.range_constexpr(R): + amax = cute.arch.fmax(amax, abs(r_values[v, i])) + for k in cutlass.range_constexpr(int(math.log2(ROW_LANES))): + amax = cute.arch.fmax( + amax, cute.arch.shuffle_sync_bfly(amax, offset=1 << k) + ) + scaled_amax[v] = amax * E4M3_MAX_RCP + # E8M0 of both columns of the pair, rounded up, the first column in the high byte. + pair = cvt_packfloat_f32( + scaled_amax[0], scaled_amax[1], 0, "ue8m0x2", rnd="rp", sat="satfinite" + ) + packed[q] = (packed[q] >> 8) | (Uint32(pair >> (8 * (1 - lane_row))) << 24) + inverse = 0xFEFE - pair + for h in cutlass.range_constexpr(2): + multiplier_bits[h] = cutlass.max( + ((inverse >> (8 * (1 - h))) & 0xFF) << 23, Int32(0x00400000) + ) + for i in cutlass.range_constexpr(R): + pair_values = cute.make_tensor(r_values.iterator + 2 * i, pair_row) + cute.make_tensor(out_e4m3.iterator + 2 * q + V * i, pair_row).store( + (pair_values.load() * multiplier.load()).to(Float8E4M3FN) + ) + cute.copy( + access, + r_out, + cute.make_tensor(cute.recast_ptr(col_codes + offset, dtype=Uint16), rows), + ) + # The tile's expert by a branchless lower bound over the row ends, then its start row. + ends = cute.make_tensor(expert_row_ends, cute.make_layout((num_experts,))) + group_row = row_group * TILE_ROWS + expert, n = Int32(0), num_experts + for _ in cutlass.range_constexpr(int(math.ceil(math.log2(num_experts)))): + half = n // 2 + expert = cutlass.select_(ends[expert + half - 1] <= group_row, expert + half, expert) + n -= half + expert = cutlass.select_(ends[expert] <= group_row, expert + 1, expert) + if expert < num_experts: + start = cutlass.select_(expert > 0, ends[cutlass.max(expert - 1, Int32(0))], Int32(0)) + count = ends[expert] - start + local_group = Int64(row_group - start // TILE_ROWS) + # Int32 word of the expert's swizzled scales: its start, the 128-column atom, the + # 128-row group in it, the column in its 32 and which of the four 32-column groups. + c = column + lane_row + index = ( + Int64(start) * (COLS // 128) + + Int64(c // 128) * count + + local_group * 128 + + (c % 32) * 4 + + (c // 32) % 4 + ) + for j in cutlass.range_constexpr(V // 2): + word = cute.make_tensor( + col_scales + index + j * ROW_LANES * 4, cute.make_layout((1,)) + ) + word[0] = packed[j] + + +def _compile(cfg: Mxfp8RequantConfig): + """Compile the launch wrapper of ``cfg`` with TVM-FFI.""" + assert cfg.rows % TILE_ROWS == 0 and cfg.cols % TILE_COLUMNS == 0, (cfg.rows, cfg.cols) + slot_rows = cfg.ready_slot_rows + # A tile waits for whole slots: one, or the slots it spans; the capacity is whole slots. + assert not slot_rows or ( + (TILE_ROWS % slot_rows == 0 or slot_rows % TILE_ROWS == 0) and cfg.rows % slot_rows == 0 + ), (cfg.rows, slot_rows) + requant = _Mxfp8RequantKernel(cfg) + + @cute.jit + def launch(codes, row_scales, col_codes, col_scales, expert_row_ends, stream): + requant( + cute.recast_ptr(codes.iterator, dtype=Uint8), + cute.recast_ptr(row_scales.iterator, dtype=Uint8), + cute.recast_ptr(col_codes.iterator, dtype=Uint8), + cute.recast_ptr(col_scales.iterator, dtype=Int32), + expert_row_ends.iterator, + None, + stream, + ) + + @cute.jit + def launch_ready(codes, row_scales, col_codes, col_scales, expert_row_ends, signal, stream): + requant( + cute.recast_ptr(codes.iterator, dtype=Uint8), + cute.recast_ptr(row_scales.iterator, dtype=Uint8), + cute.recast_ptr(col_codes.iterator, dtype=Uint8), + cute.recast_ptr(col_scales.iterator, dtype=Int32), + expert_row_ends.iterator, + signal.iterator, + stream, + ) + + rows, cols = cfg.rows, cfg.cols + scales = rows * cols // SF_VEC_SIZE + signal_fake = (fake_tensor(Int32, (rows // slot_rows,), (0,), 4),) if slot_rows else () + return compile_launch( + launch_ready if slot_rows else launch, + fp8_fake((rows, cols), (1, 0)), + fake_tensor(cutlass.Float8E8M0FNU, (scales,), (0,), 16), + fp8_fake((rows, cols), (1, 0)), + fake_tensor(cutlass.Float8E8M0FNU, (scales,), (0,), 16), + fake_tensor(Int32, (cfg.num_experts,), (0,), 16), + *signal_fake, + ) + + +def get_ep_requant_function(fn_name, rows, cols, num_experts, ready_slot_rows=0) -> bool: + """Compile and register the requant of this configuration as ``fn_name``; return whether it + is. ``ready_slot_rows`` > 0: the function takes ``signal`` before the stream.""" + cfg = Mxfp8RequantConfig(rows, cols, num_experts, ready_slot_rows) + return register_function(fn_name, lambda: _compile(cfg), "EP MXFP8 requant") diff --git a/transformer_engine/common/CuTeDSL/ep_gemm/wgrad_gemm.py b/transformer_engine/common/CuTeDSL/ep_gemm/wgrad_gemm.py new file mode 100644 index 00000000000..2137dea46fe --- /dev/null +++ b/transformer_engine/common/CuTeDSL/ep_gemm/wgrad_gemm.py @@ -0,0 +1,337 @@ +# Copyright (c) 2022-2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# See LICENSE for license information. + +"""Grouped weight gradient chained into the overlapped backward (SM 10.0, 10.3 and 10.7). + +``weight_grad[e] = grad[rows of e]^T x[rows of e]`` per expert: ``grad`` [rows, m] and ``x`` +[rows, n] BF16, or MXFP8 columnwise data with their GEMM-swizzled columnwise scales, +``weight_grad`` [experts, m, n] BF16 or FP32, written or added to. Operands: ``expert_row_ends`` +[experts] int32, ``workspace`` uint8, stream; ``signal`` [rows / slot rows] int32 with +``ready_slot_rows`` (BF16 only). + +Each launch is a persistent grid that claims output tiles from a counter in ``workspace``, so +launches sharing one workspace split the tiles. It is a programmatic dependent of the kernel +before it and lets the kernel behind it start early. MXFP8 launches of an added or FP32 weight +gradient, and on SM 10.7 of a written BF16 one with long experts, read per-expert descriptors +that a ``descriptors_only`` launch writes into ``workspace`` ahead of them; the others read global +descriptors. +""" + +import functools +from dataclasses import dataclass, field + +import cutlass +from cutlass import cute + +from ._loader import ( + compile_launch, + device_compute_capability, + CLUSTER_MN, + DELAYED_TENSOR_SCALING, + MMA_TILER_MN, + MXFP8_1D_SCALING, + SF_VEC_SIZE, + fake_tensor, + fp8_fake, + import_gemm_modules, + is_sm107, + register_function, + scale_fake, +) + + +@dataclass(frozen=True) +class WgradConfig: + """Static configuration of one compiled weight-gradient launch.""" + + rows: int # receive capacity in rows + m: int # columns of grad, rows of each expert's weight gradient + n: int # columns of x, columns of each expert's weight gradient + num_experts: int # local experts + num_clusters: int # persistent clusters + fp32_out: bool = False # FP32 instead of BF16 weight gradient + accumulate: bool = False # add to the weight gradient instead of writing it + wait_primary_at_start: bool = False # wait for the kernel before it ahead of any load + ready_slot_rows: int = 0 # wait until signal[] is set for every slot of these rows + scaling_mode: int = DELAYED_TENSOR_SCALING # operand scaling (NVTEScalingMode) + descriptors_only: bool = False # MXFP8: write the per-expert descriptors, no GEMM + rows_alignment: int = 0 # rows per expert slab are a multiple of it + routed_rows: int = 0 # rows a rank receives on average + # Kernels, workspace layouts and compiled functions are specific to the device architecture. + capability: tuple = field(default_factory=device_compute_capability) + + @property + def mxfp8(self) -> bool: + """Whether the operands are MXFP8 rather than BF16.""" + return self.scaling_mode == MXFP8_1D_SCALING + + +def _mxfp8_kernels(): + """(per-expert descriptor, reuse, dense or None, moe_utils) MXFP8 kernel classes of the + device. SM 10.7 has no dense one.""" + if is_sm107(): + stock, reuse, moe_utils = import_gemm_modules( + "moe_blockscaled_grouped_gemm_wgrad_rubin", + "moe_blockscaled_grouped_gemm_wgrad_reuse_rubin", + ) + return ( + stock.BlockScaledMoEGroupedGemmWgradRubinKernel, + reuse.BlockScaledMoEGroupedGemmWgradReuseRubinKernel, + None, + moe_utils, + ) + blockscaled, dense, reuse, moe_utils = import_gemm_modules( + "moe_blockscaled_grouped_gemm_wgrad", + "moe_blockscaled_grouped_gemm_wgrad_dense", + "moe_blockscaled_grouped_gemm_wgrad_reuse", + ) + return ( + blockscaled.BlockScaledMoEGroupedGemmWgradKernel, + reuse.BlockScaledMoEGroupedGemmWgradReuseKernel, + dense.BlockScaledMoEGroupedGemmWgradDenseKernel, + moe_utils, + ) + + +def _global_descriptor_kernel(cfg: WgradConfig): + """Class of an MXFP8 weight gradient written in BF16 that reads global descriptors: the one + keeping A across the N tiles of an expert when the experts are short on average, else the + dense one; None for the others.""" + if cfg.accumulate or cfg.fp32_out: + return None + _, reuse, dense, _ = _mxfp8_kernels() + # Each weight gradient picks for its own shape; EPCompOverlap keeps A only when both can, so + # with ffn 256, 1280 or 1792 it runs the first one dense too. + if reuse.can_implement(cfg.m, cfg.n, cfg.rows_alignment, cfg.routed_rows, cfg.num_experts): + return reuse + return dense + + +def reads_descriptors(cfg: WgradConfig) -> bool: + """Whether the launches of ``cfg`` read the per-expert descriptors of a ``descriptors_only`` + launch.""" + return cfg.mxfp8 and _global_descriptor_kernel(cfg) is None + + +def build_kernel(cfg: WgradConfig): + """Kernel for ``cfg``: 256 x 512 output tiles where they divide a BF16 weight gradient that is + written, else 256 x 256 tiles. An MXFP8 weight gradient written in BF16 keeps A across the N + tiles of an expert when the experts are short on average, else reads A, B and the scales + through global descriptors (per-expert ones on SM 10.7).""" + if cfg.mxfp8: + stock, _, _, moe_utils = _mxfp8_kernels() + kernel = _global_descriptor_kernel(cfg) + if kernel is not None: + # The SM 10.7 reuse kernel sizes its A ring to the average padded expert. + padded_rows = cfg.routed_rows + cfg.num_experts * cfg.rows_alignment // 2 + a_stages = ( + {"a_stages": kernel.a_stages_for(padded_rows, cfg.num_experts)} + if is_sm107() + else {} + ) + return kernel( + sf_vec_size=SF_VEC_SIZE, + acc_dtype=cutlass.Float32, + use_2cta_instrs=True, + mma_tiler_mn=MMA_TILER_MN, + cluster_shape_mn=CLUSTER_MN, + expert_cnt=cfg.num_experts, + weight_mode=moe_utils.MoEWeightMode.DENSE, + input_order=moe_utils.WGradInputOrder.Tensor2D, + tile_claim=moe_utils.WgradTileClaim.COUNTER, + use_pdl=True, + wait_primary_at_start=cfg.wait_primary_at_start, + **a_stages, + ) + if is_sm107() and cfg.rows <= 256: + # The SM 10.7 kernel faults when the K extent is a single 256-row tile. + raise ValueError( + "The SM 10.7 MXFP8 weight gradient that is added, FP32 or of long experts needs " + "a receive capacity above 256 rows." + ) + return stock( + sf_vec_size=SF_VEC_SIZE, + acc_dtype=cutlass.Float32, + use_2cta_instrs=True, + mma_tiler_mn=MMA_TILER_MN, + cluster_shape_mn=CLUSTER_MN, + accumulate_on_output=cfg.accumulate, + expert_cnt=cfg.num_experts, + weight_mode=moe_utils.MoEWeightMode.DENSE, + input_order=moe_utils.WGradInputOrder.Tensor2D, + tile_claim=moe_utils.WgradTileClaim.COUNTER, + descriptors_only=cfg.descriptors_only, + descriptors_prebuilt=not cfg.descriptors_only, + use_pdl=not cfg.descriptors_only, + wait_primary_at_start=cfg.wait_primary_at_start, + ) + if is_sm107(): + # Both kernels, sized for the SM 10.7 shared memory. + names = ("moe_grouped_gemm_sm107",) * 2 + else: + names = ("moe_grouped_gemm_wgrad", "moe_grouped_gemm_wgrad_wide") + stock, wide, moe_utils = import_gemm_modules(*names) + options = { + "expert_cnt": cfg.num_experts, + "tile_claim": moe_utils.WgradTileClaim.COUNTER, + } + wide_kernel = wide.MoEGroupedGemmWgradWideBF16Kernel + if not (cfg.accumulate or cfg.fp32_out) and wide_kernel.can_implement(cfg.m, cfg.n): + return wide_kernel( + use_pdl=True, + wait_primary_at_start=cfg.wait_primary_at_start, + ready_slot_rows=cfg.ready_slot_rows, + **options, + ) + return stock.MoEGroupedGemmWgradBF16Kernel( + acc_dtype=cutlass.Float32, + use_2cta_instrs=True, + mma_tiler_mn=MMA_TILER_MN, + cluster_shape_mn=CLUSTER_MN, + accumulate_on_output=cfg.accumulate, + weight_mode=moe_utils.MoEWeightMode.DENSE, + input_order=moe_utils.WGradInputOrder.Tensor2D, + **options, + ) + + +@functools.lru_cache(maxsize=None) +def workspace_layout(cfg: WgradConfig): + """Total bytes and byte offset of the tile counter of ``cfg``'s workspace.""" + kernel = build_kernel(cfg) + return kernel.get_workspace_bytes(), kernel.get_desc_workspace_bytes() + + +def _compile(cfg: WgradConfig): + """Compile the launch wrapper of ``cfg`` with TVM-FFI.""" + kernel = build_kernel(cfg) + rows, m, n, experts, num_clusters = cfg.rows, cfg.m, cfg.n, cfg.num_experts, cfg.num_clusters + + def views(grad, x, weight_grad): + # grad^T as (m, rows), x as (rows, n), weight_grad as (experts, m, n). + return ( + cute.make_tensor(grad.iterator, cute.make_layout((m, rows), stride=(1, m))), + cute.make_tensor(x.iterator, cute.make_layout((rows, n), stride=(n, 1))), + cute.make_tensor( + weight_grad.iterator, cute.make_layout((experts, m, n), stride=(m * n, n, 1)) + ), + ) + + out_fake = fake_tensor( + cutlass.Float32 if cfg.fp32_out else cutlass.BFloat16, (experts, m, n), (2, 1, 0), 16 + ) + tail = ( + fake_tensor(cutlass.Int32, (experts,), (0,), 16), + fake_tensor(cutlass.Uint8, (workspace_layout(cfg)[0],), (0,), 128), + ) + if cfg.mxfp8: + k_scales = rows // SF_VEC_SIZE + + @cute.jit + def launch_mxfp8( + grad, x, grad_scales, x_scales, weight_grad, expert_row_ends, workspace, stream + ): + a, b, out = views(grad, x, weight_grad) + # Columnwise scales as (columns, rows / 32) over the per-expert swizzled atoms. + sfa = cute.make_tensor( + grad_scales.iterator, cute.make_layout((m, k_scales), stride=(k_scales, 1)) + ) + sfb = cute.make_tensor( + x_scales.iterator, cute.make_layout((n, k_scales), stride=(k_scales, 1)) + ) + kernel(a, b, sfa, sfb, out, expert_row_ends, workspace, num_clusters, stream) + + return compile_launch( + launch_mxfp8, + fp8_fake((rows, m), (1, 0)), + fp8_fake((rows, n), (1, 0)), + scale_fake(rows, m), + scale_fake(rows, n), + out_fake, + *tail, + ) + + fakes = ( + fake_tensor(cutlass.BFloat16, (rows, m), (1, 0), 16), + fake_tensor(cutlass.BFloat16, (rows, n), (1, 0), 16), + out_fake, + *tail, + ) + if cfg.ready_slot_rows: + # Only the wide kernel waits on the signal. The stock kernel, chosen for FP32 or + # accumulated gradients and shapes the wide one cannot implement, is launched without PDL, + # so it starts after the signaling kernels complete and has no flags to wait for. + wait_on_signal = getattr(kernel, "ready_slot_rows", 0) > 0 + + @cute.jit + def launch_ready(grad, x, weight_grad, expert_row_ends, workspace, signal, stream): + a, b, out = views(grad, x, weight_grad) + if cutlass.const_expr(wait_on_signal): + kernel( + a, b, out, expert_row_ends, workspace, num_clusters, stream, None, + signal.iterator, + ) # fmt: skip + else: + kernel(a, b, out, expert_row_ends, workspace, num_clusters, stream) + + return compile_launch( + launch_ready, + *fakes, + fake_tensor(cutlass.Int32, (rows // cfg.ready_slot_rows,), (0,), 4), + ) + + @cute.jit + def launch(grad, x, weight_grad, expert_row_ends, workspace, stream): + a, b, out = views(grad, x, weight_grad) + kernel(a, b, out, expert_row_ends, workspace, num_clusters, stream) + + return compile_launch(launch, *fakes) + + +def _config( + rows, m, n, num_experts, num_clusters, fp32_out, accumulate, wait_primary_at_start, + ready_slot_rows, scaling_mode, descriptors_only, rows_alignment, routed_rows, +): # fmt: skip + """Build a WgradConfig from the entry-point arguments.""" + return WgradConfig( + rows, m, n, num_experts, num_clusters, bool(fp32_out), bool(accumulate), + bool(wait_primary_at_start), ready_slot_rows, int(scaling_mode), bool(descriptors_only), + rows_alignment, routed_rows, + ) # fmt: skip + + +def get_ep_wgrad_workspace_layout( + rows, m, n, num_experts, num_clusters, fp32_out, accumulate, wait_primary_at_start, + ready_slot_rows, scaling_mode, descriptors_only, rows_alignment, routed_rows, +): # fmt: skip + """[total bytes, counter offset] of the workspace of this configuration.""" + return list(workspace_layout(_config( + rows, m, n, num_experts, num_clusters, fp32_out, accumulate, wait_primary_at_start, + ready_slot_rows, scaling_mode, descriptors_only, rows_alignment, routed_rows, + ))) # fmt: skip + + +def get_ep_wgrad_reads_descriptors( + rows, m, n, num_experts, num_clusters, fp32_out, accumulate, wait_primary_at_start, + ready_slot_rows, scaling_mode, descriptors_only, rows_alignment, routed_rows, +) -> bool: # fmt: skip + """Whether the launches of this configuration read the per-expert descriptors of a + ``descriptors_only`` launch.""" + return reads_descriptors(_config( + rows, m, n, num_experts, num_clusters, fp32_out, accumulate, wait_primary_at_start, + ready_slot_rows, scaling_mode, descriptors_only, rows_alignment, routed_rows, + )) # fmt: skip + + +def get_ep_wgrad_function( + fn_name, rows, m, n, num_experts, num_clusters, fp32_out, accumulate, wait_primary_at_start, + ready_slot_rows, scaling_mode, descriptors_only, rows_alignment, routed_rows, +) -> bool: # fmt: skip + """Compile and register the weight gradient of this configuration as ``fn_name``; return + whether it is.""" + cfg = _config( + rows, m, n, num_experts, num_clusters, fp32_out, accumulate, wait_primary_at_start, + ready_slot_rows, scaling_mode, descriptors_only, rows_alignment, routed_rows, + ) # fmt: skip + return register_function(fn_name, lambda: _compile(cfg), "EP weight-gradient grouped GEMM") diff --git a/transformer_engine/common/CuTeDSL/utils.py b/transformer_engine/common/CuTeDSL/utils.py index 9f80a2b5c42..b121fdc91aa 100644 --- a/transformer_engine/common/CuTeDSL/utils.py +++ b/transformer_engine/common/CuTeDSL/utils.py @@ -64,6 +64,12 @@ def check(result): return (0, 0) +def tvm_ffi_function(compiled): + """The TVM-FFI function of a kernel compiled with ``--enable-tvm-ffi``, for registration.""" + native = getattr(compiled, "__tvm_ffi_object__", lambda: None)() + return native if native is not None else compiled + + def str_to_cutlass_dtype(dtype_str: str): """Convert a string dtype to a cutlass dtype, or None if unknown.""" return _CUTLASS_DTYPE_FROM_STR.get(dtype_str, None) diff --git a/transformer_engine/common/ep/ep_api.cpp b/transformer_engine/common/ep/ep_api.cpp index bc85c1e00f5..d1b204c4aa3 100644 --- a/transformer_engine/common/ep/ep_api.cpp +++ b/transformer_engine/common/ep/ep_api.cpp @@ -53,15 +53,24 @@ Cfg normalize_ep_config(const Cfg* user, size_t min_size, const char* name) { } } // namespace +NVTEEpLayerConfig transformer_engine::ep::normalize_layer_config(const NVTEEpLayerConfig* cfg) { + return normalize_ep_config(cfg, kLayerConfigMinSize, "layer_cfg"); +} + void nvte_ep_initialize(void* ep_comm, const NVTEEpGroupConfig* group_config) { + NVTE_API_CALL(nvte_ep_initialize); NVTE_CHECK(ep_comm != nullptr, "ep_comm must not be null"); NVTEEpGroupConfig cfg = normalize_ep_config(group_config, kGroupConfigMinSize, "group_config"); EPBackend::initialize(static_cast(ep_comm), cfg); } -void nvte_ep_shutdown(void) { EPBackend::shutdown(); } +void nvte_ep_shutdown(void) { + NVTE_API_CALL(nvte_ep_shutdown); + EPBackend::shutdown(); +} size_t nvte_ep_handle_mem_size(const NVTEEpLayerConfig* layer_cfg) { + NVTE_API_CALL(nvte_ep_handle_mem_size); NVTEEpLayerConfig cfg = normalize_ep_config(layer_cfg, kLayerConfigMinSize, "layer_cfg"); return EPBackend::handle_mem_size(cfg); } @@ -69,6 +78,7 @@ size_t nvte_ep_handle_mem_size(const NVTEEpLayerConfig* layer_cfg) { void nvte_ep_prepare(NVTETensor handle_mem, NVTETensor topk_idx, NVTETensor recv_tokens_per_expert, NVTETensor total_recv_tokens_per_rank, const NVTEEpLayerConfig* layer_cfg, cudaStream_t stream) { + NVTE_API_CALL(nvte_ep_prepare); NVTEEpLayerConfig cfg = normalize_ep_config(layer_cfg, kLayerConfigMinSize, "layer_cfg"); EPBackend::get().prepare(handle_mem, topk_idx, recv_tokens_per_expert, total_recv_tokens_per_rank, cfg, stream); @@ -80,10 +90,11 @@ void nvte_ep_dispatch(NVTETensor handle_mem, NVTETensor topk_idx, NVTETensor tok NVTECommWindow recv_tokens_win, NVTETensor recv_topk_weights, NVTECommWindow recv_topk_weights_win, const NVTEEpLayerConfig* layer_cfg, cudaStream_t stream) { + NVTE_API_CALL(nvte_ep_dispatch); NVTEEpLayerConfig cfg = normalize_ep_config(layer_cfg, kLayerConfigMinSize, "layer_cfg"); EPBackend::get().dispatch(handle_mem, topk_idx, tokens, tokens_win, topk_weights, topk_weights_win, recv_tokens, recv_tokens_win, recv_topk_weights, - recv_topk_weights_win, cfg, stream); + recv_topk_weights_win, /*dispatch_signal=*/nullptr, cfg, stream); } void nvte_ep_dispatch_v2(NVTETensor handle_mem, NVTETensor topk_idx, NVTETensor tokens, @@ -92,6 +103,7 @@ void nvte_ep_dispatch_v2(NVTETensor handle_mem, NVTETensor topk_idx, NVTETensor NVTECommWindow recv_tokens_win, NVTETensor recv_topk_weights, NVTECommWindow recv_topk_weights_win, const NVTEEpLayerConfig* layer_cfg, cudaStream_t stream) { + NVTE_API_CALL(nvte_ep_dispatch_v2); nvte_ep_dispatch(handle_mem, topk_idx, tokens, tokens_win, topk_weights, topk_weights_win, recv_tokens, recv_tokens_win, recv_topk_weights, recv_topk_weights_win, layer_cfg, stream); @@ -105,22 +117,27 @@ void nvte_ep_prepare_and_dispatch(NVTETensor handle_mem, NVTETensor topk_idx, NV NVTETensor recv_tokens_per_expert, NVTETensor total_recv_tokens_per_rank, const NVTEEpLayerConfig* layer_cfg, cudaStream_t stream) { + NVTE_API_CALL(nvte_ep_prepare_and_dispatch); NVTEEpLayerConfig cfg = normalize_ep_config(layer_cfg, kLayerConfigMinSize, "layer_cfg"); EPBackend::get().prepare_and_dispatch( handle_mem, topk_idx, tokens, tokens_win, topk_weights, topk_weights_win, recv_tokens, recv_tokens_win, recv_topk_weights, recv_topk_weights_win, recv_tokens_per_expert, - total_recv_tokens_per_rank, cfg, stream); + total_recv_tokens_per_rank, /*expert_token_offsets=*/nullptr, /*dispatch_signal=*/nullptr, + cfg, stream); } void nvte_ep_combine(NVTETensor handle_mem, NVTETensor expert_out, NVTECommWindow expert_out_win, NVTETensor result, const NVTEEpLayerConfig* layer_cfg, cudaStream_t stream) { + NVTE_API_CALL(nvte_ep_combine); NVTEEpLayerConfig cfg = normalize_ep_config(layer_cfg, kLayerConfigMinSize, "layer_cfg"); - EPBackend::get().combine(handle_mem, expert_out, expert_out_win, result, cfg, stream); + EPBackend::get().combine(handle_mem, expert_out, expert_out_win, result, + /*combine_signal=*/nullptr, cfg, stream); } void nvte_ep_combine_v2(NVTETensor handle_mem, NVTETensor expert_out, NVTECommWindow expert_out_win, NVTETensor result, const NVTEEpLayerConfig* layer_cfg, cudaStream_t stream) { + NVTE_API_CALL(nvte_ep_combine_v2); nvte_ep_combine(handle_mem, expert_out, expert_out_win, result, layer_cfg, stream); } @@ -128,16 +145,18 @@ void nvte_ep_dispatch_bwd(NVTETensor handle_mem, NVTETensor grad, NVTECommWindow NVTETensor g_recv_topk_weights, NVTECommWindow g_recv_topk_weights_win, NVTETensor grad_tokens, NVTETensor grad_topk_weights, const NVTEEpLayerConfig* layer_cfg, cudaStream_t stream) { + NVTE_API_CALL(nvte_ep_dispatch_bwd); NVTEEpLayerConfig cfg = normalize_ep_config(layer_cfg, kLayerConfigMinSize, "layer_cfg"); EPBackend::get().dispatch_bwd(handle_mem, grad, grad_win, g_recv_topk_weights, - g_recv_topk_weights_win, grad_tokens, grad_topk_weights, cfg, - stream); + g_recv_topk_weights_win, grad_tokens, grad_topk_weights, + /*combine_signal=*/nullptr, cfg, stream); } void nvte_ep_dispatch_bwd_v2(NVTETensor handle_mem, NVTETensor grad, NVTECommWindow grad_win, NVTETensor g_recv_topk_weights, NVTECommWindow g_recv_topk_weights_win, NVTETensor grad_tokens, NVTETensor grad_topk_weights, const NVTEEpLayerConfig* layer_cfg, cudaStream_t stream) { + NVTE_API_CALL(nvte_ep_dispatch_bwd_v2); nvte_ep_dispatch_bwd(handle_mem, grad, grad_win, g_recv_topk_weights, g_recv_topk_weights_win, grad_tokens, grad_topk_weights, layer_cfg, stream); } @@ -145,14 +164,16 @@ void nvte_ep_dispatch_bwd_v2(NVTETensor handle_mem, NVTETensor grad, NVTECommWin void nvte_ep_combine_bwd(NVTETensor handle_mem, NVTETensor grad, NVTECommWindow grad_win, NVTETensor grad_expert_out, NVTECommWindow grad_expert_out_win, const NVTEEpLayerConfig* layer_cfg, cudaStream_t stream) { + NVTE_API_CALL(nvte_ep_combine_bwd); NVTEEpLayerConfig cfg = normalize_ep_config(layer_cfg, kLayerConfigMinSize, "layer_cfg"); EPBackend::get().combine_bwd(handle_mem, grad, grad_win, grad_expert_out, grad_expert_out_win, - cfg, stream); + /*dispatch_signal=*/nullptr, cfg, stream); } void nvte_ep_combine_bwd_v2(NVTETensor handle_mem, NVTETensor grad, NVTECommWindow grad_win, NVTETensor grad_expert_out, NVTECommWindow grad_expert_out_win, const NVTEEpLayerConfig* layer_cfg, cudaStream_t stream) { + NVTE_API_CALL(nvte_ep_combine_bwd_v2); nvte_ep_combine_bwd(handle_mem, grad, grad_win, grad_expert_out, grad_expert_out_win, layer_cfg, stream); } diff --git a/transformer_engine/common/ep/ep_backend.cpp b/transformer_engine/common/ep/ep_backend.cpp index 6642dc435c0..1dbff30af45 100644 --- a/transformer_engine/common/ep/ep_backend.cpp +++ b/transformer_engine/common/ep/ep_backend.cpp @@ -102,6 +102,51 @@ inline ncclEpTensor_t make_nccl_ep_tensor(const NVTETensor t, NVTEShape& shape_o return desc; } +// NCCL EP first published the overlap completion signal in 0.3.0. An older runtime loaded through +// NCCL_EP_HOME ignores the signal output field and returns success without ever raising the flags, +// leaving the overlapped GEMM waiting forever. Reject a signaled op on such a runtime up front. +void require_signal_capable(const char* call) { + constexpr int kMinSignalVersion = 300; // NCCL EP 0.3.0 + const int version = nccl_ep::runtime_version(); + NVTE_CHECK(version >= kMinSignalVersion, "The loaded NCCL EP runtime ", version / 10000, ".", + (version / 100) % 100, ".", version % 100, + " does not support the overlap completion signal required by the ", call, + "; it needs NCCL EP >= 0.3.0. Use a compatible runtime or disable the overlap."); +} + +// Signal descriptor of a dispatch or combine call; attach() returns the NCCL EP signal to wire into +// the call, or nullptr when no signal is given. +struct SignalDesc { + NVTEShape shape; + ncclEpTensor_t desc = NCCL_EP_TENSOR_INIT; + ncclEpSignal_t sig = NCCL_EP_SIGNAL_INIT; + + ncclEpSignal_t* attach(const EpSignal* signal, ncclEpSignalUnit_t unit, const char* call) { + if (signal == nullptr) { + return nullptr; + } + require_signal_capable(call); + NVTE_CHECK( + nvte_tensor_type(signal->ready) == kNVTEInt32 && nvte_tensor_shape(signal->ready).ndim == 1, + call, " signal must be a 1D int32 tensor"); + NVTE_CHECK(signal->granularity > 0, call, " signal granularity must be positive"); + desc = make_nccl_ep_tensor(signal->ready, shape); + sig.granularity = static_cast(signal->granularity); + sig.unit = unit; + sig.signal = &desc; + return &sig; + } +}; + +// NCCL EP rejects a signaled call it cannot serve with ncclInvalidUsage, e.g. on a group of more +// than one LSA team (NVLink domain). +void check_signaled_call(ncclResult_t status, bool signaled, const char* call) { + NVTE_CHECK(!signaled || status != ncclInvalidUsage, "NCCL EP rejected the signaled ", call, + " (invalid usage): the overlapped EP ops need the EP group within one NVLink domain " + "(one LSA team); NCCL EP prints the cause to stderr"); + NVTE_CHECK_NCCL(status); +} + int current_device() { int device = 0; NVTE_CHECK_CUDA(cudaGetDevice(&device)); @@ -187,6 +232,11 @@ void EPBackend::validate_config(const NVTEEpGroupConfig& config) { ") must be divisible by ep_size (", config.ep_size, ")"); NVTE_CHECK(config.num_comm_sms >= 0, "num_comm_sms must be >= 0 (0 = auto), got ", config.num_comm_sms); + NVTE_CHECK(config.dispatch_fwd_num_sms >= 0 && config.combine_fwd_num_sms >= 0 && + config.dispatch_bwd_num_sms >= 0 && config.combine_bwd_num_sms >= 0, + "dispatch/combine fwd/bwd num_sms must be >= 0 (0 = inherit), got ", + config.dispatch_fwd_num_sms, ", ", config.combine_fwd_num_sms, ", ", + config.dispatch_bwd_num_sms, ", ", config.combine_bwd_num_sms); const int sm = cuda::sm_arch(); NVTE_CHECK(sm >= 90, "NCCL EP requires SM_90+ (Hopper or later), but current device is SM_", sm); @@ -336,9 +386,43 @@ void EPBackend::init(ncclComm_t ep_comm, NVTEEpGroupConfig group_config) { // Default the dispatch/combine (comm) kernels to 32 SMs, clamped to the device SM count. constexpr int kDefaultCommSms = 32; const int device_sms = cuda::sm_count(); - cfg.max_num_sms = group_config.num_comm_sms > 0 - ? static_cast(group_config.num_comm_sms) - : static_cast(std::min(kDefaultCommSms, device_sms)); + // Resolve the per-call counts here, so that the overlapped GEMMs (group_config()) and NCCL EP + // use the same ones: forward inherits num_comm_sms, backward the forward count of its kind. The + // per-call counts cover every communication kernel, so leave NCCL EP's shared budget on AUTO; + // setting it would also throttle the local permute kernels, which want the whole device. + const auto inherit = [](int num_sms, int fallback) { return num_sms > 0 ? num_sms : fallback; }; + const int comm_sms = group_config.num_comm_sms > 0 ? group_config.num_comm_sms + : std::min(kDefaultCommSms, device_sms); + const int dispatch_fwd = inherit(group_config.dispatch_fwd_num_sms, comm_sms); + const int combine_fwd = inherit(group_config.combine_fwd_num_sms, comm_sms); + const int dispatch_bwd = inherit(group_config.dispatch_bwd_num_sms, dispatch_fwd); + const int combine_bwd = inherit(group_config.combine_bwd_num_sms, combine_fwd); + NVTE_CHECK(comm_sms <= device_sms && dispatch_fwd <= device_sms && combine_fwd <= device_sms && + dispatch_bwd <= device_sms && combine_bwd <= device_sms, + "num_comm_sms and dispatch/combine fwd/bwd num_sms must be <= the device SM count (", + device_sms, "), got num_comm_sms ", comm_sms, ", dispatch fwd/bwd ", dispatch_fwd, "/", + dispatch_bwd, ", combine fwd/bwd ", combine_fwd, "/", combine_bwd); + group_config_.dispatch_fwd_num_sms = dispatch_fwd; + group_config_.combine_fwd_num_sms = combine_fwd; + group_config_.dispatch_bwd_num_sms = dispatch_bwd; + group_config_.combine_bwd_num_sms = combine_bwd; + cfg.dispatch_num_sms = static_cast(dispatch_fwd); + cfg.combine_num_sms = static_cast(combine_fwd); + // NCCL EP's backward counts default to its forward ones; set them only where they differ. +#if NCCL_EP_GROUP_CONFIG_V5_SIZE >= 144u + if (dispatch_bwd != dispatch_fwd) { + cfg.dispatch_bwd_num_sms = static_cast(dispatch_bwd); + } + if (combine_bwd != combine_fwd) { + cfg.combine_bwd_num_sms = static_cast(combine_bwd); + } +#else + NVTE_CHECK(dispatch_bwd == dispatch_fwd && combine_bwd == combine_fwd, + "backward dispatch/combine SM counts other than the forward ones need a Transformer " + "Engine built against an NCCL EP with dispatch_bwd_num_sms and combine_bwd_num_sms; " + "got dispatch fwd/bwd ", + dispatch_fwd, "/", dispatch_bwd, ", combine fwd/bwd ", combine_fwd, "/", combine_bwd); +#endif // 0 = NCCL_EP_AUTO, which enables eager mode (recv buffers sized per routing). cfg.max_recv_tokens_per_rank = static_cast(group_config.max_recv_tokens_per_rank); cfg.zero_copy = group_config.zero_copy ? NCCL_EP_ZERO_COPY_ON : NCCL_EP_ZERO_COPY_OFF; @@ -434,15 +518,14 @@ void EPBackend::prepare(NVTETensor handle_mem, const NVTETensor topk_idx, NVTE_CHECK_NCCL(nccl_ep::update_handle(guard.get(), &nccl_topk_idx, &layout_info, stream)); } -void EPBackend::issue_dispatch_locked(ncclEpHandle_t handle, const NVTETensor topk_idx, - const NVTETensor tokens, const NVTECommWindow& tokens_win, - const NVTETensor topk_weights, - const NVTECommWindow& topk_weights_win, - NVTETensor recv_tokens, const NVTECommWindow& recv_tokens_win, - NVTETensor recv_topk_weights, - const NVTECommWindow& recv_topk_weights_win, - NVTETensor recv_tokens_per_expert, - NVTETensor total_recv_tokens_per_rank, cudaStream_t stream) { +void EPBackend::issue_dispatch_locked( + ncclEpHandle_t handle, const NVTETensor topk_idx, const NVTETensor tokens, + const NVTECommWindow& tokens_win, const NVTETensor topk_weights, + const NVTECommWindow& topk_weights_win, NVTETensor recv_tokens, + const NVTECommWindow& recv_tokens_win, NVTETensor recv_topk_weights, + const NVTECommWindow& recv_topk_weights_win, NVTETensor recv_tokens_per_expert, + NVTETensor total_recv_tokens_per_rank, NVTETensor expert_token_offsets, + const EpSignal* dispatch_signal, cudaStream_t stream) { NVTE_CHECK(nvte_tensor_shape(tokens).ndim == 2, "tokens must be 2D [T, hidden_dim]"); NVTE_CHECK(nvte_tensor_shape(recv_tokens).ndim == 2, "recv_tokens must be 2D [recv_T, hidden_dim]"); @@ -517,6 +600,10 @@ void EPBackend::issue_dispatch_locked(ncclEpHandle_t handle, const NVTETensor to out_struct.topk_weights = is_forward ? &nccl_topk_weights_out : nullptr; out_struct.scales = is_scaled ? &nccl_scales_out : nullptr; + SignalDesc dispatch_signal_desc; + out_struct.dispatch_signal = + dispatch_signal_desc.attach(dispatch_signal, NCCL_EP_SIGNAL_UNIT_TILE_ROWS, "dispatch"); + ncclEpDispatchConfig_t dispatch_cfg = NCCL_EP_DISPATCH_CONFIG_INIT; dispatch_cfg.pass_direction = is_forward ? NCCL_EP_FWD_PASS : NCCL_EP_BWD_PASS; // Block-scaled payloads forward the per-token scale-inverse; select the matching recipe. @@ -526,8 +613,8 @@ void EPBackend::issue_dispatch_locked(ncclEpHandle_t handle, const NVTETensor to // fused dispatch writes them (the count scan is fused into the dispatch). NULL leaves // layout_info unset (non-count callers). ncclEpLayoutInfo_t layout_info = NCCL_EP_LAYOUT_INFO_INIT; - NVTEShape recv_counts_shape, total_recv_shape; - ncclEpTensor_t recv_counts_desc, total_recv_desc; + NVTEShape recv_counts_shape, total_recv_shape, recv_offsets_shape; + ncclEpTensor_t recv_counts_desc, total_recv_desc, recv_offsets_desc; const ncclEpLayoutInfo_t* layout_info_ptr = nullptr; if (recv_tokens_per_expert != nullptr) { recv_counts_desc = make_nccl_ep_tensor(recv_tokens_per_expert, recv_counts_shape); @@ -539,9 +626,15 @@ void EPBackend::issue_dispatch_locked(ncclEpHandle_t handle, const NVTETensor to layout_info.recv_total_counter = &total_recv_desc; layout_info_ptr = &layout_info; } + if (expert_token_offsets != nullptr) { + recv_offsets_desc = make_nccl_ep_tensor(expert_token_offsets, recv_offsets_shape); + layout_info.expert_offsets = &recv_offsets_desc; + layout_info_ptr = &layout_info; + } - NVTE_CHECK_NCCL( - nccl_ep::dispatch(handle, &in_struct, &out_struct, layout_info_ptr, &dispatch_cfg, stream)); + check_signaled_call( + nccl_ep::dispatch(handle, &in_struct, &out_struct, layout_info_ptr, &dispatch_cfg, stream), + out_struct.dispatch_signal != nullptr, "dispatch"); } void EPBackend::dispatch(NVTETensor handle_mem, const NVTETensor topk_idx, const NVTETensor tokens, @@ -549,7 +642,8 @@ void EPBackend::dispatch(NVTETensor handle_mem, const NVTETensor topk_idx, const const NVTECommWindow& topk_weights_win, NVTETensor recv_tokens, const NVTECommWindow& recv_tokens_win, NVTETensor recv_topk_weights, const NVTECommWindow& recv_topk_weights_win, - const NVTEEpLayerConfig& layer_cfg, cudaStream_t stream) { + const EpSignal* dispatch_signal, const NVTEEpLayerConfig& layer_cfg, + cudaStream_t stream) { void* hm_ptr = handle_mem_ptr(handle_mem); const int num_tokens = static_cast(nvte_tensor_shape(tokens).data[0]); std::lock_guard lock(mutex_); @@ -560,7 +654,8 @@ void EPBackend::dispatch(NVTETensor handle_mem, const NVTETensor topk_idx, const issue_dispatch_locked(h, topk_idx, tokens, tokens_win, topk_weights, topk_weights_win, recv_tokens, recv_tokens_win, recv_topk_weights, recv_topk_weights_win, /*recv_tokens_per_expert=*/nullptr, - /*total_recv_tokens_per_rank=*/nullptr, stream); + /*total_recv_tokens_per_rank=*/nullptr, + /*expert_token_offsets=*/nullptr, dispatch_signal, stream); } void EPBackend::prepare_and_dispatch( @@ -569,7 +664,8 @@ void EPBackend::prepare_and_dispatch( const NVTECommWindow& topk_weights_win, NVTETensor recv_tokens, const NVTECommWindow& recv_tokens_win, NVTETensor recv_topk_weights, const NVTECommWindow& recv_topk_weights_win, NVTETensor recv_tokens_per_expert, - NVTETensor total_recv_tokens_per_rank, NVTEEpLayerConfig layer_cfg, cudaStream_t stream) { + NVTETensor total_recv_tokens_per_rank, NVTETensor expert_token_offsets, + const EpSignal* dispatch_signal, NVTEEpLayerConfig layer_cfg, cudaStream_t stream) { void* hm_ptr = handle_mem_ptr(handle_mem); NVTE_CHECK(layer_cfg.top_k > 0, "top_k must be > 0, got ", layer_cfg.top_k); NVTE_CHECK(nvte_tensor_shape(topk_idx).ndim == 2, "topk_idx must be 2D [T, top_k]"); @@ -589,12 +685,14 @@ void EPBackend::prepare_and_dispatch( nccl_ep::update_handle(guard.get(), &nccl_topk_idx, /*layout_info=*/nullptr, stream)); issue_dispatch_locked(guard.get(), topk_idx, tokens, tokens_win, topk_weights, topk_weights_win, recv_tokens, recv_tokens_win, recv_topk_weights, recv_topk_weights_win, - recv_tokens_per_expert, total_recv_tokens_per_rank, stream); + recv_tokens_per_expert, total_recv_tokens_per_rank, expert_token_offsets, + dispatch_signal, stream); } void EPBackend::combine(NVTETensor handle_mem, const NVTETensor expert_out, const NVTECommWindow& expert_out_win, NVTETensor result, - const NVTEEpLayerConfig& layer_cfg, cudaStream_t stream) { + const EpSignal* combine_signal, const NVTEEpLayerConfig& layer_cfg, + cudaStream_t stream) { void* hm_ptr = handle_mem_ptr(handle_mem); NVTE_CHECK(nvte_tensor_shape(expert_out).ndim == 2, "expert_out must be 2D [recv_T, hidden_dim]"); NVTE_CHECK(nvte_tensor_shape(result).ndim == 2, "result must be 2D [T, hidden_dim]"); @@ -607,6 +705,10 @@ void EPBackend::combine(NVTETensor handle_mem, const NVTETensor expert_out, ncclEpCombineInputs_t in_struct = NCCL_EP_COMBINE_INPUTS_INIT; in_struct.tokens = &nccl_expert_in; + SignalDesc combine_signal_desc; + in_struct.combine_signal = + combine_signal_desc.attach(combine_signal, NCCL_EP_SIGNAL_UNIT_CHUNK_ELEMS, "combine"); + ncclEpCombineOutputs_t out_struct = NCCL_EP_COMBINE_OUTPUTS_INIT; out_struct.tokens = &nccl_result_out; @@ -615,14 +717,15 @@ void EPBackend::combine(NVTETensor handle_mem, const NVTETensor expert_out, ncclEpHandle_t h = import_handle_locked(hm_ptr, nvte_tensor_size_bytes(handle_mem), num_tokens, layer_cfg); ScopedHandle guard(h); - NVTE_CHECK_NCCL(nccl_ep::combine(h, &in_struct, &out_struct, /*config=*/nullptr, stream)); + check_signaled_call(nccl_ep::combine(h, &in_struct, &out_struct, /*config=*/nullptr, stream), + combine_signal != nullptr, "combine"); } void EPBackend::dispatch_bwd(NVTETensor handle_mem, const NVTETensor grad, const NVTECommWindow& grad_win, const NVTETensor g_recv_topk_weights, const NVTECommWindow& g_recv_topk_weights_win, NVTETensor grad_tokens, - NVTETensor grad_topk_weights, const NVTEEpLayerConfig& layer_cfg, - cudaStream_t stream) { + NVTETensor grad_topk_weights, const EpSignal* combine_signal, + const NVTEEpLayerConfig& layer_cfg, cudaStream_t stream) { void* hm_ptr = handle_mem_ptr(handle_mem); const int num_tokens = static_cast(nvte_tensor_shape(grad_tokens).data[0]); NVTE_CHECK(nvte_tensor_shape(grad).ndim == 2, "grad must be 2D [recv_capacity, hidden_dim]"); @@ -645,6 +748,10 @@ void EPBackend::dispatch_bwd(NVTETensor handle_mem, const NVTETensor grad, in_struct.tokens = &nccl_tok_in; in_struct.topk_weights = &nccl_w_in; + SignalDesc combine_signal_desc; + in_struct.combine_signal = + combine_signal_desc.attach(combine_signal, NCCL_EP_SIGNAL_UNIT_CHUNK_ELEMS, "combine"); + ncclEpCombineOutputs_t out_struct = NCCL_EP_COMBINE_OUTPUTS_INIT; out_struct.tokens = &nccl_tok_out; out_struct.topk_weights = &nccl_w_out; @@ -657,19 +764,21 @@ void EPBackend::dispatch_bwd(NVTETensor handle_mem, const NVTETensor grad, ncclEpHandle_t h = import_handle_locked(hm_ptr, nvte_tensor_size_bytes(handle_mem), num_tokens, layer_cfg); ScopedHandle guard(h); - NVTE_CHECK_NCCL(nccl_ep::combine(h, &in_struct, &out_struct, &cfg, stream)); + check_signaled_call(nccl_ep::combine(h, &in_struct, &out_struct, &cfg, stream), + combine_signal != nullptr, "dispatch backward"); } void EPBackend::combine_bwd(NVTETensor handle_mem, const NVTETensor grad, const NVTECommWindow& grad_win, NVTETensor grad_expert_out, const NVTECommWindow& grad_expert_out_win, - const NVTEEpLayerConfig& layer_cfg, cudaStream_t stream) { + const EpSignal* dispatch_signal, const NVTEEpLayerConfig& layer_cfg, + cudaStream_t stream) { // Backward of combine = reverse-direction dispatch. dispatch(handle_mem, /*topk_idx=*/nullptr, grad, grad_win, /*topk_weights=*/nullptr, /*topk_weights_win=*/NVTECommWindow{}, grad_expert_out, grad_expert_out_win, - /*recv_topk_weights=*/nullptr, /*recv_topk_weights_win=*/NVTECommWindow{}, layer_cfg, - stream); + /*recv_topk_weights=*/nullptr, /*recv_topk_weights_win=*/NVTECommWindow{}, + dispatch_signal, layer_cfg, stream); } } // namespace ep diff --git a/transformer_engine/common/ep/ep_backend.h b/transformer_engine/common/ep/ep_backend.h index e11ae4bf58d..2991a7df1ee 100644 --- a/transformer_engine/common/ep/ep_backend.h +++ b/transformer_engine/common/ep/ep_backend.h @@ -26,6 +26,15 @@ namespace transformer_engine { namespace ep { +/*! \brief Readiness flags of an overlapped op: 1D int32, one flag per `granularity` units of the + * signaled tensor (rows of recv_tokens for a dispatch, hidden columns for a combine). */ +struct EpSignal { + // int32 readiness signal, one entry per granularity units; reset to -1, set to the slot index i + // when that unit is ready (consumer waits for signal[s] == s). + NVTETensor ready; + size_t granularity; +}; + /*! \brief EP backend per CUDA device; owns the NCCL EP group, borrows the comm. */ class EPBackend { public: @@ -53,16 +62,20 @@ class EPBackend { cudaStream_t stream); // Per-step ops below require a prior prepare(); layer_cfg rebinds the handle from handle_mem. + // A non-null dispatch_signal publishes one flag per signal granularity rows of recv_tokens. void dispatch(NVTETensor handle_mem, const NVTETensor topk_idx, const NVTETensor tokens, const NVTECommWindow& tokens_win, const NVTETensor topk_weights, const NVTECommWindow& topk_weights_win, NVTETensor recv_tokens, const NVTECommWindow& recv_tokens_win, NVTETensor recv_topk_weights, - const NVTECommWindow& recv_topk_weights_win, const NVTEEpLayerConfig& layer_cfg, - cudaStream_t stream); + const NVTECommWindow& recv_topk_weights_win, const EpSignal* dispatch_signal, + const NVTEEpLayerConfig& layer_cfg, cudaStream_t stream); // Fused prepare + dispatch: seeds routing then dispatches in one call. Routing writes the // per-expert recv counts to recv_tokens_per_expert and the scalar pre-drop per-rank recv total // to total_recv_tokens_per_rank (nullable); the dispatch then reads the counts from the handle. + // expert_token_offsets (nullable): the padded per-expert token offsets; NCCL EP requires them, + // the counts and the total, when given, to share one integer type. + // dispatch_signal: as for dispatch(). void prepare_and_dispatch(NVTETensor handle_mem, const NVTETensor topk_idx, const NVTETensor tokens, const NVTECommWindow& tokens_win, const NVTETensor topk_weights, const NVTECommWindow& topk_weights_win, @@ -70,23 +83,32 @@ class EPBackend { NVTETensor recv_topk_weights, const NVTECommWindow& recv_topk_weights_win, NVTETensor recv_tokens_per_expert, - NVTETensor total_recv_tokens_per_rank, NVTEEpLayerConfig layer_cfg, + NVTETensor total_recv_tokens_per_rank, NVTETensor expert_token_offsets, + const EpSignal* dispatch_signal, NVTEEpLayerConfig layer_cfg, cudaStream_t stream); + // A non-null combine_signal makes the combine start on column chunks as the producer of + // expert_out publishes them. void combine(NVTETensor handle_mem, const NVTETensor expert_out, const NVTECommWindow& expert_out_win, NVTETensor result, - const NVTEEpLayerConfig& layer_cfg, cudaStream_t stream); + const EpSignal* combine_signal, const NVTEEpLayerConfig& layer_cfg, + cudaStream_t stream); // g_recv_topk_weights: 1D [recv_capacity] f32; grad_topk_weights: 2D [T, top_k] f32. + // combine_signal: as for combine(). void dispatch_bwd(NVTETensor handle_mem, const NVTETensor grad, const NVTECommWindow& grad_win, const NVTETensor g_recv_topk_weights, const NVTECommWindow& g_recv_topk_weights_win, NVTETensor grad_tokens, - NVTETensor grad_topk_weights, const NVTEEpLayerConfig& layer_cfg, - cudaStream_t stream); + NVTETensor grad_topk_weights, const EpSignal* combine_signal, + const NVTEEpLayerConfig& layer_cfg, cudaStream_t stream); + // dispatch_signal: as for dispatch(), over the rows of grad_expert_out. void combine_bwd(NVTETensor handle_mem, const NVTETensor grad, const NVTECommWindow& grad_win, NVTETensor grad_expert_out, const NVTECommWindow& grad_expert_out_win, - const NVTEEpLayerConfig& layer_cfg, cudaStream_t stream); + const EpSignal* dispatch_signal, const NVTEEpLayerConfig& layer_cfg, + cudaStream_t stream); + + const NVTEEpGroupConfig& group_config() const { return group_config_; } ~EPBackend(); @@ -122,7 +144,8 @@ class EPBackend { // Build the dispatch in/out structs and issue ncclEpDispatch on the given // handle. When recv_tokens_per_expert != nullptr (count mode), it is wired to - // layout_info.expert_counters so the dispatch writes per-expert recv counts. + // layout_info.expert_counters so the dispatch writes per-expert recv counts; likewise + // expert_token_offsets to layout_info.expert_offsets. // Caller must hold mutex_. void issue_dispatch_locked(ncclEpHandle_t handle, const NVTETensor topk_idx, const NVTETensor tokens, const NVTECommWindow& tokens_win, @@ -131,13 +154,17 @@ class EPBackend { NVTETensor recv_topk_weights, const NVTECommWindow& recv_topk_weights_win, NVTETensor recv_tokens_per_expert, - NVTETensor total_recv_tokens_per_rank, cudaStream_t stream); + NVTETensor total_recv_tokens_per_rank, NVTETensor expert_token_offsets, + const EpSignal* dispatch_signal, cudaStream_t stream); // devices_mutex_ protects the map; each backend's mutex_ protects its state. static std::mutex devices_mutex_; static std::unordered_map> devices_; }; +// A caller's versioned layer config copied into the current layout. +NVTEEpLayerConfig normalize_layer_config(const NVTEEpLayerConfig* cfg); + } // namespace ep } // namespace transformer_engine diff --git a/transformer_engine/common/ep/ep_gemm_api.cpp b/transformer_engine/common/ep/ep_gemm_api.cpp new file mode 100644 index 00000000000..d6ea3a48c04 --- /dev/null +++ b/transformer_engine/common/ep/ep_gemm_api.cpp @@ -0,0 +1,1116 @@ +/************************************************************************* + * Copyright (c) 2022-2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * + * See LICENSE for license information. + ************************************************************************/ + +#include + +#include "../util/logging.h" + +#if defined(NVTE_WITH_NCCL_EP) && defined(NVTE_WITH_CUTEDSL) + +#include + +#include +#include +#include +#include +#include +#include + +#include "../common.h" +#include "../util/cuda_runtime.h" +#include "ep_backend.h" +#include "ep_gemm_config.h" +#include "ep_overlap_workspace.h" + +namespace ep = transformer_engine::ep; + +namespace { + +constexpr size_t kWorkspaceAlign = 128; +// Rows per GEMM M tile (cluster tile M). Smaller expert alignments end an expert in a tail tile. +constexpr size_t kRowsPerTile = 256; +// GEMM CTA tile N; combine readiness flags cover a multiple of it. +constexpr size_t kTileN = 256; +constexpr size_t kClusterSize = 2; + +size_t align_up(size_t value) { + return (value + kWorkspaceAlign - 1) / kWorkspaceAlign * kWorkspaceAlign; +} + +using transformer_engine::tvm_ffi_bridge::DLTensorWrapper; + +// Operands live on the current device. +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)); +} + +// The operand scaling of a MoE overlap op: BF16 (the delayed default) or MXFP8; any other mode is +// unsupported for now. +NVTEScalingMode overlap_scaling_mode(NVTETensor t) { + const NVTEScalingMode mode = nvte_tensor_scaling_mode(t); + NVTE_CHECK(mode == NVTE_DELAYED_TENSOR_SCALING || mode == NVTE_MXFP8_1D_SCALING, + "the MoE overlap ops support BF16 or MXFP8 operands only, got scaling mode ", + static_cast(mode)); + return mode; +} + +// An MXFP8 operand: E4M3 data with compact or GEMM-swizzled scales. +void check_mxfp8(NVTETensor t, bool swizzled, const char* name) { + NVTE_CHECK(t != nullptr && is_mxfp8(t) && nvte_tensor_type(t) == kNVTEFloat8E4M3, name, + " must be MXFP8 E4M3"); + uint8_t with_swizzled = 0; + nvte_get_tensor_param_v2(t, kNVTEWithGEMMSwizzledScales, &with_swizzled, sizeof(with_swizzled), + nullptr); + NVTE_CHECK((with_swizzled != 0) == swizzled, name, + swizzled ? " needs GEMM-swizzled scales" : " needs compact scales"); +} + +// Shapes the MXFP8 GEMMs take: compact scale rows of whole 16-byte TMA boxes, SwiGLU tiles and +// expert slabs of whole 128-row scale tiles. +void check_mxfp8_dims(size_t hidden, size_t ffn, size_t alignment) { + NVTE_CHECK(hidden % 512 == 0 && ffn % 256 == 0, "MXFP8 needs hidden_dim (", hidden, + ") a multiple of 512 and ffn_dim (", ffn, ") a multiple of 256"); + NVTE_CHECK(alignment >= 128, "MXFP8 needs dispatch_output_per_expert_alignment 128 or ", + kRowsPerTile); +} + +// Columns per combine flag: 1024 when it divides n, else the whole row; both are chunks NCCL EP +// accepts for bfloat16 rows. +size_t combine_chunk(size_t n) { + NVTE_CHECK(n % kTileN == 0, "output columns (", n, ") must be a multiple of ", kTileN); + return n % 1024 == 0 ? 1024 : n; +} + +// The combine (or dispatch backward) starts at the GEMM's entry and waits on its chunk flags. +constexpr bool kCombineAtGemmEntry = true; + +// Group and layer state checked by every entry point. +struct EpGemmContext { + ep::EPBackend& backend; + const NVTEEpGroupConfig& group; + NVTEEpLayerConfig layer_cfg; + int num_clusters; + int all_clusters; // clusters of every SM + // max_recv_tokens_per_rank == 0: the caller sized the recv buffers with nvte_ep_prepare. + bool eager; + + size_t alignment() const { return layer_cfg.dispatch_output_per_expert_alignment; } + // Rows per dispatch readiness flag: the alignment. A GEMM M tile (kRowsPerTile rows) is a whole + // multiple of every allowed alignment, so each tile spans a whole number of readiness slots. + size_t ready_slot_rows() const { return alignment(); } +}; + +// comm_sms: the group's SM count of the NCCL EP call that the entry point overlaps; the GEMM runs +// on the other SMs. +EpGemmContext make_context(const NVTEEpLayerConfig* layer_cfg, int NVTEEpGroupConfig::*comm_sms) { + const NVTEEpLayerConfig cfg = ep::normalize_layer_config(layer_cfg); + const size_t alignment = cfg.dispatch_output_per_expert_alignment; + NVTE_CHECK(alignment == 64 || alignment == 128 || alignment == kRowsPerTile, + "dispatch_output_per_expert_alignment must be 64, 128 or ", kRowsPerTile); + ep::EPBackend& backend = ep::EPBackend::get(); + const NVTEEpGroupConfig& group = backend.group_config(); + NVTE_CHECK(group.num_comm_sms > 0, "the overlapped ops need an explicit num_comm_sms"); + NVTE_CHECK(!group.zero_copy, "the overlapped ops do not support zero-copy"); + // The GEMMs take the SMs left beside the ep_bootstrap counts, which these variables would + // change for the NCCL EP kernels only. + for (const char* name : {"NCCL_EP_COMM_SMS", "NCCL_EP_DISPATCH_SMS", "NCCL_EP_COMBINE_SMS", + "NCCL_EP_DISPATCH_BWD_SMS", "NCCL_EP_COMBINE_BWD_SMS"}) { + NVTE_CHECK(std::getenv(name) == nullptr, + "the overlapped ops split the SMs by the ep_bootstrap " + "counts; unset ", + name); + } + const int sm_count = transformer_engine::cuda::sm_count(); + NVTE_CHECK(sm_count - group.*comm_sms >= static_cast(kClusterSize), "fewer than ", + kClusterSize, " SMs left beside the ", group.*comm_sms, " communication SMs"); + // The GEMM tails take the clusters of every SM. + const int max_clusters = + transformer_engine::cuda::max_active_clusters(static_cast(kClusterSize)); + NVTE_CHECK(max_clusters == sm_count / static_cast(kClusterSize), "the device runs ", + max_clusters, " clusters of ", kClusterSize, " SMs at once, not ", sm_count, " / ", + kClusterSize); + EpGemmContext ctx{backend, + group, + cfg, + (sm_count - group.*comm_sms) / static_cast(kClusterSize), + sm_count / static_cast(kClusterSize), + group.max_recv_tokens_per_rank == 0}; + return ctx; +} + +// A caller-owned [num_experts] int32 count tensor. +void check_counts(NVTETensor counts, size_t num_experts, const char* name) { + NVTE_CHECK(counts != nullptr, name, " must not be null"); + NVTE_CHECK(nvte_tensor_shape(counts).ndim == 1 && nvte_tensor_numel(counts) == num_experts && + nvte_tensor_type(counts) == kNVTEInt32, + name, " must be an int32 tensor of ", num_experts, " elements"); +} + +// A caller-owned float32 [rows] tensor. +void check_row_floats(NVTETensor t, size_t rows, const char* name) { + NVTE_CHECK(t != nullptr, name, " must not be null"); + NVTE_CHECK(nvte_tensor_shape(t).ndim == 1 && nvte_tensor_numel(t) == rows && + nvte_tensor_type(t) == kNVTEFloat32, + name, " must be a float32 tensor of recv_capacity (", rows, ") elements"); +} + +// The GEMM reads the per-expert row ends from expert_token_offsets[1:] and requires them 16-byte +// aligned; callers front-pad the [num_experts + 1] int32 layout by 3 elements to achieve that. +void check_expert_token_offsets(const NVTETensor expert_token_offsets, size_t num_experts) { + NVTE_CHECK(nvte_tensor_numel(expert_token_offsets) == num_experts + 1 && + nvte_tensor_type(expert_token_offsets) == kNVTEInt32, + "expert_token_offsets must be an int32 tensor of num_experts + 1 elements"); + const int32_t* row_ends = static_cast(nvte_tensor_data(expert_token_offsets)) + 1; + NVTE_CHECK(reinterpret_cast(row_ends) % 16 == 0, + "expert_token_offsets[1:] (the per-expert row ends) must start 16-byte aligned; " + "front-pad the num_experts + 1 int32 layout by 3 elements"); +} + +// Rows: the group capacity, or any multiple of the flag rows in eager mode. +void check_rows(const EpGemmContext& ctx, size_t rows, const char* name) { + NVTE_CHECK(rows % ctx.ready_slot_rows() == 0, name, " rows (", rows, ") must be a multiple of ", + ctx.ready_slot_rows()); + NVTE_CHECK(ctx.eager || rows == static_cast(ctx.group.max_recv_tokens_per_rank), name, + " has ", rows, " rows, max_recv_tokens_per_rank is ", + ctx.group.max_recv_tokens_per_rank); +} + +// Whether the forward dispatch counts the routing itself and writes the caller's expert layout. As +// NCCL EP's dispatch_pull_count_capable for the overlapped group (pull-push flow in one LSA team): +// not in eager mode and at most 65536 / 32 local experts. Without drops only: with them the +// dispatch reports the pre-drop row total. +bool dispatch_writes_layout(const EpGemmContext& ctx, size_t num_local_experts) { + return !ctx.eager && !ctx.group.drop_on_overflow && num_local_experts <= 65536 / 32; +} + +// The forward combine_gemm GEMM of [rows, k] inputs and n output columns. +ep::EpCombineGemmConfig combine_fwd_config(const EpGemmContext& ctx, size_t rows, size_t k, + size_t n, size_t num_experts, + NVTEScalingMode scaling_mode) { + return ep::EpCombineGemmConfig{rows, + k, + n, + num_experts, + ctx.num_clusters, + combine_chunk(n), + kCombineAtGemmEntry, + false, + scaling_mode, + ctx.alignment(), + ctx.all_clusters}; +} + +// Per-call scratch for the GEMM's readiness flags and state, sliced from the caller's workspace. +// ScratchLayout is the byte layout; nvte_ep_overlap_workspace_size uses it to size the workspace +// without a buffer, and claim_scratch uses it to resolve the pointers in GemmScratch. +struct ScratchLayout { + size_t row_ends; // [num_experts] int32 per-expert row ends, the grouped GEMM layout operand + size_t alpha; // [num_experts] float32 per-expert output scale, set to 1 (reused as norm_const) + size_t ones; // [rows] float32 of 1, the probability operand when the GEMM is unweighted + size_t wgrad; // backward weight-gradient accumulation workspace, empty when no weight gradient + size_t total; // end offset: the bytes the caller must provide +}; + +ScratchLayout scratch_layout(size_t gemm_bytes, size_t num_experts, size_t rows, bool unit_probs, + size_t wgrad_bytes) { + ScratchLayout l; + l.row_ends = align_up(gemm_bytes + sizeof(int32_t)); + l.alpha = l.row_ends + align_up(sizeof(int32_t) * num_experts); + l.ones = l.alpha + align_up(sizeof(float) * num_experts); + l.wgrad = l.ones + (unit_probs ? align_up(sizeof(float) * rows) : 0); + l.total = l.wgrad + align_up(wgrad_bytes); + return l; +} + +// Resolved pointers into the workspace slices, plus the words each launch resets. row_ends usually +// addresses the layout slice, but dispatch_fwd re-points it to the caller's expert_token_offsets. +struct GemmScratch { + uint8_t* base; + uint8_t* wgrad = nullptr; + int32_t* row_ends = nullptr; // [num_experts] + float* alpha = nullptr; // [num_experts] + float* ones = nullptr; // [rows] + int32_t* signal = nullptr; // [signal_capacity] readiness flags + int signal_capacity = 0; + int num_experts = 0; + ep::WorkspaceReset reset; +}; + +GemmScratch claim_scratch(uint8_t* base, size_t workspace_bytes, size_t gemm_bytes, + size_t num_experts, size_t rows, bool unit_probs, size_t wgrad_bytes) { + const ScratchLayout l = scratch_layout(gemm_bytes, num_experts, rows, unit_probs, wgrad_bytes); + NVTE_CHECK(l.total <= workspace_bytes, "the EP overlap workspace needs ", l.total, " bytes, got ", + workspace_bytes, "; size it with nvte_ep_overlap_workspace_size"); + GemmScratch scratch{base}; + if (wgrad_bytes > 0) { + scratch.wgrad = base + l.wgrad; + } + scratch.row_ends = reinterpret_cast(base + l.row_ends); + scratch.alpha = reinterpret_cast(base + l.alpha); + scratch.num_experts = static_cast(num_experts); + scratch.reset.fill(scratch.alpha, scratch.num_experts, ep::kFillOne); + if (unit_probs) { + scratch.ones = reinterpret_cast(base + l.ones); + scratch.reset.fill(scratch.ones, static_cast(rows), ep::kFillOne); + } + return scratch; +} + +// Base pointer and byte capacity of the caller's workspace tensor. +std::pair workspace_span(const NVTETensor workspace) { + NVTE_CHECK(workspace != nullptr, "the EP overlap ops need a workspace tensor"); + void* const ptr = nvte_tensor_data(workspace); + NVTE_CHECK(ptr != nullptr && nvte_tensor_type(workspace) == kNVTEByte, + "the EP overlap workspace must be a non-null uint8 tensor"); + NVTE_CHECK(reinterpret_cast(ptr) % kWorkspaceAlign == 0, + "the EP overlap workspace must be ", kWorkspaceAlign, "-byte aligned"); + return {static_cast(ptr), nvte_tensor_numel(workspace)}; +} + +// Stage a GemmScratch's reset words once the GEMM's WorkspaceLayout is known: the readiness flags, +// scheduler state and row ends each launch reinitializes. + +// Words of a GEMM that waits on the dispatch tile flags: its tile counter, flags and scheduler +// state. +void set_signal_words(GemmScratch& scratch, const ep::WorkspaceLayout& layout, size_t slots) { + scratch.signal = reinterpret_cast(scratch.base + layout.signal); + scratch.signal_capacity = static_cast(slots); + scratch.reset.fill(scratch.base + layout.counter, 1, ep::kFillZero); + scratch.reset.fill(scratch.signal, scratch.signal_capacity, ep::kFillMinusOne); + scratch.reset.fill(scratch.base + layout.state, (layout.total_bytes - layout.state) / 4, + ep::kFillZero); +} + +// Words of a GEMM that publishes column chunks: its first zeroed_bytes (scheduler words, zero at +// entry) and chunk flags. +void set_chunk_words(GemmScratch& scratch, const ep::WorkspaceLayout& layout, size_t chunks, + size_t zeroed_bytes) { + scratch.signal = reinterpret_cast(scratch.base + layout.signal); + scratch.signal_capacity = static_cast(chunks); + scratch.reset.fill(scratch.base, zeroed_bytes / 4, ep::kFillZero); + scratch.reset.fill(scratch.signal, scratch.signal_capacity, ep::kFillMinusOne); +} + +// Row ends the dispatch writes: unset until it does, together with the reserved word before them. +void unset_row_ends(GemmScratch& scratch) { + scratch.reset.fill(scratch.row_ends - 1, scratch.num_experts + 1, ep::kFillMinusOne); +} + +// Row ends computed by the reset from the padded int32 counts per local expert; write_layout_base +// also writes the reserved word before them, expert 0's start, as 0. +void set_row_ends(GemmScratch& scratch, NVTETensor counts, bool write_layout_base = false) { + scratch.reset.counts = static_cast(nvte_tensor_data(counts)); + scratch.reset.row_ends = scratch.row_ends; + scratch.reset.num_experts = scratch.num_experts; + if (write_layout_base) { + scratch.reset.fill(scratch.row_ends - 1, 1, ep::kFillZero); + } +} + +// Compiled GEMM and workspace layout of a configuration. +template +tvm::ffi::Function get_gemm(const Config& config, ep::WorkspaceLayout* layout) { + auto kernel = config.get_kernel(); + NVTE_CHECK(kernel.has_value(), + "the EP grouped GEMM is not available: needs NVTE_ENABLE_CUTEDSL_BACKEND=1, " + "NVTE_MOE_OVERLAP and SM 10.0, 10.3 or 10.7"); + const auto offsets = config.workspace_layout(); + NVTE_CHECK(offsets.has_value(), "cannot query the GEMM workspace layout"); + *layout = *offsets; + return *kernel; +} + +// The dispatch GEMM on `clusters` more clusters than the first launch's, which share its workspace. +tvm::ffi::Function get_tail_gemm(ep::EpDispatchGemmConfig config, int clusters, + const ep::WorkspaceLayout& layout, const char* name) { + config.num_clusters = clusters; + ep::WorkspaceLayout tail_layout; + const tvm::ffi::Function tail = get_gemm(config, &tail_layout); + NVTE_CHECK(tail_layout.total_bytes == layout.total_bytes && + tail_layout.counter == layout.counter && tail_layout.signal == layout.signal && + tail_layout.state == layout.state, + name, " has another workspace layout"); + return tail; +} + +// A weight gradient chained behind a backward GEMM: weight_grad[e] = grad^T x over the rows of +// expert e, written or added to. +struct Wgrad { + NVTETensor grad; + NVTETensor x; + NVTETensor weight_grad; + ep::EpWgradConfig config; // each launch sets its clusters and wait options + ep::WorkspaceLayout layout; +}; + +// Checks the weight-gradient operands of a backward entry; nullopt without weight_grad. MXFP8 +// reads both operands columnwise. +std::optional make_wgrad(const EpGemmContext& ctx, NVTETensor grad, NVTETensor x, + NVTETensor weight_grad, bool accumulate, size_t rows, + size_t num_experts, NVTEScalingMode scaling_mode) { + const bool mxfp8 = transformer_engine::is_mxfp8_scaling(scaling_mode); + if (weight_grad == nullptr) { + NVTE_CHECK(x == nullptr, "wgrad_input needs weight_grad"); + return std::nullopt; + } + NVTE_CHECK(x != nullptr, "weight_grad needs wgrad_input"); + NVTE_CHECK(rows > 0, "the chained weight gradient needs received rows"); + NVTE_CHECK(nvte_tensor_shape(grad).ndim == 2 && nvte_tensor_shape(x).ndim == 2, + "wgrad_input and the gradient must be 2D"); + const NVTEShape shape = nvte_tensor_shape(weight_grad); + NVTE_CHECK(shape.ndim == 3 && shape.data[0] == num_experts, + "weight_grad must be [num_local_experts, m, n]"); + NVTE_CHECK(reinterpret_cast(nvte_tensor_data(weight_grad)) % 16 == 0, + "weight_grad must be 16-byte aligned"); + const size_t m = shape.data[1]; + const size_t n = shape.data[2]; + NVTE_CHECK(nvte_tensor_shape(grad).data[1] == m && nvte_tensor_shape(x).data[0] == rows && + nvte_tensor_shape(x).data[1] == n, + "weight_grad must be [num_local_experts, ", nvte_tensor_shape(grad).data[1], + ", n] with wgrad_input [recv_capacity, n]"); + if (mxfp8) { + check_mxfp8(x, true, "wgrad_input"); + // Both operands are read columnwise: [rows, cols] E4M3 data and rows * cols / 32 scales. + const auto check_columnwise = [rows](NVTETensor t, size_t cols, const char* name) { + const NVTEBasicTensor data = nvte_get_tensor_param(t, kNVTEColumnwiseData); + const NVTEBasicTensor scales = nvte_get_tensor_param(t, kNVTEColumnwiseScaleInv); + size_t scale_count = 1; + for (size_t i = 0; i < scales.shape.ndim; ++i) { + scale_count *= scales.shape.data[i]; + } + NVTE_CHECK(data.data_ptr != nullptr && scales.data_ptr != nullptr, + "the MXFP8 weight gradient needs columnwise ", name, " data and scales"); + NVTE_CHECK(data.shape.ndim == 2 && data.shape.data[0] == rows && data.shape.data[1] == cols, + "the columnwise MXFP8 ", name, " must be [", rows, ", ", cols, "]"); + NVTE_CHECK(scale_count == rows * cols / 32, "the columnwise MXFP8 ", name, " needs ", + rows * cols / 32, " scales, got ", scale_count); + }; + check_columnwise(grad, m, "gradient"); + check_columnwise(x, n, "wgrad_input"); + } else { + NVTE_CHECK(nvte_tensor_type(x) == kNVTEBFloat16, "wgrad_input must be bfloat16"); + } + const NVTEDType out_type = nvte_tensor_type(weight_grad); + NVTE_CHECK(out_type == kNVTEBFloat16 || out_type == kNVTEFloat32, + "weight_grad must be bfloat16 or float32"); + const size_t routed_rows = + static_cast(ctx.group.max_tokens_per_rank) * ctx.layer_cfg.top_k; + Wgrad wgrad{grad, + x, + weight_grad, + {rows, m, n, num_experts, 1, out_type == kNVTEFloat32, accumulate, false, 0, + scaling_mode, false, ctx.alignment(), routed_rows}, + {}}; + const auto layout = wgrad.config.workspace_layout(); + NVTE_CHECK(layout.has_value(), "cannot query the weight-gradient workspace layout"); + wgrad.layout = *layout; + return wgrad; +} + +// Whether the MXFP8 weight gradient reads per-expert descriptors that a descriptors_only launch +// writes: an added or FP32 one, and on SM 10.7 a written BF16 one with long experts. The others +// read global descriptors. +bool needs_descriptors(const Wgrad& wgrad) { + return wgrad.config.is_mxfp8() && wgrad.config.reads_descriptors(); +} + +// One launch of a weight gradient on num_clusters clusters (none: no launch), a programmatic +// dependent of the kernel before it. Launches sharing the call's workspace split the tiles. +// wait_primary_at_start: no load before that kernel completes. ready_slot_rows: no load before +// every dispatch flag of the expert rows is set. descriptors_only (MXFP8): a plain launch that +// writes the per-expert descriptors the other launches read; it follows the scratch reset. +void launch_wgrad(const Wgrad& wgrad, const GemmScratch& scratch, int num_clusters, + bool wait_primary_at_start, size_t ready_slot_rows, cudaStream_t stream, + bool descriptors_only) { + if (num_clusters <= 0) { + return; + } + ep::EpWgradConfig config = wgrad.config; + config.num_clusters = num_clusters; + config.wait_primary_at_start = wait_primary_at_start; + config.ready_slot_rows = ready_slot_rows; + config.descriptors_only = descriptors_only; + ep::WorkspaceLayout layout; + const tvm::ffi::Function gemm = get_gemm(config, &layout); + // The call sized the scratch from its base configuration. + NVTE_CHECK( + layout.total_bytes <= wgrad.layout.total_bytes && layout.counter == wgrad.layout.counter, + "weight-gradient workspace layout differs between launches"); + auto out = wrap_rowwise(wgrad.weight_grad, false); + auto row_ends = wrap_raw(scratch.row_ends, kNVTEInt32, config.num_experts); + auto ws = wrap_raw(scratch.wgrad, kNVTEByte, layout.total_bytes); + if (config.is_mxfp8()) { + auto grad = wrap_columnwise(wgrad.grad, true); + auto x = wrap_columnwise(wgrad.x, true); + auto grad_scales = wrap_scales(wgrad.grad, true, config.rows, config.m); + auto x_scales = wrap_scales(wgrad.x, true, config.rows, config.n); + gemm(&grad, &x, &grad_scales, &x_scales, &out, &row_ends, &ws, static_cast(stream)); + return; + } + auto grad = wrap_rowwise(wgrad.grad, true); + auto x = wrap_rowwise(wgrad.x, true); + if (ready_slot_rows > 0) { + auto signal = wrap_raw(scratch.signal, kNVTEInt32, config.rows / ready_slot_rows); + gemm(&grad, &x, &out, &row_ends, &ws, &signal, static_cast(stream)); + return; + } + gemm(&grad, &x, &out, &row_ends, &ws, static_cast(stream)); +} + +// The columnwise MXFP8 copy of t's received rows, requantized from its rowwise data and compact +// scales; columnwise scales GEMM-swizzled per expert slab. A programmatic dependent of the kernel +// before it. ready_slot_rows > 0: a tile starts once the dispatch has set the flags of its rows. +void launch_requant(NVTETensor t, const GemmScratch& scratch, size_t rows, size_t cols, + size_t num_experts, size_t ready_slot_rows, cudaStream_t stream) { + const ep::EpRequantConfig config{rows, cols, num_experts, ready_slot_rows}; + const auto kernel = config.get_kernel(); + NVTE_CHECK(kernel.has_value(), + "the EP MXFP8 requant is not available: needs NVTE_ENABLE_CUTEDSL_BACKEND=1, " + "NVTE_MOE_OVERLAP and SM 10.0, 10.3 or 10.7"); + auto codes = wrap_rowwise(t, true); + auto row_scales = wrap_scales(t, false, rows, cols); + auto col_codes = wrap_columnwise(t, true); + auto col_scales = wrap_scales(t, true, rows, cols); + auto row_ends = wrap_raw(scratch.row_ends, kNVTEInt32, num_experts); + if (ready_slot_rows > 0) { + auto signal = wrap_raw(scratch.signal, kNVTEInt32, rows / ready_slot_rows); + (*kernel)(&codes, &row_scales, &col_codes, &col_scales, &row_ends, &signal, + static_cast(stream)); + return; + } + (*kernel)(&codes, &row_scales, &col_codes, &col_scales, &row_ends, static_cast(stream)); +} + +// Bytes of the chained weight-gradient workspace of a backward GEMM over num_experts slabs of +// [m, n], as make_wgrad sizes it; the max over the output precisions, which the query does not know. +size_t wgrad_workspace_bytes(const EpGemmContext& ctx, size_t rows, size_t m, size_t n, + size_t num_experts, NVTEScalingMode scaling_mode) { + const size_t routed_rows = + static_cast(ctx.group.max_tokens_per_rank) * ctx.layer_cfg.top_k; + size_t bytes = 0; + for (const bool fp32_out : {false, true}) { + const ep::EpWgradConfig config{rows, m, n, num_experts, 1, fp32_out, + false, false, 0, scaling_mode, false, ctx.alignment(), + routed_rows}; + // The output precision is not known here, so size over both. A variant the device does not + // support (e.g. the SM 10.7 FP32 MXFP8 weight gradient at or below 256 rows) throws while + // building its kernel; skip it rather than failing the sizing of a supported call. + try { + const auto layout = config.workspace_layout(); + if (layout.has_value()) { + bytes = std::max(bytes, layout->total_bytes); + } + } catch (...) { + // An unsupported output precision is simply left out of the workspace sizing. + } + } + return bytes; +} + +// total_bytes of a GEMM configuration, or a clear error when the kernel is unavailable. +template +size_t gemm_workspace_bytes(const Config& config) { + const auto layout = config.workspace_layout(); + NVTE_CHECK(layout.has_value(), + "the EP grouped GEMM is not available: needs NVTE_ENABLE_CUTEDSL_BACKEND=1, " + "NVTE_MOE_OVERLAP and SM 10.0, 10.3 or 10.7"); + return layout->total_bytes; +} + +} // namespace + +extern "C" { + +// Returns the max scratch over every op of the group, not per op: the scratch is small, so one +// size that fits any call lets a caller size one workspace instead of querying each op. +size_t nvte_ep_overlap_workspace_size(size_t hidden_dim, size_t ffn_dim, size_t num_local_experts, + size_t recv_capacity, int with_weight_grad, int mxfp8, + const NVTEEpLayerConfig* layer_cfg) { + NVTE_API_CALL(nvte_ep_overlap_workspace_size); + using namespace transformer_engine; + const size_t ne = num_local_experts; + const size_t rows = recv_capacity; + const NVTEScalingMode mx = mxfp8 != 0 ? NVTE_MXFP8_1D_SCALING : NVTE_DELAYED_TENSOR_SCALING; + const bool wg = with_weight_grad != 0; + size_t need = 0; + // Largest scratch of a call whose GEMM uses `config`; unit_probs sizes the per-row ones buffer and + // wgrad the weight-gradient workspace. + const auto consider = [&](const auto& config, bool unit_probs, size_t wgrad) { + need = std::max( + need, scratch_layout(gemm_workspace_bytes(config), ne, rows, unit_probs, wgrad).total); + }; + + // Forward dispatch: FC1 + SwiGLU, no weight gradient. + { + const EpGemmContext ctx = make_context(layer_cfg, &NVTEEpGroupConfig::dispatch_fwd_num_sms); + consider(ep::EpDispatchGemmConfig{rows, hidden_dim, 2 * ffn_dim, ne, ctx.num_clusters, false, + mx, ctx.alignment(), dispatch_writes_layout(ctx, ne)}, + false, 0); + } + // Forward combine: FC2. Size the unit-probs row buffer, which the MXFP8 path omits. + { + const EpGemmContext ctx = make_context(layer_cfg, &NVTEEpGroupConfig::combine_fwd_num_sms); + consider(combine_fwd_config(ctx, rows, ffn_dim, hidden_dim, ne, mx), true, 0); + } + // Backward combine: FC2 dgrad + SwiGLU backward, with the FC2 weight gradient [hidden, ffn]. + { + const EpGemmContext ctx = make_context(layer_cfg, &NVTEEpGroupConfig::dispatch_bwd_num_sms); + const size_t wgrad = wg ? wgrad_workspace_bytes(ctx, rows, hidden_dim, ffn_dim, ne, mx) : 0; + consider(ep::EpDispatchGemmConfig{rows, hidden_dim, ffn_dim, ne, ctx.num_clusters, true, mx, + ctx.alignment()}, + false, wgrad); + } + // Backward dispatch: FC1 dgrad, with the FC1 weight gradient [2 * ffn, hidden]. + { + const EpGemmContext ctx = make_context(layer_cfg, &NVTEEpGroupConfig::combine_bwd_num_sms); + const bool plain = wg && ctx.num_clusters > 0; + const size_t n_chunk = plain ? 0 : combine_chunk(hidden_dim); + const size_t wgrad = wg ? wgrad_workspace_bytes(ctx, rows, 2 * ffn_dim, hidden_dim, ne, mx) : 0; + consider(ep::EpCombineGemmConfig{rows, 2 * ffn_dim, hidden_dim, ne, + wg ? ctx.all_clusters : ctx.num_clusters, n_chunk, + !plain && kCombineAtGemmEntry, true, mx, ctx.alignment()}, + true, wgrad); + } + return need; +} + +void nvte_ep_dispatch_gemm_fwd(NVTETensor handle_mem, const NVTETensor topk_idx, + const NVTETensor tokens, NVTECommWindow tokens_win, + const NVTETensor topk_weights, const NVTETensor weight, + NVTETensor recv_tokens, NVTETensor recv_topk_weights, + NVTETensor gemm_out, NVTETensor act_out, + NVTETensor recv_tokens_per_expert, NVTETensor expert_token_offsets, + NVTETensor total_recv_tokens, NVTETensor workspace, + const NVTEEpLayerConfig* layer_cfg, cudaStream_t stream) { + NVTE_API_CALL(nvte_ep_dispatch_gemm_fwd); + using namespace transformer_engine; + const EpGemmContext ctx = make_context(layer_cfg, &NVTEEpGroupConfig::dispatch_fwd_num_sms); + checkCuDriverContext(stream); + const auto [ws_base, ws_bytes] = workspace_span(workspace); + + const size_t rows = nvte_tensor_shape(recv_tokens).data[0]; + const size_t hidden = nvte_tensor_shape(tokens).data[1]; + const size_t num_experts = nvte_tensor_shape(weight).data[0]; + const size_t n = nvte_tensor_shape(weight).data[1]; + check_rows(ctx, rows, "recv_tokens"); + NVTE_CHECK(num_experts * ctx.group.ep_size == static_cast(ctx.group.num_experts), + "weight has ", num_experts, " experts, expected num_experts / ep_size = ", + ctx.group.num_experts / ctx.group.ep_size); + NVTE_CHECK(nvte_tensor_shape(act_out).data[1] * 2 == n, "weight rows (", n, + ") must be 2 * the act_out columns: SwiGLU"); + check_counts(recv_tokens_per_expert, num_experts, "recv_tokens_per_expert"); + check_row_floats(recv_topk_weights, rows, "recv_topk_weights"); + NVTE_CHECK(total_recv_tokens == nullptr || (nvte_tensor_numel(total_recv_tokens) == 1 && + nvte_tensor_type(total_recv_tokens) == kNVTEInt32), + "total_recv_tokens must be an int32 tensor of 1 element"); + const NVTEScalingMode scaling_mode = overlap_scaling_mode(tokens); + const bool mxfp8 = scaling_mode == NVTE_MXFP8_1D_SCALING; + if (mxfp8) { + check_mxfp8(tokens, false, "tokens"); + check_mxfp8(recv_tokens, false, "recv_tokens"); + check_mxfp8(weight, true, "weight"); + check_mxfp8(act_out, true, "act_out"); + NVTE_CHECK(nvte_tensor_type(gemm_out) == kNVTEBFloat16, "gemm_out must be bfloat16"); + check_mxfp8_dims(hidden, n / 2, ctx.alignment()); + } else { + NVTE_CHECK( + nvte_tensor_type(tokens) == kNVTEBFloat16 && nvte_tensor_type(weight) == kNVTEBFloat16, + "tokens and weight must be bfloat16 or MXFP8"); + } + + // No count exchange before the dispatch when the dispatch writes the GEMM's expert layout. + const bool device_layout = dispatch_writes_layout(ctx, num_experts); + + // The GEMM runs beside the dispatch, and its tail on the SMs the dispatch frees. Both launches + // claim tiles from one workspace. + ep::WorkspaceLayout layout; + const ep::EpDispatchGemmConfig config{rows, hidden, n, + num_experts, ctx.num_clusters, false, + scaling_mode, ctx.alignment(), device_layout}; + std::vector gemms{get_gemm(config, &layout)}; + const int tail_clusters = ctx.all_clusters - ctx.num_clusters; + if (tail_clusters > 0) { + gemms.push_back(get_tail_gemm(config, tail_clusters, layout, "the GEMM tail")); + } + GemmScratch scratch = + claim_scratch(ws_base, ws_bytes, layout.total_bytes, num_experts, rows, false, 0); + set_signal_words(scratch, layout, rows / ctx.ready_slot_rows()); + // The GEMM reads the expert row ends from the caller's [num_experts + 1] int32 + // expert_token_offsets (expert 0's start, then the per-expert ends); the dispatch writes them in + // capacity mode. + check_expert_token_offsets(expert_token_offsets, num_experts); + scratch.row_ends = static_cast(nvte_tensor_data(expert_token_offsets)) + 1; + + // The dispatch publishes one flag per slot of rows; the GEMM behind it consumes ready tiles. + TensorWrapper signal(scratch.signal, + std::vector{static_cast(scratch.signal_capacity)}, + DType::kInt32); + const ep::EpSignal dispatch_signal{signal.data(), ctx.ready_slot_rows()}; + NVTECommWindow no_window{}; + if (device_layout) { + // Flags, scheduler state and unset layout words, before the dispatch that sets them. The fused + // dispatch writes the GEMM's expert layout and the padded counts in one scan. + unset_row_ends(scratch); + ep::reset_workspace(scratch.reset, stream); + // Expert offsets, then the row total: the expert row ends sit one word in. + int32_t* const expert_layout = scratch.row_ends - 1; + TensorWrapper offsets(expert_layout, std::vector{num_experts}, DType::kInt32); + TensorWrapper total(expert_layout + num_experts, std::vector{1}, DType::kInt32); + ctx.backend.prepare_and_dispatch(handle_mem, topk_idx, tokens, tokens_win, topk_weights, + no_window, recv_tokens, no_window, recv_topk_weights, + no_window, recv_tokens_per_expert, total.data(), + offsets.data(), &dispatch_signal, ctx.layer_cfg, stream); + } else { + // Capacity mode runs the routing prepare; eager mode ran nvte_ep_prepare already. + if (!ctx.eager) { + ctx.backend.prepare(handle_mem, topk_idx, recv_tokens_per_expert, total_recv_tokens, + ctx.layer_cfg, stream); + } + // Flags, scheduler state and expert row ends, before the dispatch that sets the flags. The + // reset also writes the caller offsets' leading 0 (expert 0's start), which the dispatch + // layout scan does not touch here. + set_row_ends(scratch, recv_tokens_per_expert, /*write_layout_base=*/true); + ep::reset_workspace(scratch.reset, stream); + ctx.backend.dispatch(handle_mem, topk_idx, tokens, tokens_win, topk_weights, no_window, + recv_tokens, no_window, recv_topk_weights, no_window, &dispatch_signal, + &ctx.layer_cfg, stream); + } + + // The GEMM is a programmatic dependent of the dispatch: tiles start as their flags are set. The + // tail is the GEMM's programmatic dependent. + auto a = wrap_rowwise(recv_tokens, true); + auto b = wrap_rowwise(weight, false); + auto c = wrap_rowwise(gemm_out, true); + auto d = wrap_rowwise(act_out, true); + auto row_ends = wrap_raw(scratch.row_ends, kNVTEInt32, num_experts); + auto alpha = wrap_raw(scratch.alpha, kNVTEFloat32, num_experts); + auto ws = wrap_raw(scratch.base, kNVTEByte, layout.total_bytes); + if (mxfp8) { + auto sfb = wrap_scales(weight, false, num_experts * n, hidden); + auto sfa = wrap_scales(recv_tokens, false, rows, hidden); + auto sfd = wrap_scales(act_out, false, rows, n / 2); + auto norm_const = wrap_raw(scratch.alpha, kNVTEFloat32, 1); + for (const tvm::ffi::Function& gemm : gemms) { + gemm(&a, &b, &sfb, &sfa, &c, &d, &sfd, &row_ends, &alpha, &norm_const, &ws, + static_cast(stream)); + } + } else { + auto prob = wrap_rowwise(recv_topk_weights, false); + for (const tvm::ffi::Function& gemm : gemms) { + gemm(&a, &b, &c, &d, &row_ends, &alpha, &prob, &ws, static_cast(stream)); + } + } +} + +void nvte_ep_combine_gemm_fwd(NVTETensor handle_mem, const NVTETensor gemm_in, + const NVTETensor recv_topk_weights, + const NVTETensor expert_token_offsets, const NVTETensor weight, + NVTETensor expert_out, NVTETensor result, NVTETensor workspace, + const NVTEEpLayerConfig* layer_cfg, cudaStream_t stream) { + NVTE_API_CALL(nvte_ep_combine_gemm_fwd); + using namespace transformer_engine; + const EpGemmContext ctx = make_context(layer_cfg, &NVTEEpGroupConfig::combine_fwd_num_sms); + checkCuDriverContext(stream); + const auto [ws_base, ws_bytes] = workspace_span(workspace); + + const size_t rows = nvte_tensor_shape(gemm_in).data[0]; + const size_t k = nvte_tensor_shape(gemm_in).data[1]; + const size_t num_experts = nvte_tensor_shape(weight).data[0]; + const size_t n = nvte_tensor_shape(weight).data[1]; + check_rows(ctx, rows, "gemm_in"); + NVTE_CHECK(nvte_tensor_shape(weight).data[2] == k, "weight columns must equal gemm_in columns"); + const NVTEScalingMode scaling_mode = overlap_scaling_mode(gemm_in); + const bool mxfp8 = scaling_mode == NVTE_MXFP8_1D_SCALING; + if (mxfp8) { + check_mxfp8(gemm_in, true, "gemm_in"); + check_mxfp8(weight, true, "weight"); + check_mxfp8_dims(n, k, ctx.alignment()); + } else { + NVTE_CHECK( + nvte_tensor_type(gemm_in) == kNVTEBFloat16 && nvte_tensor_type(weight) == kNVTEBFloat16, + "gemm_in and weight must be bfloat16 or MXFP8"); + } + check_expert_token_offsets(expert_token_offsets, num_experts); + const bool weighted = recv_topk_weights != nullptr; + NVTE_CHECK(!weighted || (nvte_tensor_type(recv_topk_weights) == kNVTEFloat32 && + nvte_tensor_numel(recv_topk_weights) == rows), + "recv_topk_weights must be float32 [recv_capacity]"); + + // The GEMM launches on every SM; the clusters past those beside the combine stop after the + // first chunk and leave their SMs to the combine. + ep::WorkspaceLayout layout; + const ep::EpCombineGemmConfig config = + combine_fwd_config(ctx, rows, k, n, num_experts, scaling_mode); + const size_t n_chunk = config.n_chunk; + const tvm::ffi::Function gemm = get_gemm(config, &layout); + // Own workspace for the signal, scheduler and alpha words; the expert layout is the caller's + // expert_token_offsets the dispatch wrote. + GemmScratch scratch = + claim_scratch(ws_base, ws_bytes, layout.total_bytes, num_experts, rows, !weighted, 0); + set_chunk_words(scratch, layout, n / n_chunk, layout.signal); + ep::reset_workspace(scratch.reset, stream); + + // The GEMM fills the flags; the combine is its programmatic dependent. + auto a = wrap_rowwise(gemm_in, true); + auto b = wrap_rowwise(weight, false); + auto d = wrap_rowwise(expert_out, true); + auto row_ends = wrap_raw(static_cast(nvte_tensor_data(expert_token_offsets)) + 1, + kNVTEInt32, num_experts); + auto alpha = wrap_raw(scratch.alpha, kNVTEFloat32, num_experts); + auto prob = weighted ? wrap_rowwise(recv_topk_weights, false) + : wrap_raw(scratch.ones, kNVTEFloat32, rows); + auto ws = wrap_raw(scratch.base, kNVTEByte, layout.total_bytes); + if (mxfp8) { + auto sfb = wrap_scales(weight, false, num_experts * n, k); + auto sfa = wrap_scales(gemm_in, false, rows, k); + gemm(&a, &b, &sfb, &sfa, &d, &row_ends, &alpha, &prob, &ws, static_cast(stream)); + } else { + gemm(&a, &b, &d, &row_ends, &alpha, &prob, &ws, static_cast(stream)); + } + + NVTECommWindow no_window{}; + TensorWrapper signal(scratch.base + layout.signal, std::vector{n / n_chunk}, + DType::kInt32); + const ep::EpSignal combine_signal{signal.data(), n_chunk}; + ctx.backend.combine(handle_mem, expert_out, no_window, result, &combine_signal, &ctx.layer_cfg, + stream); +} + +void nvte_ep_combine_gemm_bwd(NVTETensor handle_mem, const NVTETensor grad_result, + NVTECommWindow grad_result_win, const NVTETensor gemm_out, + const NVTETensor recv_topk_weights, + const NVTETensor recv_tokens_per_expert, const NVTETensor weight, + const NVTETensor wgrad_input, NVTETensor grad_expert_out, + NVTETensor grad_gemm_out, NVTETensor grad_recv_topk_weights, + NVTETensor act_out, NVTETensor weight_grad, + int accumulate_weight_grad, NVTETensor workspace, + const NVTEEpLayerConfig* layer_cfg, cudaStream_t stream) { + NVTE_API_CALL(nvte_ep_combine_gemm_bwd); + using namespace transformer_engine; + const EpGemmContext ctx = make_context(layer_cfg, &NVTEEpGroupConfig::dispatch_bwd_num_sms); + checkCuDriverContext(stream); + const auto [ws_base, ws_bytes] = workspace_span(workspace); + + const size_t rows = nvte_tensor_shape(grad_expert_out).data[0]; + const size_t hidden = nvte_tensor_shape(grad_expert_out).data[1]; + const size_t num_experts = nvte_tensor_shape(weight).data[0]; + const size_t ffn = nvte_tensor_shape(weight).data[2]; + check_rows(ctx, rows, "grad_expert_out"); + NVTE_CHECK(nvte_tensor_shape(weight).data[1] == hidden && + nvte_tensor_shape(gemm_out).data[1] == 2 * ffn && + nvte_tensor_shape(grad_gemm_out).data[1] == 2 * ffn, + "weight must be [experts, hidden, ffn] with 2 * ffn the gemm_out columns: SwiGLU"); + NVTE_CHECK(nvte_tensor_type(gemm_out) == kNVTEBFloat16, "gemm_out must be bfloat16"); + const NVTEScalingMode scaling_mode = overlap_scaling_mode(grad_result); + const bool mxfp8 = scaling_mode == NVTE_MXFP8_1D_SCALING; + if (mxfp8) { + check_mxfp8(grad_result, false, "grad_result"); + check_mxfp8(grad_expert_out, false, "grad_expert_out"); + check_mxfp8(weight, true, "weight"); + check_mxfp8(grad_gemm_out, true, "grad_gemm_out"); + check_mxfp8(act_out, true, "act_out"); + NVTE_CHECK(nvte_tensor_shape(act_out).data[1] == ffn, "act_out must have ffn columns"); + check_mxfp8_dims(hidden, ffn, ctx.alignment()); + } else { + NVTE_CHECK( + nvte_tensor_type(grad_result) == kNVTEBFloat16 && nvte_tensor_type(weight) == kNVTEBFloat16, + "grad_result and weight must be bfloat16 or MXFP8"); + NVTE_CHECK(act_out == nullptr, "act_out is written for MXFP8 only"); + } + check_counts(recv_tokens_per_expert, num_experts, "recv_tokens_per_expert"); + check_row_floats(recv_topk_weights, rows, "recv_topk_weights"); + check_row_floats(grad_recv_topk_weights, rows, "grad_recv_topk_weights"); + + // The MXFP8 weight gradient reads the columnwise grad_expert_out that this call writes. + const bool requant = + mxfp8 && nvte_get_tensor_param(grad_expert_out, kNVTEColumnwiseData).data_ptr != nullptr; + NVTE_CHECK(!mxfp8 || weight_grad == nullptr || requant, + "the MXFP8 weight gradient needs the columnwise grad_expert_out"); + const std::optional wgrad = + make_wgrad(ctx, grad_expert_out, wgrad_input, weight_grad, accumulate_weight_grad, rows, + num_experts, scaling_mode); + + ep::WorkspaceLayout layout; + const ep::EpDispatchGemmConfig config{ + rows, hidden, ffn, num_experts, ctx.num_clusters, true, scaling_mode, ctx.alignment()}; + const tvm::ffi::Function gemm = get_gemm(config, &layout); + GemmScratch scratch = claim_scratch(ws_base, ws_bytes, layout.total_bytes, num_experts, rows, + false, wgrad ? wgrad->layout.total_bytes : 0); + set_signal_words(scratch, layout, rows / ctx.ready_slot_rows()); + if (wgrad) { + scratch.reset.fill(scratch.wgrad + wgrad->layout.counter, 1, ep::kFillZero); + } + // The GEMM adds each row's routing-weight gradient into grad_recv_topk_weights. + scratch.reset.fill(nvte_tensor_data(grad_recv_topk_weights), static_cast(rows), + ep::kFillZero); + set_row_ends(scratch, recv_tokens_per_expert); + ep::reset_workspace(scratch.reset, stream); + if (wgrad && needs_descriptors(*wgrad)) { + launch_wgrad(*wgrad, scratch, 1, false, 0, stream, true); + } + + // The reverse dispatch publishes one flag per slot; the GEMM consumes ready tiles. + TensorWrapper signal(scratch.signal, + std::vector{static_cast(scratch.signal_capacity)}, + DType::kInt32); + const ep::EpSignal dispatch_signal{signal.data(), ctx.ready_slot_rows()}; + NVTECommWindow no_window{}; + ctx.backend.combine_bwd(handle_mem, grad_result, grad_result_win, grad_expert_out, no_window, + &dispatch_signal, &ctx.layer_cfg, stream); + + // FC2 data gradient with the SwiGLU backward in its epilogue. + auto a = wrap_rowwise(grad_expert_out, true); + auto c = wrap_rowwise(gemm_out, true); + auto d = wrap_rowwise(grad_gemm_out, true); + auto dprob = wrap_rowwise(grad_recv_topk_weights, false); + auto row_ends = wrap_raw(scratch.row_ends, kNVTEInt32, num_experts); + auto alpha = wrap_raw(scratch.alpha, kNVTEFloat32, num_experts); + auto prob = wrap_rowwise(recv_topk_weights, false); + auto ws = wrap_raw(scratch.base, kNVTEByte, layout.total_bytes); + if (mxfp8) { + // The columnwise forward weight; the epilogue also recomputes act_out columnwise. + auto b = wrap_columnwise(weight, false); + auto sfb = wrap_scales(weight, true, num_experts * hidden, ffn); + auto sfa = wrap_scales(grad_expert_out, false, rows, hidden); + auto d_col = wrap_columnwise(grad_gemm_out, true); + auto sfd_row = wrap_scales(grad_gemm_out, false, rows, 2 * ffn); + auto sfd_col = wrap_scales(grad_gemm_out, true, rows, 2 * ffn); + auto h = wrap_columnwise(act_out, true); + auto sfh_col = wrap_scales(act_out, true, rows, ffn); + auto norm_const = wrap_raw(scratch.alpha, kNVTEFloat32, 1); + gemm(&a, &b, &sfb, &sfa, &c, &d, &d_col, &sfd_row, &sfd_col, &h, &sfh_col, &dprob, &row_ends, + &alpha, &prob, &norm_const, &ws, static_cast(stream)); + // The columnwise grad_expert_out, a dependent of the GEMM, which starts it at entry: each + // tile waits for the reverse dispatch's flags of its rows. + if (requant) { + launch_requant(grad_expert_out, scratch, rows, hidden, num_experts, ctx.ready_slot_rows(), + stream); + } + // Its tail on the SMs the reverse dispatch frees takes the tiles the GEMM has not claimed. + const int tail_clusters = ctx.all_clusters - ctx.num_clusters; + if (tail_clusters > 0) { + const tvm::ffi::Function tail = get_tail_gemm(config, tail_clusters, layout, "the dGLU tail"); + tail(&a, &b, &sfb, &sfa, &c, &d, &d_col, &sfd_row, &sfd_col, &h, &sfh_col, &dprob, &row_ends, + &alpha, &prob, &norm_const, &ws, static_cast(stream)); + } + // The weight gradient once the GEMM and the requant complete: its base, which then lets its + // tail in. + if (wgrad) { + launch_wgrad(*wgrad, scratch, ctx.num_clusters, true, 0, stream, false); + launch_wgrad(*wgrad, scratch, ctx.all_clusters - ctx.num_clusters, false, 0, stream, false); + } + return; + } + auto b = wrap_rowwise(weight, false); + gemm(&a, &b, &c, &d, &dprob, &row_ends, &alpha, &prob, &ws, static_cast(stream)); + // The weight gradient once every row is received: its tail on the SMs the reverse dispatch + // frees, its base on those the GEMM frees. + if (wgrad) { + launch_wgrad(*wgrad, scratch, ctx.all_clusters - ctx.num_clusters, false, ctx.ready_slot_rows(), + stream, false); + launch_wgrad(*wgrad, scratch, ctx.num_clusters, false, ctx.ready_slot_rows(), stream, false); + } +} + +void nvte_ep_dispatch_gemm_bwd(NVTETensor handle_mem, const NVTETensor grad_gemm_out, + const NVTETensor grad_recv_topk_weights, + const NVTETensor recv_tokens_per_expert, const NVTETensor weight, + const NVTETensor wgrad_input, NVTETensor grad_recv_tokens, + NVTETensor grad_tokens, NVTETensor grad_topk_weights, + NVTETensor weight_grad, int accumulate_weight_grad, + NVTETensor workspace, const NVTEEpLayerConfig* layer_cfg, + cudaStream_t stream) { + NVTE_API_CALL(nvte_ep_dispatch_gemm_bwd); + using namespace transformer_engine; + const EpGemmContext ctx = make_context(layer_cfg, &NVTEEpGroupConfig::combine_bwd_num_sms); + checkCuDriverContext(stream); + const auto [ws_base, ws_bytes] = workspace_span(workspace); + + const size_t rows = nvte_tensor_shape(grad_gemm_out).data[0]; + const size_t k = nvte_tensor_shape(grad_gemm_out).data[1]; + const size_t hidden = nvte_tensor_shape(grad_recv_tokens).data[1]; + const size_t num_experts = nvte_tensor_shape(weight).data[0]; + check_rows(ctx, rows, "grad_gemm_out"); + NVTE_CHECK(nvte_tensor_shape(weight).data[1] == k && nvte_tensor_shape(weight).data[2] == hidden, + "weight must be [experts, 2 * ffn, hidden]"); + check_counts(recv_tokens_per_expert, num_experts, "recv_tokens_per_expert"); + check_row_floats(grad_recv_topk_weights, rows, "grad_recv_topk_weights"); + const NVTEScalingMode scaling_mode = overlap_scaling_mode(grad_gemm_out); + const bool mxfp8 = scaling_mode == NVTE_MXFP8_1D_SCALING; + if (mxfp8) { + check_mxfp8(grad_gemm_out, true, "grad_gemm_out"); + check_mxfp8(weight, true, "weight"); + NVTE_CHECK(nvte_tensor_type(grad_recv_tokens) == kNVTEBFloat16, + "grad_recv_tokens must be bfloat16"); + check_mxfp8_dims(hidden, k / 2, ctx.alignment()); + } else { + NVTE_CHECK(nvte_tensor_type(grad_gemm_out) == kNVTEBFloat16 && + nvte_tensor_type(weight) == kNVTEBFloat16, + "grad_gemm_out and weight must be bfloat16 or MXFP8"); + } + const std::optional wgrad = + make_wgrad(ctx, grad_gemm_out, wgrad_input, weight_grad, accumulate_weight_grad, rows, + num_experts, scaling_mode); + // MXFP8: the call writes the columnwise wgrad_input from its rowwise data when that is set. + const bool requant = + wgrad && mxfp8 && nvte_get_tensor_param(wgrad_input, kNVTERowwiseData).data_ptr != nullptr; + // With the weight gradient the dispatch backward starts behind the weight gradient's base, which + // waits for the GEMM to complete: the GEMM publishes nothing and runs in the stock tile order, and + // the one flag of the whole row is reset to 0, published. + const bool plain = wgrad && ctx.num_clusters > 0; + const size_t n_chunk = plain ? 0 : combine_chunk(hidden); + const size_t chunk = plain ? hidden : n_chunk; + + // With the weight gradient the GEMM runs alone on every SM, and the weight gradient beside the + // dispatch backward. + ep::WorkspaceLayout layout; + const ep::EpCombineGemmConfig config{rows, + k, + hidden, + num_experts, + wgrad ? ctx.all_clusters : ctx.num_clusters, + n_chunk, + !plain && kCombineAtGemmEntry, + true, + scaling_mode, + ctx.alignment()}; + const tvm::ffi::Function gemm = get_gemm(config, &layout); + GemmScratch scratch = claim_scratch(ws_base, ws_bytes, layout.total_bytes, num_experts, rows, + true, wgrad ? wgrad->layout.total_bytes : 0); + set_chunk_words(scratch, layout, plain ? 0 : hidden / chunk, + plain ? layout.total_bytes : layout.signal); + if (wgrad) { + scratch.reset.fill(scratch.wgrad + wgrad->layout.counter, 1, ep::kFillZero); + } + set_row_ends(scratch, recv_tokens_per_expert); + ep::reset_workspace(scratch.reset, stream); + if (wgrad && needs_descriptors(*wgrad)) { + launch_wgrad(*wgrad, scratch, 1, false, 0, stream, true); + } + // The columnwise wgrad_input, before the GEMM. + if (requant) { + launch_requant(wgrad_input, scratch, rows, hidden, num_experts, 0, stream); + } + + // The GEMM fills the flags; the dispatch backward is its programmatic dependent. + auto a = wrap_rowwise(grad_gemm_out, true); + auto d = wrap_rowwise(grad_recv_tokens, true); + auto row_ends = wrap_raw(scratch.row_ends, kNVTEInt32, num_experts); + auto alpha = wrap_raw(scratch.alpha, kNVTEFloat32, num_experts); + auto prob = wrap_raw(scratch.ones, kNVTEFloat32, rows); + auto ws = wrap_raw(scratch.base, kNVTEByte, layout.total_bytes); + if (mxfp8) { + // The columnwise forward weight. + auto b = wrap_columnwise(weight, false); + auto sfb = wrap_scales(weight, true, num_experts * k, hidden); + auto sfa = wrap_scales(grad_gemm_out, false, rows, k); + gemm(&a, &b, &sfb, &sfa, &d, &row_ends, &alpha, &prob, &ws, static_cast(stream)); + } else { + auto b = wrap_rowwise(weight, false); + gemm(&a, &b, &d, &row_ends, &alpha, &prob, &ws, static_cast(stream)); + } + // The weight gradient's base starts once the GEMM completes and lets the dispatch backward in. + if (wgrad) { + launch_wgrad(*wgrad, scratch, ctx.num_clusters, true, 0, stream, false); + } + + NVTECommWindow no_window{}; + TensorWrapper signal(scratch.base + layout.signal, std::vector{hidden / chunk}, + DType::kInt32); + const ep::EpSignal combine_signal{signal.data(), chunk}; + ctx.backend.dispatch_bwd(handle_mem, grad_recv_tokens, no_window, grad_recv_topk_weights, + no_window, grad_tokens, grad_topk_weights, &combine_signal, + &ctx.layer_cfg, stream); + // Its tail takes the tiles left on the communication SMs. + if (wgrad) { + launch_wgrad(*wgrad, scratch, ctx.all_clusters - ctx.num_clusters, false, 0, stream, false); + } +} + +} // extern "C" + +#else // !(NVTE_WITH_NCCL_EP && NVTE_WITH_CUTEDSL): throwing stubs. + +namespace { +[[noreturn]] void ep_gemm_not_built() { + NVTE_ERROR( + "The EP grouped GEMMs need TransformerEngine built with NVTE_WITH_NCCL_EP=1 and " + "NVTE_WITH_CUTEDSL=1."); +} +} // namespace + +extern "C" { + +size_t nvte_ep_overlap_workspace_size(size_t, size_t, size_t, size_t, int, int, + const NVTEEpLayerConfig*) { + ep_gemm_not_built(); +} + +void nvte_ep_dispatch_gemm_fwd(NVTETensor, NVTETensor, NVTETensor, NVTECommWindow, NVTETensor, + NVTETensor, NVTETensor, NVTETensor, NVTETensor, NVTETensor, + NVTETensor, NVTETensor, NVTETensor, NVTETensor, + const NVTEEpLayerConfig*, cudaStream_t) { + ep_gemm_not_built(); +} + +void nvte_ep_combine_gemm_fwd(NVTETensor, NVTETensor, NVTETensor, NVTETensor, NVTETensor, + NVTETensor, NVTETensor, NVTETensor, const NVTEEpLayerConfig*, + cudaStream_t) { + ep_gemm_not_built(); +} + +void nvte_ep_combine_gemm_bwd(NVTETensor, NVTETensor, NVTECommWindow, NVTETensor, NVTETensor, + NVTETensor, NVTETensor, NVTETensor, NVTETensor, NVTETensor, + NVTETensor, NVTETensor, NVTETensor, int, NVTETensor, + const NVTEEpLayerConfig*, cudaStream_t) { + ep_gemm_not_built(); +} + +void nvte_ep_dispatch_gemm_bwd(NVTETensor, NVTETensor, NVTETensor, NVTETensor, NVTETensor, + NVTETensor, NVTETensor, NVTETensor, NVTETensor, NVTETensor, int, + NVTETensor, const NVTEEpLayerConfig*, cudaStream_t) { + ep_gemm_not_built(); +} + +} // extern "C" + +#endif diff --git a/transformer_engine/common/ep/ep_gemm_config.h b/transformer_engine/common/ep/ep_gemm_config.h new file mode 100644 index 00000000000..8d182e5c529 --- /dev/null +++ b/transformer_engine/common/ep/ep_gemm_config.h @@ -0,0 +1,319 @@ +/************************************************************************* + * Copyright (c) 2022-2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * + * See LICENSE for license information. + ************************************************************************/ + +#ifndef TRANSFORMER_ENGINE_COMMON_EP_EP_GEMM_CONFIG_H_ +#define TRANSFORMER_ENGINE_COMMON_EP_EP_GEMM_CONFIG_H_ + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "../tvm_ffi_bridge.h" +#include "../util/cuda_runtime.h" + +namespace transformer_engine { +namespace ep { + +// Signal-aware grouped GEMMs (CuTeDSL via TVM-FFI), keyed by configuration. The first +// get_kernel of a configuration compiles: call it at warmup, outside graph capture. + +// Byte offsets inside a GEMM workspace: total size, then the words the entry points reset. +struct WorkspaceLayout { + size_t total_bytes; + size_t counter; // dispatch GEMM, weight gradient: claim counter + size_t signal; // dispatch GEMM: tile flags; combine GEMM: column-chunk flags + size_t state; // dispatch GEMM: scheduler state +}; + +// Compiled functions and workspace layouts depend on the architecture of the current device. +inline std::string arch_key() { return "_sm" + std::to_string(cuda::sm_arch()); } + +// Cache keyed by a configuration string, read under a shared lock. Configurations carry sizes that +// do not fit the 32-bit id of tvm_ffi_bridge::TVMFFIConfigCache. +template +class KeyedCache { + public: + // Process lifetime, as TVMFFIConfigCache: nothing is destroyed at static teardown. + static KeyedCache &create() { return *new KeyedCache(); } + + // The value of key, from make() on a miss. A missing value is cached only with cache_missing. + template + std::optional get(const std::string &key, Make &&make, bool cache_missing = false) { + { + std::shared_lock lock(mutex_); + auto it = map_.find(key); + if (it != map_.end()) { + return it->second; + } + } + std::unique_lock lock(mutex_); + auto it = map_.find(key); + if (it != map_.end()) { + return it->second; + } + std::optional value = make(); + if (value.has_value() || cache_missing) { + map_.emplace(key, value); + } + return value; + } + + private: + KeyedCache() = default; + + std::shared_mutex mutex_; + std::unordered_map> map_; +}; + +// Cache key: the prefix, every argument of the configuration, and the device architecture. +template +std::string config_key(const char *prefix, const Args &args) { + std::string key = prefix; + std::apply([&](const auto &...value) { ((key += "_" + std::to_string(value)), ...); }, args); + return key + arch_key(); +} + +template +std::optional get_cached_kernel(const Config &config) { + tvm_ffi_bridge::TVMFFICentral ¢ral = tvm_ffi_bridge::TVMFFICentral::getInstance(); + if (!central.get_cutedsl_backend_enabled()) { + return central.load_tvm_ffi_function(config); + } + static auto &cache = KeyedCache::create(); + return cache.get( + config.to_key(), [&] { return central.load_tvm_ffi_function(config); }, + /*cache_missing=*/true); +} + +// Calls the global function `name` with the configuration's arguments, prefixed by `prefix`. +template +std::optional call_entry(const char *name, const Config &config, + const Prefix &...prefix) { + auto fn = tvm::ffi::Function::GetGlobal(name); + if (!fn.has_value()) { + return std::nullopt; + } + return std::apply([&](const auto &...args) { return (*fn)(prefix..., args...); }, config.args()); +} + +template +bool retrieve_from_python(const Config &config, const std::string &fn_name) { + auto result = call_entry(Config::kEntrypointName, config, tvm::ffi::String(fn_name)); + return result.has_value() && result->template try_cast().value_or(false); +} + +// The layout entry returns [total, counter, signal, state], [total, signal, entries] or +// [total, counter]. +template +std::optional query_layout_from_python(const Config &config) { + auto result = call_entry(Config::kLayoutName, config); + if (!result.has_value()) { + return std::nullopt; + } + auto offsets = result->template try_cast>(); + if (!offsets.has_value()) { + return std::nullopt; + } + const auto at = [&](size_t i) { return static_cast((*offsets)[i]); }; + if (offsets->size() == 4) { + return WorkspaceLayout{at(0), at(1), at(2), at(3)}; + } + if (offsets->size() == 3) { + return WorkspaceLayout{at(0), 0, at(1), 0}; + } + if (offsets->size() == 2) { + return WorkspaceLayout{at(0), at(1), 0, 0}; + } + return std::nullopt; +} + +// query_layout_from_python, kept per configuration once found. +template +std::optional query_layout(const Config &config) { + static auto &cache = KeyedCache::create(); + return cache.get(config.to_key(), [&] { return query_layout_from_python(config); }); +} + +// GEMM behind the dispatch: waits on the dispatch tile flags. +struct EpDispatchGemmConfig { + static constexpr const char *kEntrypointName = "get_ep_dispatch_gemm_function"; + static constexpr const char *kLayoutName = "get_ep_dispatch_gemm_workspace_layout"; + + size_t rows; // receive capacity + size_t k; // reduction size + size_t n; // GEMM output columns + size_t num_experts; + int num_clusters; // persistent clusters beside its NCCL EP call's SMs + bool backward; // the second GEMM's data gradient and SwiGLU backward instead of the first GEMM + NVTEScalingMode scaling_mode; // operand scaling: delayed for BF16, MXFP8 1D for MXFP8 + size_t rows_alignment; // rows per expert slab are a multiple of it + // Forward: the dispatch writes the expert offsets and the row total, the word before the row + // ends and the row ends, after the caller set them to -1. + bool device_layout = false; + + bool is_mxfp8() const { return scaling_mode == NVTE_MXFP8_1D_SCALING; } + + // In the parameter order of the get_ep_* function of CuTeDSL/ep_gemm/dispatch_gemm.py. + auto args() const { + return std::make_tuple(static_cast(rows), static_cast(k), + static_cast(n), static_cast(num_experts), num_clusters, + backward, static_cast(scaling_mode), + static_cast(rows_alignment), device_layout); + } + + std::string to_key() const { return config_key("ep_dispatch_gemm", args()); } + + bool retrieve_func_from_python(const std::string &fn_name) const { + return retrieve_from_python(*this, fn_name); + } + + std::optional get_kernel() const { return get_cached_kernel(*this); } + + std::optional workspace_layout() const { return query_layout(*this); } +}; + +// GEMM in front of the combine: publishes finished column chunks of its output. +struct EpCombineGemmConfig { + static constexpr const char *kEntrypointName = "get_ep_combine_gemm_function"; + static constexpr const char *kLayoutName = "get_ep_combine_gemm_workspace_layout"; + + size_t rows; // receive capacity + size_t k; // reduction size + size_t n; // output columns + size_t num_experts; + int num_clusters; // persistent clusters beside the combine's SMs + size_t n_chunk; // columns per readiness flag + bool dependents_at_entry; + bool backward; // the data gradient of the first GEMM instead of the second GEMM + NVTEScalingMode scaling_mode; // operand scaling: delayed for BF16, MXFP8 1D for MXFP8 + size_t rows_alignment; // rows per expert slab are a multiple of it + // Clusters launched, 0: num_clusters. Those past num_clusters stop after the first chunk. + int grid_clusters = 0; + + bool is_mxfp8() const { return scaling_mode == NVTE_MXFP8_1D_SCALING; } + + // In the parameter order of the get_ep_* function of CuTeDSL/ep_gemm/combine_gemm.py. + auto args() const { + return std::make_tuple(static_cast(rows), static_cast(k), + static_cast(n), static_cast(num_experts), num_clusters, + static_cast(n_chunk), dependents_at_entry, backward, + static_cast(scaling_mode), static_cast(rows_alignment), + grid_clusters); + } + + std::string to_key() const { return config_key("ep_combine_gemm", args()); } + + bool retrieve_func_from_python(const std::string &fn_name) const { + return retrieve_from_python(*this, fn_name); + } + + std::optional get_kernel() const { return get_cached_kernel(*this); } + + // total_bytes and the byte offset of signal[]; the other words are unused. + std::optional workspace_layout() const { return query_layout(*this); } +}; + +// Weight gradient chained behind a backward GEMM: a persistent grid that claims output tiles +// from the workspace counter, so launches sharing one workspace split the tiles. +struct EpWgradConfig { + static constexpr const char *kEntrypointName = "get_ep_wgrad_function"; + static constexpr const char *kLayoutName = "get_ep_wgrad_workspace_layout"; + static constexpr const char *kDescriptorsName = "get_ep_wgrad_reads_descriptors"; + + size_t rows; // receive capacity + size_t m; // rows of each expert's weight gradient + size_t n; // columns of each expert's weight gradient + size_t num_experts; + int num_clusters; // persistent clusters + bool fp32_out; // FP32 instead of BF16 weight gradient + bool accumulate; // add to the weight gradient instead of writing it + bool wait_primary_at_start; // wait for the kernel before it ahead of any load + size_t ready_slot_rows; // wait for every dispatch flag of this many rows, 0: none + // Operand scaling: delayed for BF16, MXFP8 1D for MXFP8. With MXFP8 the GEMM launches of some + // weight gradients (reads_descriptors) read the per-expert descriptors that one launch with + // descriptors_only writes into the workspace first. + NVTEScalingMode scaling_mode; + bool descriptors_only; + size_t rows_alignment; // rows per expert slab are a multiple of it + size_t routed_rows; // rows a rank receives at capacity under uniform routing, unpadded + + bool is_mxfp8() const { return scaling_mode == NVTE_MXFP8_1D_SCALING; } + + // In the parameter order of the get_ep_* function of CuTeDSL/ep_gemm/wgrad_gemm.py. + auto args() const { + return std::make_tuple(static_cast(rows), static_cast(m), + static_cast(n), static_cast(num_experts), num_clusters, + fp32_out, accumulate, wait_primary_at_start, + static_cast(ready_slot_rows), + static_cast(scaling_mode), descriptors_only, + static_cast(rows_alignment), static_cast(routed_rows)); + } + + std::string to_key() const { return config_key("ep_wgrad", args()); } + + bool retrieve_func_from_python(const std::string &fn_name) const { + return retrieve_from_python(*this, fn_name); + } + + std::optional get_kernel() const { return get_cached_kernel(*this); } + + // total_bytes and the byte offset of the claim counter. + std::optional workspace_layout() const { return query_layout(*this); } + + // Whether the GEMM launches read the per-expert descriptors of a descriptors_only launch, kept + // per configuration once found. Without an answer, the added and FP32 ones read them. + bool reads_descriptors() const { + static auto &cache = KeyedCache::create(); + return cache + .get(to_key(), + [&]() -> std::optional { + auto result = call_entry(kDescriptorsName, *this); + return result.has_value() ? result->template try_cast() : std::nullopt; + }) + .value_or(is_mxfp8() && (accumulate || fp32_out)); + } +}; + +// Rowwise to columnwise MXFP8 requant of received rows for a weight gradient: one CTA per tile of +// the receive capacity. +struct EpRequantConfig { + static constexpr const char *kEntrypointName = "get_ep_requant_function"; + + size_t rows; // receive capacity + size_t cols; + size_t num_experts; + size_t ready_slot_rows; // wait for the dispatch flags of a tile's rows, this many each; 0: none + + // In the parameter order of the get_ep_* function of CuTeDSL/ep_gemm/requantize.py. + auto args() const { + return std::make_tuple(static_cast(rows), static_cast(cols), + static_cast(num_experts), + static_cast(ready_slot_rows)); + } + + std::string to_key() const { return config_key("ep_requant", args()); } + + bool retrieve_func_from_python(const std::string &fn_name) const { + return retrieve_from_python(*this, fn_name); + } + + std::optional get_kernel() const { return get_cached_kernel(*this); } +}; + +} // namespace ep +} // namespace transformer_engine + +#endif // TRANSFORMER_ENGINE_COMMON_EP_EP_GEMM_CONFIG_H_ diff --git a/transformer_engine/common/ep/ep_overlap_workspace.cu b/transformer_engine/common/ep/ep_overlap_workspace.cu new file mode 100644 index 00000000000..02f38f3f249 --- /dev/null +++ b/transformer_engine/common/ep/ep_overlap_workspace.cu @@ -0,0 +1,75 @@ +/************************************************************************* + * Copyright (c) 2022-2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * + * See LICENSE for license information. + ************************************************************************/ + +#include +#include + +#include "../util/logging.h" +#include "ep_overlap_workspace.h" + +namespace transformer_engine { +namespace ep { + +namespace { + +constexpr int kThreads = 1024; + +__global__ void reset_workspace_kernel(WorkspaceReset reset) { + const int tid = threadIdx.x; + const int index = blockIdx.x * kThreads + tid; + const int stride = gridDim.x * kThreads; +#pragma unroll + for (int f = 0; f < WorkspaceReset::kMaxFills; ++f) { + if (f < reset.num_fills) { + for (int i = index; i < reset.fills[f].count; i += stride) { + reset.fills[f].words[i] = reset.fills[f].value; + } + } + } + if (blockIdx.x != 0 || reset.counts == nullptr) { + return; + } + // Inclusive prefix sum, kThreads experts per step. + using BlockScan = cub::BlockScan; + __shared__ typename BlockScan::TempStorage scan_storage; + int32_t running = 0; + for (int first = 0; first < reset.num_experts; first += kThreads) { + const int e = first + tid; + const int32_t count = e < reset.num_experts ? reset.counts[e] : 0; + int32_t row_end = 0; + int32_t step_total = 0; + BlockScan(scan_storage).InclusiveSum(count, row_end, step_total); + if (e < reset.num_experts) { + reset.row_ends[e] = running + row_end; + } + running += step_total; + __syncthreads(); + } +} + +} // namespace + +void WorkspaceReset::fill(void* words, int count, int32_t value) { + if (count == 0) { + return; + } + NVTE_CHECK(num_fills < kMaxFills, "too many workspace fills"); + fills[num_fills++] = {static_cast(words), count, value}; +} + +void reset_workspace(const WorkspaceReset& reset, cudaStream_t stream) { + // One block per kThreads words of the largest fill. + int most_words = 1; + for (int f = 0; f < reset.num_fills; ++f) { + most_words = std::max(most_words, reset.fills[f].count); + } + const int blocks = (most_words + kThreads - 1) / kThreads; + reset_workspace_kernel<<>>(reset); + NVTE_CHECK_CUDA(cudaGetLastError()); +} + +} // namespace ep +} // namespace transformer_engine diff --git a/transformer_engine/common/ep/ep_overlap_workspace.h b/transformer_engine/common/ep/ep_overlap_workspace.h new file mode 100644 index 00000000000..820cb35ef3e --- /dev/null +++ b/transformer_engine/common/ep/ep_overlap_workspace.h @@ -0,0 +1,47 @@ +/************************************************************************* + * Copyright (c) 2022-2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * + * See LICENSE for license information. + ************************************************************************/ + +#ifndef TRANSFORMER_ENGINE_COMMON_EP_EP_OVERLAP_WORKSPACE_H_ +#define TRANSFORMER_ENGINE_COMMON_EP_EP_OVERLAP_WORKSPACE_H_ + +#include +#include +#include + +namespace transformer_engine { +namespace ep { + +// Bit patterns of the words a reset fills with: int32 0 and -1, float 0.0f and 1.0f. +constexpr int32_t kFillZero = 0; +constexpr int32_t kFillMinusOne = -1; +constexpr int32_t kFillOne = 0x3F800000; + +// The words one launch writes before a call: constant fills and, optionally, the expert row ends +// as the inclusive prefix sums of the padded int32 counts. +struct WorkspaceReset { + static constexpr int kMaxFills = 8; + struct Fill { + int32_t* words; + int count; + int32_t value; + }; + Fill fills[kMaxFills]; + int num_fills = 0; + const int32_t* counts = nullptr; // [num_experts] padded counts; null: no row ends + int32_t* row_ends = nullptr; // [num_experts] row ends + int num_experts = 0; + + // Fill count words from words with value (a kFill* pattern); a zero count adds nothing. + void fill(void* words, int count, int32_t value); +}; + +// One launch performing every fill and the row-ends scan of reset. +void reset_workspace(const WorkspaceReset& reset, cudaStream_t stream); + +} // namespace ep +} // namespace transformer_engine + +#endif // TRANSFORMER_ENGINE_COMMON_EP_EP_OVERLAP_WORKSPACE_H_ diff --git a/transformer_engine/common/ep/nccl_ep_provider.cpp b/transformer_engine/common/ep/nccl_ep_provider.cpp index 4e4aa42599c..fa8d069f9a3 100644 --- a/transformer_engine/common/ep/nccl_ep_provider.cpp +++ b/transformer_engine/common/ep/nccl_ep_provider.cpp @@ -216,6 +216,12 @@ void* open_nccl_ep_library() { return nullptr; // Unreachable. } +// Set once in library_handle to the loaded runtime's NCCL_EP_VERSION_CODE. +int& runtime_version_storage() { + static int version = 0; + return version; +} + void* library_handle() { // Deliberately keep libnccl_ep loaded until process exit. EPBackend owns // objects whose implementation lives in this library. @@ -230,6 +236,7 @@ void* library_handle() { NVTE_CHECK(runtime_version / 10000 == NCCL_EP_MAJOR, "Incompatible NCCL EP library major version ", runtime_version / 10000, "; expected ", NCCL_EP_MAJOR); + runtime_version_storage() = runtime_version; const std::filesystem::path library_path = shared_library_path(reinterpret_cast(get_version)); NVTE_CHECK(!library_path.empty(), "Could not determine the NCCL EP library path"); @@ -249,6 +256,11 @@ void initialize() { (void)library_handle(); } void* get_symbol(const char* symbol) { return load_symbol(library_handle(), symbol); } +int runtime_version() { + (void)library_handle(); + return runtime_version_storage(); +} + namespace { template diff --git a/transformer_engine/common/ep/nccl_ep_provider.h b/transformer_engine/common/ep/nccl_ep_provider.h index 1d64d2e573e..44e0e4186b6 100644 --- a/transformer_engine/common/ep/nccl_ep_provider.h +++ b/transformer_engine/common/ep/nccl_ep_provider.h @@ -20,6 +20,9 @@ void initialize(); /*! \brief Get a function pointer from the runtime NCCL EP library. */ void* get_symbol(const char* symbol); +/*! \brief NCCL_EP_VERSION_CODE of the loaded runtime library (loads it if needed). */ +int runtime_version(); + ncclResult_t create_group(ncclEpGroup_t* ep_group, ncclComm_t comm, const ncclEpGroupConfig_t* config); ncclResult_t group_destroy(ncclEpGroup_t ep_group); diff --git a/transformer_engine/common/include/transformer_engine/ep.h b/transformer_engine/common/include/transformer_engine/ep.h index 9df66c8099e..6d7099c5104 100644 --- a/transformer_engine/common/include/transformer_engine/ep.h +++ b/transformer_engine/common/include/transformer_engine/ep.h @@ -53,7 +53,8 @@ typedef struct { int max_recv_tokens_per_rank; /*! Token hidden dimension. */ int hidden_dim; - /*! Max SMs for NCCL EP dispatch/combine kernels. 0 = default (32, clamped to device SM count). */ + /*! SMs for NCCL EP dispatch/combine kernels where no per-direction count below is set. + * 0 = default (32, clamped to device SM count). */ int num_comm_sms; /*! Widest token dtype the group will dispatch; sizes staging buffers. * Required (no default): must be set to a real token dtype. Per-dispatch @@ -69,6 +70,21 @@ typedef struct { /*! Recv overflow policy. Nonzero drops tokens past max_recv_tokens_per_rank * and continues; 0 (default) traps. Not supported in eager mode. */ int drop_on_overflow; + /* SMs of the NCCL EP dispatch and combine kernels per pass direction, for every EP op of the + * group. 0 (default) inherits: a forward count from num_comm_sms, a backward count from the + * forward count of the same kind. Each ep_gemm.h call runs its GEMM on the SMs its NCCL EP call + * leaves. */ + /*! Forward dispatch: nvte_ep_dispatch(_v2), nvte_ep_prepare_and_dispatch, + * nvte_ep_dispatch_gemm_fwd. */ + int dispatch_fwd_num_sms; + /*! Forward combine: nvte_ep_combine(_v2), nvte_ep_combine_gemm_fwd. */ + int combine_fwd_num_sms; + /*! Backward dispatch, which carries the combine's gradient: nvte_ep_combine_bwd(_v2), + * nvte_ep_combine_gemm_bwd. */ + int dispatch_bwd_num_sms; + /*! Backward combine, which carries the dispatch's gradient: nvte_ep_dispatch_bwd(_v2), + * nvte_ep_dispatch_gemm_bwd. */ + int combine_bwd_num_sms; } NVTEEpGroupConfig; /*! \brief Per-layer configuration consumed by nvte_ep_handle_mem_size, @@ -214,7 +230,7 @@ void nvte_ep_dispatch_v2(NVTETensor handle_mem, NVTETensor topk_idx, NVTETensor * \param[out] recv_topk_weights [recv_T] float32 per-slot weights. * \param[in] recv_topk_weights_win Optional symmem window for recv_topk_weights. * \param[out] recv_tokens_per_expert [num_local_experts] int32/int64 counts. - * \param[out] total_recv_tokens_per_rank Optional [1] int32/int64 scalar recv total. May be null. + * \param[out] total_recv_tokens_per_rank [1] int32/int64 scalar recv total, or null. * \param[in] layer_cfg Per-call layer configuration (struct_size set). * \param[in] stream CUDA stream. */ diff --git a/transformer_engine/common/include/transformer_engine/ep_gemm.h b/transformer_engine/common/include/transformer_engine/ep_gemm.h new file mode 100644 index 00000000000..8f1477a0fb7 --- /dev/null +++ b/transformer_engine/common/include/transformer_engine/ep_gemm.h @@ -0,0 +1,246 @@ +/************************************************************************* + * Copyright (c) 2022-2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * + * See LICENSE for license information. + ************************************************************************/ + +/*! \file ep_gemm.h + * \brief Expert-parallel grouped GEMMs overlapped with the NCCL EP dispatch and combine. + * + * Each call overlaps the grouped GEMMs of one expert-MLP stage with an NCCL EP call: the EP call + * signals its progress in chunks and the GEMM follows chunk by chunk. The backward calls also + * run the stage's weight-gradient GEMM, weight_grad[e] = grad^T wgrad_input over the rows of + * expert e, beside the EP call when weight_grad is given (null skips it). + * + * entry GEMMs EP call SMs of the EP call + * nvte_ep_dispatch_gemm_fwd FC1 + SwiGLU dispatch dispatch_fwd_num_sms + * [dispatch on its SMs] || [FC1 + SwiGLU on the rest, tile by tile as rows arrive] + * nvte_ep_combine_gemm_fwd FC2 combine combine_fwd_num_sms + * [FC2 on the rest, chunk by chunk] || [combine on its SMs] + * nvte_ep_combine_gemm_bwd FC2 dgrad + SwiGLU bwd, wgrad dispatch bwd dispatch_bwd_num_sms + * [FC2 dgrad + SwiGLU bwd (+ wgrad) on the rest] || [dispatch bwd on its SMs] + * nvte_ep_dispatch_gemm_bwd FC1 dgrad, wgrad combine bwd combine_bwd_num_sms + * [FC1 dgrad (+ wgrad) on the rest] || [combine bwd on its SMs] + * + * The SM counts are NVTEEpGroupConfig fields. A GEMM runs on the SMs its EP call leaves and, in + * its tail, on the SMs the EP call frees as it ends. A combine readiness flag spans + * 1024 hidden columns when that divides hidden_dim, else the whole row. + * + * Each call takes a caller-owned uint8 workspace of nvte_ep_overlap_workspace_size bytes for its + * readiness flags and GEMM state; it is read only during the call, so the caller may allocate it + * per call or reuse one buffer across the calls of a group. + * + * Requirements: SM 10.0, 10.3 or 10.7, EP within one NVLink domain, num_comm_sms > 0, zero_copy + * off, dispatch_output_per_expert_alignment 256, 128 (not MXFP8 on SM 10.7) or (bfloat16 only) + * 64, and NVTE_ENABLE_CUTEDSL_BACKEND=1 with NVTE_MOE_OVERLAP. MXFP8 needs hidden_dim a multiple + * of 512 and ffn_dim a multiple of 256. The first call per shape compiles the GEMM: make it at + * warmup, outside CUDA graph capture. Issue the calls of one EP group on one stream, in the same + * order on every rank. A call throws when a requirement does not hold. + * + * A symm-mem window (tokens_win, grad_result_win) lets peers read the input in place. Either every + * rank passes a window, at the same data and scale offsets, or none does. The input must not be + * written until the call's dispatch completes, and then only from a launch with no programmatic + * dependency on the stream. + * + * Row-sized tensors have recv_capacity rows, a multiple of the alignment. Under MXFP8: tokens and + * received rows carry compact rowwise scales; weights and GEMM inputs carry GEMM-swizzled scales; + * the backward reads the weights and wgrad operands columnwise. + */ + +#ifndef TRANSFORMER_ENGINE_EP_GEMM_H_ +#define TRANSFORMER_ENGINE_EP_GEMM_H_ + +#include +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/*! \brief Dispatch overlapped with the first grouped GEMM and SwiGLU. + * + * Per expert slab e: gemm_out = recv_tokens @ weight[e]^T and + * act_out = silu(gate) * up * recv_topk_weights, gate and up being alternating 32-column blocks of + * gemm_out. MXFP8 tokens: tokens, recv_tokens, weight and act_out are MXFP8 and act_out is + * silu(gate) * up, the routing weights left to nvte_ep_combine_gemm_fwd. + * + * \param[in,out] handle_mem uint8 routing-state buffer. + * \param[in] topk_idx [T, top_k] int32 or int64 routing indices. + * \param[in] tokens [T, hidden_dim] input tokens. + * \param[in] tokens_win Optional symm-mem window for tokens (MXFP8: and, in + * scale_window, for its scales); NVTECommWindow{} stages + * them. + * \param[in] topk_weights [T, top_k] float32 routing weights. + * \param[in] weight [num_local_experts, 2 * ffn_dim, hidden_dim] weights. + * \param[out] recv_tokens [recv_capacity, hidden_dim] received tokens. + * \param[out] recv_topk_weights [recv_capacity] float32 per-row routing weights. + * \param[out] gemm_out [recv_capacity, 2 * ffn_dim] GEMM output. + * \param[out] act_out [recv_capacity, ffn_dim] SwiGLU output. + * \param[in,out] recv_tokens_per_expert [num_local_experts] int32 padded counts. Eager mode + * provides them to build the expert layout. Capacity mode + * writes them: the dispatch without drops and with at most + * 2048 local experts, otherwise the routing prepare. + * \param[out] expert_token_offsets [num_local_experts + 1] int32 expert layout in tokens + * (rows): expert 0's start (0), then each expert's padded + * row end, the GEMM operand. expert_token_offsets[1:] must + * start 16-byte aligned, so front-pad the allocation by 3 + * int32 elements. Capacity mode writes it; eager mode builds + * it from recv_tokens_per_expert. The last element is the + * recv total; the per-expert counts are its diffs. + * \param[out] total_recv_tokens [1] int32 recv total before any overflow drop. The routing + * prepare writes it; null when the dispatch writes + * expert_token_offsets, where expert_token_offsets[-1] is + * the padded total of the kept rows. + * \param[in,out] workspace uint8 scratch, nvte_ep_overlap_workspace_size bytes. + * \param[in] layer_cfg Per-layer EP configuration. + * \param[in] stream CUDA stream. + */ +void nvte_ep_dispatch_gemm_fwd(NVTETensor handle_mem, const NVTETensor topk_idx, + const NVTETensor tokens, NVTECommWindow tokens_win, + const NVTETensor topk_weights, const NVTETensor weight, + NVTETensor recv_tokens, NVTETensor recv_topk_weights, + NVTETensor gemm_out, NVTETensor act_out, + NVTETensor recv_tokens_per_expert, NVTETensor expert_token_offsets, + NVTETensor total_recv_tokens, NVTETensor workspace, + const NVTEEpLayerConfig* layer_cfg, cudaStream_t stream); + +/*! \brief Second grouped GEMM overlapped with the combine. + * + * Per expert slab e: expert_out = (gemm_in @ weight[e]^T) * recv_topk_weights; result is the + * unweighted combine of expert_out. BF16 applies the routing weights in the dispatch GEMM's + * activation, so recv_topk_weights is null here; MXFP8 leaves them off the activation and applies + * them to this FC2 output. + * + * \param[in,out] handle_mem uint8 routing-state buffer. + * \param[in] gemm_in [recv_capacity, ffn_dim] act_out of + * nvte_ep_dispatch_gemm_fwd, bfloat16 or MXFP8. + * \param[in] recv_topk_weights [recv_capacity] float32 per-row routing weights; null for + * unit weights (bfloat16 act_out carries them). + * \param[in] expert_token_offsets [num_local_experts + 1] int32 expert layout from + * nvte_ep_dispatch_gemm_fwd (the GEMM reads its row ends); + * expert_token_offsets[1:] must start 16-byte aligned. + * \param[in] weight [num_local_experts, hidden_dim, ffn_dim] weights. + * \param[out] expert_out [recv_capacity, hidden_dim] GEMM output. + * \param[out] result [T, hidden_dim] combined output. + * \param[in,out] workspace uint8 scratch, nvte_ep_overlap_workspace_size bytes. + * \param[in] layer_cfg Per-layer EP configuration. + * \param[in] stream CUDA stream. + */ +void nvte_ep_combine_gemm_fwd(NVTETensor handle_mem, const NVTETensor gemm_in, + const NVTETensor recv_topk_weights, + const NVTETensor expert_token_offsets, const NVTETensor weight, + NVTETensor expert_out, NVTETensor result, NVTETensor workspace, + const NVTEEpLayerConfig* layer_cfg, cudaStream_t stream); + +/*! \brief Backward of nvte_ep_combine_gemm_fwd and of the SwiGLU: the combine backward + * overlapped with the second GEMM's data gradient, SwiGLU backward in its epilogue. + * + * The combine backward scatters grad_result to the expert rows as grad_expert_out (dy). SwiGLU + * backward over gemm_out = [gate | up] (gate and up in alternating 32-column blocks) gives + * grad_gemm_out, scaled by recv_topk_weights (MXFP8) or carrying it from the activation (BF16). + * Over expert e's rows, with W2 its forward weight and wgrad_input the route-weighted activation: + * + * grad_recv_topk_weights = sum((dy @ W2) * (silu(gate) * up), over ffn) one value per row + * weight_grad[e] = dy^T @ wgrad_input [hidden_dim, ffn_dim] + * + * grad_recv_topk_weights uses the unweighted activation silu(gate) * up. weight_grad is written + * only when non-null; accumulate_weight_grad adds to it instead of overwriting it. + * + * \param[in,out] handle_mem uint8 routing-state buffer. + * \param[in] grad_result [T, hidden_dim] gradient of result. + * \param[in] grad_result_win Optional symm-mem window for grad_result (MXFP8: and, + * in scale_window, for its scales); NVTECommWindow{} + * stages them. + * \param[in] gemm_out [recv_capacity, 2 * ffn_dim] gemm_out of + * nvte_ep_dispatch_gemm_fwd. + * \param[in] recv_topk_weights [recv_capacity] float32 per-row routing weights. + * \param[in] recv_tokens_per_expert [num_local_experts] int32 padded counts. + * \param[in] weight [num_local_experts, hidden_dim, ffn_dim] forward weights. + * \param[in] wgrad_input [recv_capacity, ffn_dim] bfloat16 act_out of + * nvte_ep_dispatch_gemm_fwd, or MXFP8 act_out of this + * call; with weight_grad only. + * \param[out] grad_expert_out [recv_capacity, hidden_dim] received gradient of + * expert_out; MXFP8: rowwise with compact scales and, when + * its columnwise data is set, also columnwise, its scales + * GEMM-swizzled per expert slab, for the weight gradient. + * \param[out] grad_gemm_out [recv_capacity, 2 * ffn_dim] gradient of gemm_out; MXFP8: + * rowwise and columnwise. + * \param[out] grad_recv_topk_weights [recv_capacity] float32 gradient of recv_topk_weights. + * \param[out] act_out [recv_capacity, ffn_dim] columnwise MXFP8 + * recv_topk_weights * silu(gate) * up, the input of the + * second GEMM's weight gradient; MXFP8 only, else null. + * \param[in,out] weight_grad [num_local_experts, hidden_dim, ffn_dim] bfloat16 or + * float32 gradient of weight, or null. + * \param[in] accumulate_weight_grad Add to weight_grad instead of writing it. + * \param[in,out] workspace uint8 scratch, nvte_ep_overlap_workspace_size bytes. + * \param[in] layer_cfg Per-layer EP configuration. + * \param[in] stream CUDA stream. + */ +void nvte_ep_combine_gemm_bwd(NVTETensor handle_mem, const NVTETensor grad_result, + NVTECommWindow grad_result_win, const NVTETensor gemm_out, + const NVTETensor recv_topk_weights, + const NVTETensor recv_tokens_per_expert, const NVTETensor weight, + const NVTETensor wgrad_input, NVTETensor grad_expert_out, + NVTETensor grad_gemm_out, NVTETensor grad_recv_topk_weights, + NVTETensor act_out, NVTETensor weight_grad, + int accumulate_weight_grad, NVTETensor workspace, + const NVTEEpLayerConfig* layer_cfg, cudaStream_t stream); + +/*! \brief Backward of nvte_ep_dispatch_gemm_fwd: the first GEMM's data gradient overlapped with + * the dispatch backward. + * + * \param[in,out] handle_mem uint8 routing-state buffer. + * \param[in] grad_gemm_out [recv_capacity, 2 * ffn_dim] from + * nvte_ep_combine_gemm_bwd; MXFP8 with weight_grad: also + * columnwise. + * \param[in] grad_recv_topk_weights [recv_capacity] float32 from nvte_ep_combine_gemm_bwd. + * \param[in] recv_tokens_per_expert [num_local_experts] int32 padded counts. + * \param[in] weight [num_local_experts, 2 * ffn_dim, hidden_dim] forward + * weights. + * \param[in,out] wgrad_input [recv_capacity, hidden_dim] recv_tokens of + * nvte_ep_dispatch_gemm_fwd, bfloat16 or columnwise + * MXFP8; with weight_grad only. MXFP8 with its rowwise + * data and compact scales also set: the call writes the + * columnwise data and scales from them. + * \param[out] grad_recv_tokens [recv_capacity, hidden_dim] gradient of recv_tokens. + * \param[out] grad_tokens [T, hidden_dim] gradient of tokens. + * \param[out] grad_topk_weights [T, top_k] float32 gradient of topk_weights. + * \param[in,out] weight_grad [num_local_experts, 2 * ffn_dim, hidden_dim] bfloat16 or + * float32 gradient of weight, or null. + * \param[in] accumulate_weight_grad Add to weight_grad instead of writing it. + * \param[in,out] workspace uint8 scratch, nvte_ep_overlap_workspace_size bytes. + * \param[in] layer_cfg Per-layer EP configuration. + * \param[in] stream CUDA stream. + */ +void nvte_ep_dispatch_gemm_bwd(NVTETensor handle_mem, const NVTETensor grad_gemm_out, + const NVTETensor grad_recv_topk_weights, + const NVTETensor recv_tokens_per_expert, const NVTETensor weight, + const NVTETensor wgrad_input, NVTETensor grad_recv_tokens, + NVTETensor grad_tokens, NVTETensor grad_topk_weights, + NVTETensor weight_grad, int accumulate_weight_grad, + NVTETensor workspace, const NVTEEpLayerConfig* layer_cfg, + cudaStream_t stream); + +/*! \brief Bytes of a workspace that fits every overlapped GEMM call of a group. Queryable once the + * EP group is bootstrapped; call it at warmup, as it compiles the group's GEMMs. + * + * \param[in] hidden_dim Hidden size. + * \param[in] ffn_dim Expert FFN size. + * \param[in] num_local_experts Experts held by this rank. + * \param[in] recv_capacity Rows of the receive buffers (recv_capacity). + * \param[in] with_weight_grad Nonzero to fit the backward weight-gradient workspace. + * \param[in] mxfp8 Nonzero for MXFP8 operands instead of bfloat16. + * \param[in] layer_cfg Per-layer EP configuration. + * \return Required workspace size in bytes. + */ +size_t nvte_ep_overlap_workspace_size(size_t hidden_dim, size_t ffn_dim, size_t num_local_experts, + size_t recv_capacity, int with_weight_grad, int mxfp8, + const NVTEEpLayerConfig* layer_cfg); + +#ifdef __cplusplus +} +#endif + +#endif // TRANSFORMER_ENGINE_EP_GEMM_H_ diff --git a/transformer_engine/common/tvm_ffi_bridge.h b/transformer_engine/common/tvm_ffi_bridge.h index 1c2e7fffe6a..7470b2b5890 100644 --- a/transformer_engine/common/tvm_ffi_bridge.h +++ b/transformer_engine/common/tvm_ffi_bridge.h @@ -507,4 +507,10 @@ extern "C" inline void TVMFFIErrorMoveFromRaised(TVMFFIObjectHandle *result) { transformer_engine::tvm_ffi_bridge::TVMFFICentral::getInstance().move_error(result); } +// TVM-FFI error construction (e.g. in try_cast) references this symbol; backtraces stay empty. +extern "C" inline const TVMFFIByteArray *TVMFFIBacktrace(const char *, int, const char *, int) { + static const TVMFFIByteArray empty{"", 0}; + return ∅ +} + #endif // TRANSFORMER_ENGINE_COMMON_TVM_FFI_BRIDGE_H_ diff --git a/transformer_engine/common/util/cuda_runtime.h b/transformer_engine/common/util/cuda_runtime.h index 02f95c08f1e..9ef9e334d03 100644 --- a/transformer_engine/common/util/cuda_runtime.h +++ b/transformer_engine/common/util/cuda_runtime.h @@ -38,6 +38,9 @@ int sm_arch(int device_id = -1); */ int sm_count(int device_id = -1); +/* \brief Clusters of cluster_size CTAs, one CTA per SM, the current device runs at once */ +int max_active_clusters(int cluster_size); + /* \brief Maximum shared memory per block available with opt-in * * This is the upper bound for the static plus dynamic shared memory diff --git a/transformer_engine/common/util/utils.cu b/transformer_engine/common/util/utils.cu index 39d82624632..3f39423592e 100644 --- a/transformer_engine/common/util/utils.cu +++ b/transformer_engine/common/util/utils.cu @@ -9,8 +9,11 @@ #include #include +#include +#include #include "../common.h" +#include "../util/cuda_runtime.h" #include "../util/logging.h" namespace transformer_engine { @@ -80,3 +83,51 @@ void nvte_convert_pointers_to_tensor(const uint64_t *host_ptrs, NVTETensor outpu nvte_copy_host_to_device_via_kernel(host_ptrs, out_tensor->data.dptr, static_cast(count) * sizeof(uint64_t), stream); } + +namespace transformer_engine { + +namespace { + +// Occupancy probe for cuda::max_active_clusters: empty on purpose, only its launch bounds and +// cluster dim matter. +__global__ void cluster_probe_kernel() {} + +} // namespace + +namespace cuda { + +int max_active_clusters(int cluster_size) { + static std::mutex mutex; + // Occupancy depends on the device and the cluster size, so the cache keys on both. + static std::unordered_map clusters_by_device_and_size; + const int device = current_device(); + const int64_t key = (static_cast(device) << 32) | static_cast(cluster_size); + std::lock_guard lock(mutex); + auto it = clusters_by_device_and_size.find(key); + if (it == clusters_by_device_and_size.end()) { + // All the shared memory a CTA may take: one CTA per SM. + int smem = 0; + NVTE_CHECK_CUDA(cudaDeviceGetAttribute(&smem, cudaDevAttrMaxSharedMemoryPerBlockOptin, device)); + NVTE_CHECK_CUDA(cudaFuncSetAttribute(cluster_probe_kernel, + cudaFuncAttributeMaxDynamicSharedMemorySize, smem)); + cudaLaunchAttribute attr{}; + attr.id = cudaLaunchAttributeClusterDimension; + attr.val.clusterDim.x = cluster_size; + attr.val.clusterDim.y = 1; + attr.val.clusterDim.z = 1; + cudaLaunchConfig_t config{}; + config.gridDim = dim3(cluster_size, 1, 1); + config.blockDim = dim3(128, 1, 1); + config.dynamicSmemBytes = smem; + config.attrs = &attr; + config.numAttrs = 1; + int clusters = 0; + NVTE_CHECK_CUDA(cudaOccupancyMaxActiveClusters(&clusters, cluster_probe_kernel, &config)); + it = clusters_by_device_and_size.emplace(key, clusters).first; + } + return it->second; +} + +} // namespace cuda + +} // namespace transformer_engine diff --git a/transformer_engine/pytorch/csrc/extensions.h b/transformer_engine/pytorch/csrc/extensions.h index 4a582ac24c2..b7e934e091f 100644 --- a/transformer_engine/pytorch/csrc/extensions.h +++ b/transformer_engine/pytorch/csrc/extensions.h @@ -766,7 +766,9 @@ int64_t get_nccl_comm_ptr(c10d::ProcessGroup *process_group); void ep_initialize(uintptr_t comm_ptr, const std::string &group_name, int64_t num_experts, int64_t max_tokens_per_rank, int64_t max_recv_tokens_per_rank, int64_t hidden_dim, int64_t max_num_sms, pybind11::object max_token_dtype, - bool zero_copy, int64_t num_topk, bool drop_on_overflow); + bool zero_copy, int64_t num_topk, bool drop_on_overflow, + int64_t dispatch_fwd_num_sms, int64_t combine_fwd_num_sms, + int64_t dispatch_bwd_num_sms, int64_t combine_bwd_num_sms); void ep_finalize(); diff --git a/transformer_engine/pytorch/csrc/extensions/ep.cpp b/transformer_engine/pytorch/csrc/extensions/ep.cpp index 343e5f2d4c6..e2fc2857039 100644 --- a/transformer_engine/pytorch/csrc/extensions/ep.cpp +++ b/transformer_engine/pytorch/csrc/extensions/ep.cpp @@ -14,15 +14,20 @@ #include #include +#include #include #include #include #include +#include +#include #include #include +#include #include #include "transformer_engine/comm_window.h" +#include "transformer_engine/ep_gemm.h" // torch's NCCL symm-mem headers (zero-copy path) exist only since torch 2.11; // without them NCCL_HAS_SYMMEM_SUPPORT stays undefined and zero-copy is compiled out. @@ -74,13 +79,10 @@ size_t symm_mem_window_offset(T* sm, ...) { } #endif -// Resolve ``t`` to an NCCL symm-mem window for the zero-copy one-sided path. -// Returns ``kNoWindow`` when symm-mem support isn't compiled in, zero-copy is -// disabled, no group is set, or ``t`` isn't symm-mem-backed; callers pass the -// resulting window unconditionally to the backend. -NVTECommWindow maybe_make_window(const at::Tensor& t) { +// Resolve ``t`` to its NCCL symm-mem window. Returns ``kNoWindow`` when symm-mem +// support isn't compiled in, no group is set, or ``t`` isn't symm-mem-backed. +NVTECommWindow make_window(const at::Tensor& t) { #ifdef NCCL_HAS_SYMMEM_SUPPORT - if (!g_zero_copy_enabled.load(std::memory_order_relaxed)) return kNoWindow; if (g_ep_group_name.empty()) return kNoWindow; c10::intrusive_ptr sm; try { @@ -106,6 +108,29 @@ NVTECommWindow maybe_make_window(const at::Tensor& t) { #endif } +// Resolve ``t`` to an NCCL symm-mem window for the zero-copy one-sided path. +// Returns ``kNoWindow`` when zero-copy is disabled or make_window finds none; +// callers pass the resulting window unconditionally to the backend. +NVTECommWindow maybe_make_window(const at::Tensor& t) { + if (!g_zero_copy_enabled.load(std::memory_order_relaxed)) return kNoWindow; + return make_window(t); +} + +// Window of a symm-mem input and, for MXFP8, of its scales, whatever the +// zero-copy setting. Throws when either is not symm-mem-backed on the EP group. +NVTECommWindow make_input_window(const at::Tensor& t, const std::optional& scale_inv) { + NVTECommWindow win = make_window(t); + NVTE_CHECK(win.window != nullptr, "symm_input needs a symm-mem input on the EP group"); + if (scale_inv.has_value()) { + const NVTECommWindow scale_win = make_window(*scale_inv); + NVTE_CHECK(scale_win.window != nullptr, + "symm_input needs symm-mem input scales on the EP group"); + win.scale_window = scale_win.window; + win.scale_offset = scale_win.offset; + } + return win; +} + // When zero-copy is enabled, the named tensor must be symm-mem-backed on the // EP group. Throws a clear error otherwise. No-op when zero-copy is off or // symm-mem support isn't compiled in. Mirrors maybe_make_window's resolution @@ -172,6 +197,107 @@ size_t check_mxfp8_scale_pair(const at::Tensor& send_scale, const at::Tensor& re return sc_cols; } +// MXFP8 TE tensor of E4M3 rowwise and/or columnwise data (undefined: absent) and E8M0 scales. +TensorWrapper make_mxfp8_tensor(const at::Tensor& rowwise, const at::Tensor& rowwise_scale_inv, + const at::Tensor& columnwise, + const at::Tensor& columnwise_scale_inv, bool swizzled) { + TensorWrapper t(NVTE_MXFP8_1D_SCALING); + for (const bool col : {false, true}) { + const at::Tensor& data = col ? columnwise : rowwise; + const at::Tensor& scale_inv = col ? columnwise_scale_inv : rowwise_scale_inv; + if (!data.defined()) { + continue; + } + NVTE_CHECK(data.scalar_type() == at::kFloat8_e4m3fn && data.is_contiguous() && + scale_inv.defined() && scale_inv.is_contiguous() && + scale_inv.element_size() == 1, + "MXFP8 operands need contiguous E4M3 data and contiguous one-byte E8M0 scales"); + if (col) { + t.set_columnwise_data(data.data_ptr(), DType::kFloat8E4M3, getTensorShape(data)); + t.set_columnwise_scale_inv(scale_inv.data_ptr(), DType::kFloat8E8M0, + getTensorShape(scale_inv)); + } else { + t.set_rowwise_data(data.data_ptr(), DType::kFloat8E4M3, getTensorShape(data)); + t.set_rowwise_scale_inv(scale_inv.data_ptr(), DType::kFloat8E8M0, getTensorShape(scale_inv)); + } + } + t.set_with_gemm_swizzled_scales(swizzled); + return t; +} + +// Columnwise-only MXFP8 TE tensor with GEMM-swizzled scales. +TensorWrapper make_columnwise_mxfp8_tensor(const at::Tensor& data, const at::Tensor& scale_inv) { + return make_mxfp8_tensor(at::Tensor(), at::Tensor(), data, scale_inv, true); +} + +// Rowwise MXFP8 TE tensor when scale_inv is given, else the plain tensor. +TensorWrapper make_maybe_mxfp8_tensor(const at::Tensor& data, + const std::optional& scale_inv, bool swizzled) { + if (!scale_inv.has_value()) { + return makeTransformerEngineTensor(data); + } + return make_mxfp8_tensor(data, *scale_inv, at::Tensor(), at::Tensor(), swizzled); +} + +// Optional weight gradient of an overlapped backward GEMM and the activations it reads: plain, or +// columnwise MXFP8 data with its GEMM-swizzled scales. +class WeightGradTensors { + public: + // input_rowwise: the rowwise MXFP8 input the call requantizes into the columnwise input. + WeightGradTensors(const std::optional& input, + const std::optional& weight_grad, + const std::optional& input_scale_inv = std::nullopt, + const std::optional& input_rowwise = std::nullopt, + const std::optional& input_rowwise_scale_inv = std::nullopt) + : enabled_(weight_grad.has_value()) { + NVTE_CHECK(input.has_value() == enabled_, "wgrad_input and weight_grad must be given together"); + NVTE_CHECK(enabled_ || !input_scale_inv.has_value(), "wgrad_input_scale_inv needs weight_grad"); + NVTE_CHECK(input_rowwise.has_value() == input_rowwise_scale_inv.has_value() && + (input_scale_inv.has_value() || !input_rowwise.has_value()), + "the rowwise wgrad_input needs its scales and a columnwise MXFP8 wgrad_input"); + if (enabled_) { + NVTE_CHECK(input->is_contiguous() && weight_grad->is_contiguous(), + "wgrad_input and weight_grad must be contiguous"); + input_ = input_scale_inv.has_value() + ? make_mxfp8_tensor(input_rowwise.value_or(at::Tensor()), + input_rowwise_scale_inv.value_or(at::Tensor()), *input, + *input_scale_inv, true) + : makeTransformerEngineTensor(*input); + output_ = makeTransformerEngineTensor(*weight_grad); + } + } + NVTETensor input() { return enabled_ ? input_.data() : nullptr; } + NVTETensor output() { return enabled_ ? output_.data() : nullptr; } + + private: + bool enabled_; + TensorWrapper input_; + TensorWrapper output_; +}; + +// A tensor the native call reads or writes through a raw pointer: dense, on the current device. +void check_dense_cuda(const at::Tensor& t, const char* name) { + NVTE_CHECK(t.is_cuda() && t.is_contiguous() && t.device().index() == c10::cuda::current_device(), + name, " must be a contiguous tensor on the current CUDA device"); +} + +using NamedOperand = std::pair; + +const at::Tensor* operand(const at::Tensor& t) { return &t; } +const at::Tensor* operand(const std::optional& t) { + return t.has_value() ? &*t : nullptr; +} + +// The common layer treats every operand pointer as device memory, so each given operand must be a +// CUDA tensor on the current device. +void check_cuda_operands(std::initializer_list operands) { + const auto device = c10::cuda::current_device(); + for (const auto& [name, t] : operands) { + NVTE_CHECK(t == nullptr || (t->is_cuda() && t->device().index() == device), name, + " must be a tensor on the current CUDA device"); + } +} + } // namespace bool ep_get_zero_copy() { return g_zero_copy_enabled.load(std::memory_order_relaxed); } @@ -191,7 +317,9 @@ bool ep_zero_copy_supported() { void ep_initialize(uintptr_t comm_ptr, const std::string& group_name, int64_t num_experts, int64_t max_tokens_per_rank, int64_t max_recv_tokens_per_rank, int64_t hidden_dim, int64_t max_num_sms, pybind11::object max_token_dtype, - bool zero_copy, int64_t num_topk, bool drop_on_overflow) { + bool zero_copy, int64_t num_topk, bool drop_on_overflow, + int64_t dispatch_fwd_num_sms, int64_t combine_fwd_num_sms, + int64_t dispatch_bwd_num_sms, int64_t combine_bwd_num_sms) { NVTE_CHECK(!group_name.empty(), "group_name must be non-empty (used for symm-mem lookup)"); NVTE_CHECK(comm_ptr != 0, "comm_ptr must be non-null (torch NCCL host comm pointer)"); NVTE_CHECK(!g_ep_initialized, "ep_initialize called twice without ep_finalize"); @@ -212,6 +340,10 @@ void ep_initialize(uintptr_t comm_ptr, const std::string& group_name, int64_t nu .zero_copy = zero_copy ? 1 : 0, .num_topk = static_cast(num_topk), .drop_on_overflow = drop_on_overflow ? 1 : 0, + .dispatch_fwd_num_sms = static_cast(dispatch_fwd_num_sms), + .combine_fwd_num_sms = static_cast(combine_fwd_num_sms), + .dispatch_bwd_num_sms = static_cast(dispatch_bwd_num_sms), + .combine_bwd_num_sms = static_cast(combine_bwd_num_sms), }; // Release the GIL only around the native init. It must stay held while pybind11 casts // the ``max_token_dtype`` object above and destroys the by-value ``pybind11::object`` @@ -262,9 +394,14 @@ void ep_prepare(at::Tensor handle_mem, at::Tensor topk_idx, at::Tensor tokens_pe auto stream = at::cuda::getCurrentCUDAStream().stream(); NVTE_CHECK(topk_idx.dim() >= 2, "topk_idx must be at least 2D [..., top_k]"); auto idx_dtype = get_contiguous_topk_idx_te_dtype(topk_idx); - // NCCL EP requires all prepare int output counters to share a dtype. - NVTE_CHECK(tokens_per_expert.scalar_type() == at::kLong, "tokens_per_expert must be int64"); - NVTE_CHECK(total_recv_tokens.scalar_type() == at::kLong, "total_recv_tokens must be int64"); + // NCCL EP requires all prepare int output counters to share a dtype: int64, or int32 for the + // overlapped GEMMs. + NVTE_CHECK( + tokens_per_expert.scalar_type() == at::kLong || tokens_per_expert.scalar_type() == at::kInt, + "tokens_per_expert must be int64 or int32"); + NVTE_CHECK(total_recv_tokens.scalar_type() == tokens_per_expert.scalar_type(), + "total_recv_tokens must have the dtype of tokens_per_expert"); + const DType count_dtype = GetTransformerEngineDType(tokens_per_expert.scalar_type()); const size_t T_flat = topk_idx.numel() / topk_idx.size(-1); const size_t topk_n = static_cast(topk_idx.size(-1)); @@ -272,14 +409,14 @@ void ep_prepare(at::Tensor handle_mem, at::Tensor topk_idx, at::Tensor tokens_pe makeTransformerEngineTensor(topk_idx.data_ptr(), Shape{T_flat, topk_n}, idx_dtype); auto tokens_per_expert_te = makeTransformerEngineTensor( tokens_per_expert.data_ptr(), Shape{static_cast(tokens_per_expert.numel())}, - DType::kInt64); + count_dtype); auto handle_mem_te = makeTransformerEngineTensor( handle_mem.data_ptr(), Shape{static_cast(handle_mem.numel())}, DType::kByte); - // [1] int64 scalar recv-slot total; lets the caller size dispatch outputs + // [1] scalar recv-slot total; lets the caller size dispatch outputs // (eager) or detect overflow past recv_capacity_per_rank (graph mode). auto total_recv_tokens_te = makeTransformerEngineTensor( total_recv_tokens.data_ptr(), Shape{static_cast(total_recv_tokens.numel())}, - DType::kInt64); + count_dtype); auto layer_cfg = make_layer_cfg(top_k, dispatch_output_per_expert_alignment, idx_dtype); nvte_ep_prepare(handle_mem_te.data(), topk_idx_te.data(), tokens_per_expert_te.data(), @@ -712,6 +849,374 @@ void ep_combine_bwd(at::Tensor handle_mem, at::Tensor grad, at::Tensor grad_expe grad_expert_out_win, &layer_cfg, stream); } +// Fresh per-call scratch for the overlapped GEMMs, sized for the group by +// nvte_ep_overlap_workspace_size. Allocated per call like the op's other IO tensors and kept alive +// by the stream until the async GEMM completes; under graph capture it is served from the graph +// pool, as those IO tensors are. +at::Tensor overlap_workspace(int64_t hidden_dim, int64_t ffn_dim, int64_t num_local_experts, + int64_t rows, bool with_weight_grad, bool mxfp8, + const NVTEEpLayerConfig& layer_cfg, const at::Tensor& like) { + const int64_t bytes = static_cast(nvte_ep_overlap_workspace_size( + hidden_dim, ffn_dim, num_local_experts, rows, with_weight_grad, mxfp8, &layer_cfg)); + return at::empty({bytes}, like.options().dtype(at::kByte)); +} + +std::vector ep_dispatch_gemm_fwd( + at::Tensor handle_mem, at::Tensor topk_idx, at::Tensor tokens, at::Tensor topk_weights, + at::Tensor weight, std::optional recv_tokens_opt, + std::optional recv_topk_weights_opt, at::Tensor tokens_per_expert, + std::optional gemm_out_opt, std::optional act_out_opt, int64_t top_k, + int64_t dispatch_output_per_expert_alignment, std::optional total_recv_tokens, + int64_t eager_row_bucket, std::optional tokens_scale_inv, + std::optional recv_scale_inv, std::optional weight_scale_inv, + std::optional act_out_scale_inv, bool symm_input) { + check_cuda_operands({{"handle_mem", operand(handle_mem)}, + {"topk_idx", operand(topk_idx)}, + {"tokens", operand(tokens)}, + {"topk_weights", operand(topk_weights)}, + {"weight", operand(weight)}, + {"recv_tokens", operand(recv_tokens_opt)}, + {"recv_topk_weights", operand(recv_topk_weights_opt)}, + {"tokens_per_expert", operand(tokens_per_expert)}, + {"gemm_out", operand(gemm_out_opt)}, + {"act_out", operand(act_out_opt)}, + {"tokens_scale_inv", operand(tokens_scale_inv)}, + {"recv_scale_inv", operand(recv_scale_inv)}, + {"weight_scale_inv", operand(weight_scale_inv)}, + {"act_out_scale_inv", operand(act_out_scale_inv)}}); + auto stream = at::cuda::getCurrentCUDAStream().stream(); + const bool eager = !recv_tokens_opt.has_value(); + NVTE_CHECK(recv_topk_weights_opt.has_value() != eager && gemm_out_opt.has_value() != eager && + act_out_opt.has_value() != eager, + "pass all of the recv and GEMM outputs, or none (eager)"); + const bool mxfp8 = tokens_scale_inv.has_value(); + NVTE_CHECK(weight_scale_inv.has_value() == mxfp8 && + recv_scale_inv.has_value() == (mxfp8 && !eager) && + act_out_scale_inv.has_value() == (mxfp8 && !eager), + "pass all of the MXFP8 scales, or none; eager allocates the output scales"); + NVTE_CHECK(!total_recv_tokens.has_value() || total_recv_tokens->scalar_type() == at::kInt, + "total_recv_tokens must be int32"); + NVTE_CHECK(!total_recv_tokens.has_value() || total_recv_tokens->is_pinned() || + (total_recv_tokens->is_cuda() && + total_recv_tokens->device().index() == c10::cuda::current_device()), + "total_recv_tokens must be pinned host memory or on the current CUDA device"); + at::Tensor recv_tokens, recv_topk_weights, gemm_out, act_out; + if (eager) { + // Prepare, read the recv total on the host and size the outputs to whole row buckets, all + // in this call; the fused entry then skips the prepare. + NVTE_CHECK(total_recv_tokens.has_value() && total_recv_tokens->is_pinned(), + "eager needs total_recv_tokens in pinned host memory"); + NVTE_CHECK(eager_row_bucket > 0, "eager needs eager_row_bucket > 0"); + ep_prepare(handle_mem, topk_idx, tokens_per_expert, top_k, dispatch_output_per_expert_alignment, + *total_recv_tokens); + NVTE_CHECK_CUDA(cudaStreamSynchronize(stream)); + const int64_t total = *total_recv_tokens->data_ptr(); + const int64_t buckets = std::max((total + eager_row_bucket - 1) / eager_row_bucket, 1); + const int64_t rows = buckets * eager_row_bucket; + const int64_t hidden = tokens.size(1); + const int64_t ffn = weight.size(1) / 2; + recv_tokens = at::empty({rows, hidden}, tokens.options()); + recv_topk_weights = at::empty({rows}, topk_weights.options()); + gemm_out = at::empty({rows, 2 * ffn}, tokens.options().dtype(at::kBFloat16)); + act_out = at::empty({rows, ffn}, tokens.options()); + if (mxfp8) { + const int64_t scale_cols = tokens_scale_inv->size(-1); + NVTE_CHECK(scale_cols > 0 && hidden % scale_cols == 0, "eager MXFP8 tokens_scale_inv cols (", + scale_cols, ") must be a non-zero divisor of hidden (", hidden, ")"); + const int64_t block = hidden / scale_cols; + recv_scale_inv = at::empty({rows, scale_cols}, tokens_scale_inv->options()); + act_out_scale_inv = at::empty({rows * ffn / block}, tokens_scale_inv->options()); + } + } else { + recv_tokens = *recv_tokens_opt; + recv_topk_weights = *recv_topk_weights_opt; + gemm_out = *gemm_out_opt; + act_out = *act_out_opt; + } + NVTE_CHECK(tokens.is_contiguous() && recv_tokens.is_contiguous() && weight.is_contiguous() && + gemm_out.is_contiguous() && act_out.is_contiguous(), + "operands must be contiguous"); + const int64_t recv_rows = recv_tokens.size(0); + NVTE_CHECK(tokens.dim() == 2 && weight.dim() == 3 && weight.size(1) % 2 == 0 && + weight.size(2) == tokens.size(1), + "tokens must be [num_tokens, hidden] and weight [experts, 2 * ffn, hidden]"); + NVTE_CHECK(recv_tokens.dim() == 2 && recv_tokens.size(1) == tokens.size(1) && + recv_topk_weights.numel() == recv_rows && gemm_out.dim() == 2 && + gemm_out.size(0) == recv_rows && gemm_out.size(1) == weight.size(1) && + act_out.dim() == 2 && act_out.size(0) == recv_rows && + act_out.size(1) == weight.size(1) / 2, + "recv_tokens, recv_topk_weights, gemm_out and act_out must have the rows of the " + "recv buffer and the hidden, 2 * ffn and ffn columns of the operands"); + check_dense_cuda(tokens_per_expert, "tokens_per_expert"); + check_dense_cuda(recv_topk_weights, "recv_topk_weights"); + // The expert layout the GEMMs read: expert 0's start (0), then each expert's padded row end. + // Front-pad by 3 so the row ends (expert_token_offsets[1:]) start 16-byte aligned, as the GEMM + // needs. + auto expert_token_offsets = + at::empty({weight.size(0) + 4}, tokens.options().dtype(at::kInt)).slice(0, 3); + auto handle_mem_te = makeTransformerEngineTensor(handle_mem); + auto topk_idx_te = makeTransformerEngineTensor(topk_idx); + auto tokens_te = make_maybe_mxfp8_tensor(tokens, tokens_scale_inv, false); + auto topk_weights_te = makeTransformerEngineTensor(topk_weights); + auto weight_te = make_maybe_mxfp8_tensor(weight, weight_scale_inv, true); + auto recv_tokens_te = make_maybe_mxfp8_tensor(recv_tokens, recv_scale_inv, false); + auto recv_topk_weights_te = makeTransformerEngineTensor(recv_topk_weights); + auto tokens_per_expert_te = makeTransformerEngineTensor(tokens_per_expert); + auto gemm_out_te = makeTransformerEngineTensor(gemm_out); + auto act_out_te = make_maybe_mxfp8_tensor(act_out, act_out_scale_inv, true); + auto expert_token_offsets_te = makeTransformerEngineTensor(expert_token_offsets); + // In eager mode the prepare above wrote the total. + const bool report_total = total_recv_tokens.has_value() && !eager; + TensorWrapper total_recv_tokens_te; + if (report_total) { + total_recv_tokens_te = makeTransformerEngineTensor(*total_recv_tokens); + } + const NVTECommWindow tokens_win = + symm_input ? make_input_window(tokens, tokens_scale_inv) : kNoWindow; + auto layer_cfg = make_layer_cfg(top_k, dispatch_output_per_expert_alignment, + get_contiguous_topk_idx_te_dtype(topk_idx)); + // Forward: no weight gradient. ffn is half the FC1 output rows (gate and up). + auto workspace_t = overlap_workspace(tokens.size(1), weight.size(1) / 2, weight.size(0), + recv_tokens.size(0), false, mxfp8, layer_cfg, tokens); + auto workspace_te = makeTransformerEngineTensor(workspace_t); + nvte_ep_dispatch_gemm_fwd(handle_mem_te.data(), topk_idx_te.data(), tokens_te.data(), tokens_win, + topk_weights_te.data(), weight_te.data(), recv_tokens_te.data(), + recv_topk_weights_te.data(), gemm_out_te.data(), act_out_te.data(), + tokens_per_expert_te.data(), expert_token_offsets_te.data(), + report_total ? total_recv_tokens_te.data() : nullptr, + workspace_te.data(), &layer_cfg, stream); + if (mxfp8) { + return {recv_tokens, recv_topk_weights, gemm_out, act_out, + expert_token_offsets, *recv_scale_inv, *act_out_scale_inv}; + } + return {recv_tokens, recv_topk_weights, gemm_out, act_out, expert_token_offsets}; +} + +void ep_combine_gemm_fwd(at::Tensor handle_mem, at::Tensor gemm_in, at::Tensor expert_token_offsets, + at::Tensor weight, at::Tensor expert_out, at::Tensor result, int64_t top_k, + int64_t dispatch_output_per_expert_alignment, + at::ScalarType topk_idx_dtype, std::optional recv_topk_weights, + std::optional gemm_in_scale_inv, + std::optional weight_scale_inv) { + check_cuda_operands({{"handle_mem", operand(handle_mem)}, + {"gemm_in", operand(gemm_in)}, + {"expert_token_offsets", operand(expert_token_offsets)}, + {"weight", operand(weight)}, + {"expert_out", operand(expert_out)}, + {"result", operand(result)}, + {"recv_topk_weights", operand(recv_topk_weights)}, + {"gemm_in_scale_inv", operand(gemm_in_scale_inv)}, + {"weight_scale_inv", operand(weight_scale_inv)}}); + auto stream = at::cuda::getCurrentCUDAStream().stream(); + NVTE_CHECK(gemm_in.is_contiguous() && weight.is_contiguous() && expert_out.is_contiguous() && + result.is_contiguous(), + "operands must be contiguous"); + NVTE_CHECK(gemm_in.dim() == 2 && weight.dim() == 3 && weight.size(2) == gemm_in.size(1) && + expert_out.dim() == 2 && expert_out.size(0) == gemm_in.size(0) && + expert_out.size(1) == weight.size(1) && result.dim() == 2 && + result.size(1) == weight.size(1), + "gemm_in must be [rows, ffn], weight [experts, hidden, ffn], expert_out [rows, " + "hidden] and result [num_tokens, hidden]"); + check_dense_cuda(expert_token_offsets, "expert_token_offsets"); + NVTE_CHECK(gemm_in_scale_inv.has_value() == weight_scale_inv.has_value(), + "pass both MXFP8 scales, or none"); + auto handle_mem_te = makeTransformerEngineTensor(handle_mem); + auto gemm_in_te = make_maybe_mxfp8_tensor(gemm_in, gemm_in_scale_inv, true); + TensorWrapper recv_topk_weights_te; + if (recv_topk_weights.has_value()) { + recv_topk_weights_te = makeTransformerEngineTensor(*recv_topk_weights); + } + auto expert_token_offsets_te = makeTransformerEngineTensor(expert_token_offsets); + auto weight_te = make_maybe_mxfp8_tensor(weight, weight_scale_inv, true); + auto expert_out_te = makeTransformerEngineTensor(expert_out); + auto result_te = makeTransformerEngineTensor(result); + auto layer_cfg = make_layer_cfg(top_k, dispatch_output_per_expert_alignment, + get_topk_idx_te_dtype(topk_idx_dtype)); + // FC2 weight is [experts, hidden, ffn]; the combine GEMM has no weight gradient. + const bool mxfp8 = gemm_in_scale_inv.has_value(); + auto workspace_t = overlap_workspace(weight.size(1), weight.size(2), weight.size(0), + gemm_in.size(0), false, mxfp8, layer_cfg, gemm_in); + auto workspace_te = makeTransformerEngineTensor(workspace_t); + nvte_ep_combine_gemm_fwd(handle_mem_te.data(), gemm_in_te.data(), + recv_topk_weights.has_value() ? recv_topk_weights_te.data() : nullptr, + expert_token_offsets_te.data(), weight_te.data(), expert_out_te.data(), + result_te.data(), workspace_te.data(), &layer_cfg, stream); +} + +void ep_combine_gemm_bwd( + at::Tensor handle_mem, at::Tensor grad_result, at::Tensor gemm_out, + at::Tensor recv_topk_weights, at::Tensor tokens_per_expert, at::Tensor weight, + at::Tensor grad_expert_out, at::Tensor grad_gemm_out, at::Tensor grad_recv_topk_weights, + int64_t top_k, int64_t dispatch_output_per_expert_alignment, at::ScalarType topk_idx_dtype, + std::optional grad_result_scale_inv, + std::optional grad_expert_out_scale_inv, std::optional weight_scale_inv, + std::optional grad_gemm_out_scale_inv, + std::optional grad_gemm_out_columnwise, + std::optional grad_gemm_out_columnwise_scale_inv, std::optional act_out, + std::optional act_out_scale_inv, std::optional wgrad_input, + std::optional weight_grad, bool accumulate_weight_grad, + std::optional grad_expert_out_columnwise, + std::optional grad_expert_out_columnwise_scale_inv, + std::optional wgrad_input_scale_inv, bool symm_input) { + check_cuda_operands( + {{"handle_mem", operand(handle_mem)}, + {"grad_result", operand(grad_result)}, + {"gemm_out", operand(gemm_out)}, + {"recv_topk_weights", operand(recv_topk_weights)}, + {"tokens_per_expert", operand(tokens_per_expert)}, + {"weight", operand(weight)}, + {"grad_expert_out", operand(grad_expert_out)}, + {"grad_gemm_out", operand(grad_gemm_out)}, + {"grad_recv_topk_weights", operand(grad_recv_topk_weights)}, + {"grad_result_scale_inv", operand(grad_result_scale_inv)}, + {"grad_expert_out_scale_inv", operand(grad_expert_out_scale_inv)}, + {"weight_scale_inv", operand(weight_scale_inv)}, + {"grad_gemm_out_scale_inv", operand(grad_gemm_out_scale_inv)}, + {"grad_gemm_out_columnwise", operand(grad_gemm_out_columnwise)}, + {"grad_gemm_out_columnwise_scale_inv", operand(grad_gemm_out_columnwise_scale_inv)}, + {"act_out", operand(act_out)}, + {"act_out_scale_inv", operand(act_out_scale_inv)}, + {"wgrad_input", operand(wgrad_input)}, + {"weight_grad", operand(weight_grad)}, + {"grad_expert_out_columnwise", operand(grad_expert_out_columnwise)}, + {"grad_expert_out_columnwise_scale_inv", operand(grad_expert_out_columnwise_scale_inv)}, + {"wgrad_input_scale_inv", operand(wgrad_input_scale_inv)}}); + auto stream = at::cuda::getCurrentCUDAStream().stream(); + NVTE_CHECK(grad_result.is_contiguous() && gemm_out.is_contiguous() && weight.is_contiguous() && + grad_expert_out.is_contiguous() && grad_gemm_out.is_contiguous(), + "operands must be contiguous"); + check_dense_cuda(tokens_per_expert, "tokens_per_expert"); + check_dense_cuda(grad_recv_topk_weights, "grad_recv_topk_weights"); + const bool mxfp8 = grad_result_scale_inv.has_value(); + NVTE_CHECK(grad_expert_out_scale_inv.has_value() == mxfp8 && + weight_scale_inv.has_value() == mxfp8 && + grad_gemm_out_scale_inv.has_value() == mxfp8 && + grad_gemm_out_columnwise.has_value() == mxfp8 && + grad_gemm_out_columnwise_scale_inv.has_value() == mxfp8 && + act_out.has_value() == mxfp8 && act_out_scale_inv.has_value() == mxfp8, + "pass all of the MXFP8 operands, or none"); + // The columnwise grad_expert_out of the MXFP8 weight gradient, written by the call. + const bool grad_expert_out_columns = grad_expert_out_columnwise.has_value(); + NVTE_CHECK(grad_expert_out_columnwise_scale_inv.has_value() == grad_expert_out_columns && + (mxfp8 || !grad_expert_out_columns), + "pass the MXFP8 columnwise grad_expert_out with its scales, or neither"); + auto handle_mem_te = makeTransformerEngineTensor(handle_mem); + auto grad_result_te = make_maybe_mxfp8_tensor(grad_result, grad_result_scale_inv, false); + auto gemm_out_te = makeTransformerEngineTensor(gemm_out); + auto recv_topk_weights_te = makeTransformerEngineTensor(recv_topk_weights); + auto tokens_per_expert_te = makeTransformerEngineTensor(tokens_per_expert); + // MXFP8 reads the forward weight columnwise. + auto weight_te = mxfp8 ? make_columnwise_mxfp8_tensor(weight, *weight_scale_inv) + : makeTransformerEngineTensor(weight); + auto grad_expert_out_te = + grad_expert_out_columns + ? make_mxfp8_tensor(grad_expert_out, *grad_expert_out_scale_inv, + *grad_expert_out_columnwise, *grad_expert_out_columnwise_scale_inv, + false) + : make_maybe_mxfp8_tensor(grad_expert_out, grad_expert_out_scale_inv, false); + auto grad_gemm_out_te = + mxfp8 ? make_mxfp8_tensor(grad_gemm_out, *grad_gemm_out_scale_inv, *grad_gemm_out_columnwise, + *grad_gemm_out_columnwise_scale_inv, true) + : makeTransformerEngineTensor(grad_gemm_out); + auto grad_recv_topk_weights_te = makeTransformerEngineTensor(grad_recv_topk_weights); + TensorWrapper act_out_te; + if (mxfp8) { + act_out_te = make_columnwise_mxfp8_tensor(*act_out, *act_out_scale_inv); + } + NVTE_CHECK(mxfp8 || !wgrad_input_scale_inv.has_value(), + "wgrad_input_scale_inv is for MXFP8 only"); + WeightGradTensors wgrad(wgrad_input, weight_grad, wgrad_input_scale_inv); + const NVTECommWindow grad_result_win = + symm_input ? make_input_window(grad_result, grad_result_scale_inv) : kNoWindow; + auto layer_cfg = make_layer_cfg(top_k, dispatch_output_per_expert_alignment, + get_topk_idx_te_dtype(topk_idx_dtype)); + // FC2 weight is [experts, hidden, ffn]; size the wgrad region when a weight gradient is written. + auto workspace_t = + overlap_workspace(weight.size(1), weight.size(2), weight.size(0), grad_expert_out.size(0), + weight_grad.has_value(), mxfp8, layer_cfg, grad_result); + auto workspace_te = makeTransformerEngineTensor(workspace_t); + nvte_ep_combine_gemm_bwd( + handle_mem_te.data(), grad_result_te.data(), grad_result_win, gemm_out_te.data(), + recv_topk_weights_te.data(), tokens_per_expert_te.data(), weight_te.data(), wgrad.input(), + grad_expert_out_te.data(), grad_gemm_out_te.data(), grad_recv_topk_weights_te.data(), + mxfp8 ? act_out_te.data() : nullptr, wgrad.output(), accumulate_weight_grad, + workspace_te.data(), &layer_cfg, stream); +} + +void ep_dispatch_gemm_bwd( + at::Tensor handle_mem, at::Tensor grad_gemm_out, at::Tensor grad_recv_topk_weights, + at::Tensor tokens_per_expert, at::Tensor weight, at::Tensor grad_recv_tokens, + at::Tensor grad_tokens, at::Tensor grad_topk_weights, int64_t top_k, + int64_t dispatch_output_per_expert_alignment, at::ScalarType topk_idx_dtype, + std::optional grad_gemm_out_scale_inv, std::optional weight_scale_inv, + std::optional grad_gemm_out_columnwise, + std::optional grad_gemm_out_columnwise_scale_inv, + std::optional wgrad_input, std::optional wgrad_input_scale_inv, + std::optional weight_grad, bool accumulate_weight_grad, + std::optional wgrad_input_rowwise, + std::optional wgrad_input_rowwise_scale_inv) { + check_cuda_operands( + {{"handle_mem", operand(handle_mem)}, + {"grad_gemm_out", operand(grad_gemm_out)}, + {"grad_recv_topk_weights", operand(grad_recv_topk_weights)}, + {"tokens_per_expert", operand(tokens_per_expert)}, + {"weight", operand(weight)}, + {"grad_recv_tokens", operand(grad_recv_tokens)}, + {"grad_tokens", operand(grad_tokens)}, + {"grad_topk_weights", operand(grad_topk_weights)}, + {"grad_gemm_out_scale_inv", operand(grad_gemm_out_scale_inv)}, + {"weight_scale_inv", operand(weight_scale_inv)}, + {"grad_gemm_out_columnwise", operand(grad_gemm_out_columnwise)}, + {"grad_gemm_out_columnwise_scale_inv", operand(grad_gemm_out_columnwise_scale_inv)}, + {"wgrad_input", operand(wgrad_input)}, + {"wgrad_input_scale_inv", operand(wgrad_input_scale_inv)}, + {"weight_grad", operand(weight_grad)}, + {"wgrad_input_rowwise", operand(wgrad_input_rowwise)}, + {"wgrad_input_rowwise_scale_inv", operand(wgrad_input_rowwise_scale_inv)}}); + auto stream = at::cuda::getCurrentCUDAStream().stream(); + NVTE_CHECK( + grad_gemm_out.is_contiguous() && weight.is_contiguous() && grad_recv_tokens.is_contiguous(), + "operands must be contiguous"); + check_dense_cuda(tokens_per_expert, "tokens_per_expert"); + check_dense_cuda(grad_recv_topk_weights, "grad_recv_topk_weights"); + const bool mxfp8 = grad_gemm_out_scale_inv.has_value(); + NVTE_CHECK(weight_scale_inv.has_value() == mxfp8, "pass both MXFP8 scales, or none"); + // The MXFP8 weight gradient reads grad_gemm_out and wgrad_input columnwise. + const bool columnwise = grad_gemm_out_columnwise.has_value(); + NVTE_CHECK(grad_gemm_out_columnwise_scale_inv.has_value() == columnwise && + wgrad_input_scale_inv.has_value() == columnwise && (mxfp8 || !columnwise), + "pass the MXFP8 columnwise operands of the weight gradient together, or none"); + auto handle_mem_te = makeTransformerEngineTensor(handle_mem); + auto grad_gemm_out_te = + columnwise + ? make_mxfp8_tensor(grad_gemm_out, *grad_gemm_out_scale_inv, *grad_gemm_out_columnwise, + *grad_gemm_out_columnwise_scale_inv, true) + : make_maybe_mxfp8_tensor(grad_gemm_out, grad_gemm_out_scale_inv, true); + auto grad_recv_topk_weights_te = makeTransformerEngineTensor(grad_recv_topk_weights); + auto tokens_per_expert_te = makeTransformerEngineTensor(tokens_per_expert); + // MXFP8 reads the forward weight columnwise. + auto weight_te = mxfp8 ? make_columnwise_mxfp8_tensor(weight, *weight_scale_inv) + : makeTransformerEngineTensor(weight); + auto grad_recv_tokens_te = makeTransformerEngineTensor(grad_recv_tokens); + auto grad_tokens_te = makeTransformerEngineTensor(grad_tokens); + auto grad_topk_weights_te = makeTransformerEngineTensor(grad_topk_weights); + WeightGradTensors wgrad(wgrad_input, weight_grad, wgrad_input_scale_inv, wgrad_input_rowwise, + wgrad_input_rowwise_scale_inv); + auto layer_cfg = make_layer_cfg(top_k, dispatch_output_per_expert_alignment, + get_topk_idx_te_dtype(topk_idx_dtype)); + // FC1 weight is [experts, 2 * ffn, hidden]; size the wgrad region when a weight gradient is + // written. + auto workspace_t = + overlap_workspace(weight.size(2), weight.size(1) / 2, weight.size(0), grad_gemm_out.size(0), + weight_grad.has_value(), mxfp8, layer_cfg, grad_gemm_out); + auto workspace_te = makeTransformerEngineTensor(workspace_t); + nvte_ep_dispatch_gemm_bwd(handle_mem_te.data(), grad_gemm_out_te.data(), + grad_recv_topk_weights_te.data(), tokens_per_expert_te.data(), + weight_te.data(), wgrad.input(), grad_recv_tokens_te.data(), + grad_tokens_te.data(), grad_topk_weights_te.data(), wgrad.output(), + accumulate_weight_grad, workspace_te.data(), &layer_cfg, stream); +} + void register_ep_bindings(pybind11::module_& m) { namespace py = pybind11; m.def("ep_initialize", &ep_initialize, @@ -719,7 +1224,9 @@ void register_ep_bindings(pybind11::module_& m) { py::arg("comm_ptr"), py::arg("group_name"), py::arg("num_experts"), py::arg("max_tokens_per_rank"), py::arg("max_recv_tokens_per_rank"), py::arg("hidden_dim"), py::arg("max_num_sms") = 0, py::arg("max_token_dtype"), py::arg("zero_copy") = false, - py::arg("num_topk") = 0, py::arg("drop_on_overflow") = false); + py::arg("num_topk") = 0, py::arg("drop_on_overflow") = false, + py::arg("dispatch_fwd_num_sms") = 0, py::arg("combine_fwd_num_sms") = 0, + py::arg("dispatch_bwd_num_sms") = 0, py::arg("combine_bwd_num_sms") = 0); m.def("ep_finalize", &ep_finalize, "Tear down the EP backend. Idempotent.", py::call_guard()); m.def("ep_get_zero_copy", &ep_get_zero_copy, "Return the current EP zero-copy toggle state."); @@ -746,6 +1253,57 @@ void register_ep_bindings(pybind11::module_& m) { m.def("ep_combine", &ep_combine, "EP combine", py::arg("handle_mem"), py::arg("expert_out"), py::arg("result"), py::arg("top_k"), py::arg("dispatch_output_per_expert_alignment"), py::arg("topk_idx_dtype"), py::call_guard()); + m.def("ep_dispatch_gemm_fwd", &ep_dispatch_gemm_fwd, + "EP dispatch overlapped with the first GEMM. Returns recv_tokens, recv_topk_weights, " + "gemm_out, act_out and expert_token_offsets, then the recv and act_out scales when " + "MXFP8; in eager mode omit them and they are sized and allocated here", + py::arg("handle_mem"), py::arg("topk_idx"), py::arg("tokens"), py::arg("topk_weights"), + py::arg("weight"), py::arg("recv_tokens"), py::arg("recv_topk_weights"), + py::arg("tokens_per_expert"), py::arg("gemm_out"), py::arg("act_out"), py::arg("top_k"), + py::arg("dispatch_output_per_expert_alignment"), + py::arg("total_recv_tokens") = std::nullopt, py::arg("eager_row_bucket") = 0, + py::arg("tokens_scale_inv") = std::nullopt, py::arg("recv_scale_inv") = std::nullopt, + py::arg("weight_scale_inv") = std::nullopt, py::arg("act_out_scale_inv") = std::nullopt, + py::arg("symm_input") = false, py::call_guard()); + m.def("ep_combine_gemm_fwd", &ep_combine_gemm_fwd, "EP second GEMM overlapped with the combine", + py::arg("handle_mem"), py::arg("gemm_in"), py::arg("expert_token_offsets"), + py::arg("weight"), py::arg("expert_out"), py::arg("result"), py::arg("top_k"), + py::arg("dispatch_output_per_expert_alignment"), py::arg("topk_idx_dtype"), + py::arg("recv_topk_weights") = std::nullopt, py::arg("gemm_in_scale_inv") = std::nullopt, + py::arg("weight_scale_inv") = std::nullopt, py::call_guard()); + m.def("ep_combine_gemm_bwd", &ep_combine_gemm_bwd, + "Backward of the second GEMM and the combine, with the activation backward", + py::arg("handle_mem"), py::arg("grad_result"), py::arg("gemm_out"), + py::arg("recv_topk_weights"), py::arg("tokens_per_expert"), py::arg("weight"), + py::arg("grad_expert_out"), py::arg("grad_gemm_out"), py::arg("grad_recv_topk_weights"), + py::arg("top_k"), py::arg("dispatch_output_per_expert_alignment"), + py::arg("topk_idx_dtype"), py::arg("grad_result_scale_inv") = std::nullopt, + py::arg("grad_expert_out_scale_inv") = std::nullopt, + py::arg("weight_scale_inv") = std::nullopt, + py::arg("grad_gemm_out_scale_inv") = std::nullopt, + py::arg("grad_gemm_out_columnwise") = std::nullopt, + py::arg("grad_gemm_out_columnwise_scale_inv") = std::nullopt, + py::arg("act_out") = std::nullopt, py::arg("act_out_scale_inv") = std::nullopt, + py::arg("wgrad_input") = std::nullopt, py::arg("weight_grad") = std::nullopt, + py::arg("accumulate_weight_grad") = false, + py::arg("grad_expert_out_columnwise") = std::nullopt, + py::arg("grad_expert_out_columnwise_scale_inv") = std::nullopt, + py::arg("wgrad_input_scale_inv") = std::nullopt, py::arg("symm_input") = false, + py::call_guard()); + m.def( + "ep_dispatch_gemm_bwd", &ep_dispatch_gemm_bwd, "Backward of the first GEMM and the dispatch", + py::arg("handle_mem"), py::arg("grad_gemm_out"), py::arg("grad_recv_topk_weights"), + py::arg("tokens_per_expert"), py::arg("weight"), py::arg("grad_recv_tokens"), + py::arg("grad_tokens"), py::arg("grad_topk_weights"), py::arg("top_k"), + py::arg("dispatch_output_per_expert_alignment"), py::arg("topk_idx_dtype"), + py::arg("grad_gemm_out_scale_inv") = std::nullopt, py::arg("weight_scale_inv") = std::nullopt, + py::arg("grad_gemm_out_columnwise") = std::nullopt, + py::arg("grad_gemm_out_columnwise_scale_inv") = std::nullopt, + py::arg("wgrad_input") = std::nullopt, py::arg("wgrad_input_scale_inv") = std::nullopt, + py::arg("weight_grad") = std::nullopt, py::arg("accumulate_weight_grad") = false, + py::arg("wgrad_input_rowwise") = std::nullopt, + py::arg("wgrad_input_rowwise_scale_inv") = std::nullopt, + py::call_guard()); m.def("ep_dispatch_bwd", &ep_dispatch_bwd, "EP dispatch backward", py::arg("handle_mem"), py::arg("grad"), py::arg("g_recv_topk_weights"), py::arg("grad_tokens"), py::arg("grad_topk_weights"), py::arg("top_k"), diff --git a/transformer_engine/pytorch/ep.py b/transformer_engine/pytorch/ep.py index 614affc70fc..98dbc10310d 100644 --- a/transformer_engine/pytorch/ep.py +++ b/transformer_engine/pytorch/ep.py @@ -6,6 +6,9 @@ from __future__ import annotations import atexit +import functools +import math +import os import warnings from dataclasses import dataclass from typing import Optional, TYPE_CHECKING @@ -15,11 +18,13 @@ import transformer_engine_torch as tex +from ..common import _load_core_library from .constants import DType from .cpu_offload import mark_not_offload from .distributed import symm_mem_alloc, release_symm_mem_pool from .quantized_tensor import QuantizedTensor, QuantizedTensorStorage from .tensor.storage.mxfp8_tensor_storage import MXFP8TensorStorage +from .utils import round_up_to_nearest_multiple # Type-hint-only import; keeps the ``Recipe`` annotation without a runtime import of # common.recipe (the concrete recipe classes are imported lazily where used). @@ -84,11 +89,15 @@ def _check_nccl_runtime_version() -> None: _ATEXIT_REGISTERED = False # EP group captured at bootstrap; used by the zero-copy symm-mem pool allocator. _EP_GROUP: Optional[dist.ProcessGroup] = None +# Communication SMs of the overlapped MoE ops when ep_bootstrap picks them. +_OVERLAP_COMM_SMS = 24 # Eager-mode toggle captured at bootstrap (set when recv_capacity_per_rank is # omitted); ep_dispatch reads it to size the recv outputs from the per-step # recv-token total instead of a fixed recv_capacity_per_rank. _EAGER = False _BOOTSTRAP_SETTINGS: Optional[dict[str, object]] = None +# Symm-mem data and scale buffers the overlapped MoE ops quantize their MXFP8 dispatch inputs into. +_DISPATCH_WINDOW: Optional[tuple[torch.Tensor, torch.Tensor]] = None @dataclass(frozen=True, slots=True) @@ -125,9 +134,10 @@ class EpConfig: def _atexit_finalize() -> None: """Best-effort teardown at interpreter shutdown; swallows errors.""" - global _BOOTSTRAPPED, _EP_GROUP, _EAGER, _BOOTSTRAP_SETTINGS + global _BOOTSTRAPPED, _EP_GROUP, _EAGER, _BOOTSTRAP_SETTINGS, _DISPATCH_WINDOW if _BOOTSTRAPPED: try: + _DISPATCH_WINDOW = None tex.ep_finalize() except Exception: # pylint: disable=broad-exception-caught import traceback @@ -151,6 +161,10 @@ def ep_bootstrap( zero_copy: bool = False, drop_on_overflow: bool = False, max_token_dtype: torch.dtype = torch.bfloat16, + dispatch_fwd_num_sms: int = 0, + combine_fwd_num_sms: int = 0, + dispatch_bwd_num_sms: int = 0, + combine_bwd_num_sms: int = 0, ) -> None: """Initialize EP by borrowing ep_group's NCCL comm. Call once per process. @@ -172,9 +186,22 @@ def ep_bootstrap( ``drop_on_overflow`` drops tokens exceeding ``recv_capacity_per_rank`` instead of trapping. Requires ``recv_capacity_per_rank``. + + ``max_num_sms`` defaults to 24 when the ``te.ops`` MoE overlap is available + (``NVTE_ENABLE_CUTEDSL_BACKEND=1``, ``NVTE_MOE_OVERLAP`` set) and ``zero_copy`` is off. + + ``dispatch_fwd_num_sms``, ``combine_fwd_num_sms``, ``dispatch_bwd_num_sms`` and + ``combine_bwd_num_sms`` set the SMs of the NCCL EP kernels of the dispatch and combine of the + layer forward and backward, overlapped or not. The backward of MoeCombine is a dispatch and the + backward of MoeDispatch a combine. 0 inherits: a forward budget takes ``max_num_sms``, a + backward budget the forward one. ``FusedMoE`` runs the GEMMs on the remaining SMs. A backward + budget other than the forward one needs NCCL EP with backward SM budgets. ``NCCL_EP_COMM_SMS`` + and NCCL EP's per-call SM variables override these counts, and ``FusedMoE`` rejects them. """ global _BOOTSTRAPPED, _ATEXIT_REGISTERED, _EP_GROUP, _EAGER, _BOOTSTRAP_SETTINGS eager = recv_capacity_per_rank is None + if max_num_sms == 0 and _moe_overlap_available() and not zero_copy: + max_num_sms = _OVERLAP_COMM_SMS if _BOOTSTRAPPED: raise RuntimeError("ep_bootstrap was already called in this process") if ep_group.size() < 2: @@ -216,6 +243,10 @@ def ep_bootstrap( bool(zero_copy), int(num_topk), bool(drop_on_overflow), + int(dispatch_fwd_num_sms), + int(combine_fwd_num_sms), + int(dispatch_bwd_num_sms), + int(combine_bwd_num_sms), ) _BOOTSTRAPPED = True _EP_GROUP = ep_group @@ -254,6 +285,28 @@ def get_ep_drop_on_overflow() -> Optional[bool]: return bool(_BOOTSTRAP_SETTINGS["drop_on_overflow"]) +@functools.lru_cache(maxsize=None) +def _cutedsl_backend_built() -> bool: + """Whether the core library was built with the CuTeDSL backend.""" + core = _load_core_library() + return hasattr(core, "nvte_is_cutedsl_backend_built") and bool( + core.nvte_is_cutedsl_backend_built() + ) + + +def _moe_overlap_available() -> bool: + """Whether the overlapped MoE GEMMs can run: SM 10.0, 10.3 or 10.7 (tcgen05 kernels), the + CuTeDSL backend built and on, and the GEMM path set.""" + if not torch.cuda.is_available(): + return False + return ( + torch.cuda.get_device_capability() in ((10, 0), (10, 3), (10, 7)) + and os.environ.get("NVTE_ENABLE_CUTEDSL_BACKEND", "0") != "0" + and bool(os.environ.get("NVTE_MOE_OVERLAP")) + and _cutedsl_backend_built() + ) + + def _ep_is_eager() -> bool: """Return whether the bootstrapped EP group uses variable-size eager buffers.""" return _EAGER @@ -269,10 +322,11 @@ def ep_finalize() -> None: a caller that used ``symm_mem_alloc(use_pool=True)`` does not need a separate ``release_symm_mem_pool()`` before destroying the PG. """ - global _BOOTSTRAPPED, _EP_GROUP, _EAGER, _BOOTSTRAP_SETTINGS + global _BOOTSTRAPPED, _EP_GROUP, _EAGER, _BOOTSTRAP_SETTINGS, _DISPATCH_WINDOW if not _BOOTSTRAPPED: return try: + _DISPATCH_WINDOW = None # Deregister pooled symm-mem windows while the group's comm is still valid. release_symm_mem_pool() tex.ep_finalize() @@ -330,6 +384,8 @@ class EpBuffer: "zero_copy", "eager", "total_recv_tokens", + "tokens_per_expert_i32", + "total_recv_tokens_i32", "dispatch_fwd_quant_recipe", "combine_bwd_quant_recipe", ) @@ -394,6 +450,17 @@ def __init__( else: self.total_recv_tokens = torch.empty(1, dtype=torch.int64, device=device) mark_not_offload(self.total_recv_tokens) + # Int32 per-expert counts and recv total for the fused MoE overlap, placed as above. + # TODO(phuonguyen): drop these int32 mirrors of tokens_per_expert and total_recv_tokens, + # and write those directly, once the CuTeDSL signal GEMMs accept int64 counts/offsets. + self.tokens_per_expert_i32 = torch.empty( + self.num_local_experts, dtype=torch.int32, device=device + ) + if self.eager: + self.total_recv_tokens_i32 = torch.empty(1, dtype=torch.int32, pin_memory=True) + else: + self.total_recv_tokens_i32 = torch.empty(1, dtype=torch.int32, device=device) + mark_not_offload(self.total_recv_tokens_i32) # torch.library custom ops (so they don't graph-break under torch.compile) @@ -1084,17 +1151,74 @@ def _alloc_io(shape, dtype: torch.dtype, device, zero_copy: bool) -> torch.Tenso return torch.empty(*shape, dtype=dtype, device=device) +def _dispatch_window(device) -> Optional[tuple[torch.Tensor, torch.Tensor]]: + """Symm-mem data and scale buffers of one MXFP8 dispatch input, or None without symm-mem + support. Allocated collectively on first use and shared by every layer and direction, so the + EP calls of the group must share one stream.""" + global _DISPATCH_WINDOW + if _DISPATCH_WINDOW is None: + if not tex.ep_zero_copy_supported(): + return None + if torch.cuda.is_current_stream_capturing(): + raise RuntimeError( + "The EP dispatch window is allocated on first use; run a warmup step before " + "CUDA graph capture." + ) + from .tensor.mxfp8_tensor import MXFP8Quantizer + + 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) + window = symm_mem_alloc( + (data_bytes + math.prod(scale_shape),), torch.uint8, _EP_GROUP, device=device + ) + mark_not_offload(window) + _DISPATCH_WINDOW = (window[:data_bytes], window[data_bytes:]) + return _DISPATCH_WINDOW + + +def _mxfp8_storage(out, shape, quantizer: "MXFP8Quantizer", fake_dtype=None) -> MXFP8TensorStorage: + """Rowwise MXFP8 storage of ``shape`` at the start of the uint8 data and scale buffers ``out``.""" + data, scales = out + for name, buf in (("data", data), ("scale", scales)): + if buf.dtype != torch.uint8 or not buf.is_contiguous(): + raise ValueError(f"MXFP8 {name} output buffer must be a contiguous uint8 tensor.") + if data.device != scales.device: + raise ValueError("MXFP8 data and scale output buffers must be on the same device.") + data, scales = data.view(-1), scales.view(-1) + scale_shape = quantizer.get_scale_shape(shape, False) + if data.numel() < math.prod(shape) or scales.numel() < math.prod(scale_shape): + raise ValueError(f"MXFP8 output buffers too small for {tuple(shape)}.") + return MXFP8TensorStorage( + data[: math.prod(shape)].view(shape), + scales[: math.prod(scale_shape)].view(scale_shape), + None, + None, + quantizer.dtype, + quantizer, + False, + fake_dtype=fake_dtype, + ) + + def quantize_for_ep( input_: torch.Tensor | QuantizedTensorStorage, quantizer: Optional["Quantizer"], + out: Optional[tuple[torch.Tensor, torch.Tensor]] = None, ) -> tuple[MXFP8TensorStorage, torch.Tensor]: - """Quantize an EP input with a supported quantizer.""" + """Quantize an EP input with a supported quantizer. + + ``out`` is a pair of contiguous uint8 tensors on the input's device, the data and the scales. + The data holds ``input_.numel()`` bytes and the scales the rowwise scale shape of the quantizer + (``get_scale_shape(shape, False)``, rows padded to 128). When given, the returned storage and + the compact scales it returns are views of them, so they alias ``out``. + """ from .tensor.mxfp8_tensor import MXFP8Quantizer if quantizer is None: raise ValueError("EP quantization requires a quantizer.") if isinstance(quantizer, MXFP8Quantizer): - return _quantize_mxfp8(input_, quantizer) + return _quantize_mxfp8(input_, quantizer, out) raise NotImplementedError( "EP dispatch/combine quantization currently supports only MXFP8; " f"got {type(quantizer).__name__}." @@ -1104,12 +1228,19 @@ def quantize_for_ep( def _quantize_mxfp8( input_: torch.Tensor | QuantizedTensorStorage, quantizer: "MXFP8Quantizer", + out: Optional[tuple[torch.Tensor, torch.Tensor]] = None, ) -> tuple[MXFP8TensorStorage, torch.Tensor]: """Return E4M3 MXFP8 storage and compact rowwise scales for EP.""" from .constants import MXFP8_BLOCK_SCALING_SIZE if quantizer.dtype != DType.kFloat8E4M3: raise NotImplementedError("EP supports only E4M3 MXFP8 data.") + if out is not None: + input_device = ( + input_._rowwise_data.device if isinstance(input_, MXFP8TensorStorage) else input_.device + ) + if out[0].device != input_device: + raise ValueError(f"EP output buffers must be on the input's device {input_device}.") if isinstance(input_, MXFP8TensorStorage): quantized = input_ elif isinstance(input_, QuantizedTensorStorage): @@ -1118,7 +1249,11 @@ def _quantize_mxfp8( if not quantizer.internal: quantizer = quantizer.copy() quantizer.internal = True - quantized = quantizer(input_) + if out is None: + quantized = quantizer(input_) + else: + quantized = _mxfp8_storage(out, input_.shape, quantizer, input_.dtype) + tex.quantize(input_, quantizer, quantized, None) if quantized._fp8_dtype != DType.kFloat8E4M3: raise NotImplementedError("EP supports only E4M3 MXFP8 data.") @@ -1145,6 +1280,12 @@ def _quantize_mxfp8( scale_inv = scale_inv[:t_flat, :scale_cols] if not scale_inv.is_contiguous(): raise ValueError("EP requires compact contiguous MXFP8 scales.") + if out is not None and quantized is input_: + # An MXFP8 input is copied into out, so the result is there whatever the input. + quantized = _mxfp8_storage(out, input_.shape, quantizer, fake_dtype=input_.dtype) + quantized._rowwise_data.copy_(data) + quantized._rowwise_scale_inv[:t_flat, :scale_cols].copy_(scale_inv) + scale_inv = quantized._rowwise_scale_inv[:t_flat, :scale_cols] return quantized, scale_inv diff --git a/transformer_engine/pytorch/ops/__init__.py b/transformer_engine/pytorch/ops/__init__.py index 5e21bb39e8d..4fbbe2c5e8e 100644 --- a/transformer_engine/pytorch/ops/__init__.py +++ b/transformer_engine/pytorch/ops/__init__.py @@ -18,3 +18,4 @@ from .op import BasicOperation, FusedOperation, FusibleOperation from .sequential import Sequential from . import fused +from .fused import moe_overlap_supported, moe_overlap_unsupported_reason diff --git a/transformer_engine/pytorch/ops/fused/__init__.py b/transformer_engine/pytorch/ops/fused/__init__.py index ff1075e6fe2..d1b0b1b715f 100644 --- a/transformer_engine/pytorch/ops/fused/__init__.py +++ b/transformer_engine/pytorch/ops/fused/__init__.py @@ -36,3 +36,8 @@ GroupedMLP_CuTeGEMMUnary, GroupedMLP_CuTeGEMMGLUBf16, ) +from .moe_overlap import ( # pylint: disable=wrong-import-position + FusedMoE, + moe_overlap_supported, + moe_overlap_unsupported_reason, +) diff --git a/transformer_engine/pytorch/ops/fused/moe_overlap.py b/transformer_engine/pytorch/ops/fused/moe_overlap.py new file mode 100644 index 00000000000..e262749bc6d --- /dev/null +++ b/transformer_engine/pytorch/ops/fused/moe_overlap.py @@ -0,0 +1,1138 @@ +# Copyright (c) 2022-2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# See LICENSE for license information. + +"""Fused MoE layer with EP dispatch and combine overlapped with the grouped GEMMs.""" + +from __future__ import annotations + +import functools +from collections.abc import Callable, Sequence +from typing import Any, NamedTuple, Optional + +import torch + +import transformer_engine_torch as tex +from ....common.recipe import Format, MXFP8BlockScaling +from ...constants import MXFP8_BLOCK_SCALING_SIZE +from ...cpu_offload import ( + is_cpu_offload_enabled, + mark_activation_offload, + mark_not_offload, + start_offload, +) +from ...ep import ( + EpConfig, + _dispatch_window, + _make_grouped_mxfp8, + _moe_overlap_available, + quantize_for_ep, +) +from ...distributed_weight import is_distributed_weight +from ...quantization import Recipe +from ...tensor.grouped_tensor import GroupedTensor +from ...tensor.mxfp8_tensor import MXFP8Quantizer +from ...utils import clear_tensor_data, mark_grouped_tensor +from ..basic import ( + GroupedLinear, + MoeCombine, + MoeDispatch, + ScaledClampedQGeGLU, + ScaledSiTUGLU, + ScaledSwiGLU, +) +from ..basic.dispatch import _validate_dispatch_input, _validate_routing_inputs +from ..basic.grouped_linear import GRAD_INPUT_BUFFER_KEY, OUTPUT_BUFFER_KEY +from ..fuser import register_forward_backward_fusion +from ..op import FusedOperation, FusibleOperation, OperationContext +from .._common import maybe_dequantize, validate_ep_buffer +from .grouped_mlp import ( + GroupedMLP_CuTeGEMMGLU, + GroupedMLP_CuTeGEMMGLUBf16, + _bf16_packed_weight, + _bf16_wgrad_fn_factory, + _compute_grad_params, + _deterministic_algorithms_required, + validate_grouped_mlp_dims, +) + +# Recv rows are multiples of this tile, as are hidden_dim and the MXFP8 ffn_hidden_size. +_TILE = 256 +# Each distinct recv-row count compiles a new GEMM, so eager rounds the recv rows up to a multiple +# of this to bound how many are compiled. +_EAGER_ROW_BUCKET = 1024 +_SF_VEC = MXFP8_BLOCK_SCALING_SIZE +# Width of the alternating FC1 gate and up blocks the GEMMs take. +_GLU_BLOCK = 32 + + +class FusedMoE(FusedOperation): + """MoeDispatch, GroupedLinear, ScaledSwiGLU, GroupedLinear and MoeCombine as one op. + + Pipeline: dispatch -> FC1 -> SwiGLU -> FC2 -> combine, with the dispatch overlapped with FC1 + and the combine overlapped with FC2, forward and backward. + + Requirements: + - Packed weights (``single_grouped_weight=True``) without bias: BF16 parameters, or MXFP8 + primary weights (``quantized_model_init``) under ``MXFP8BlockScaling``. + - Contiguous forward inputs. + - EP within one NVLink domain. + - ``EpConfig`` ``alignment`` of 256, 128 or (without a recipe) 64, with the receive capacity + a multiple of 256. + - Recipe of none or ``MXFP8BlockScaling``. + + Notes: + - With the overlap enabled (``NVTE_MOE_OVERLAP``), a ``Sequential`` of these ops that does not + meet the requirements raises an error naming the reason, instead of running unfused; + ``moe_overlap_unsupported_reason`` gives it beforehand. + - Each GEMM allocates a small uint8 workspace for its flags and state in the binding, freed + after the call; the calls of an EP group must run on one CUDA stream. + - With a fixed receive capacity the op can be captured in a CUDA graph after a warmup call; + with eager receive sizing (no ``recv_capacity_per_rank``) the host is synchronized and it + cannot be captured. + - Without a recipe the routing weights are applied in the activation; under + ``MXFP8BlockScaling`` the GEMMs and the EP transport run in MXFP8 and the routing weights + are applied to the second GEMM's output. Either way their gradient goes to the dispatch's + ``topk_weights``. + - The weights are prepared for the GEMMs (quantized to MXFP8, or their FC1 rows reordered) at + each forward. + - The GEMMs take the FC1 gate and up rows in alternating blocks of 32 + (``glu_interleave_size=32``). With ``glu_interleave_size=None`` the FC1 weight rows are + reordered when the weights are prepared and the FC1 weight gradient is returned in the + parameter's own layout. + """ + + @classmethod + def is_supported(cls) -> bool: + """Whether this fused operation can run on the current system.""" + # TODO(phuonguyen): once the kernels and the overlap signals are upstreamed into cuDNN and + # NCCL EP, gate this on their minimum versions instead of the kernel path and interface + # check. + if not _moe_overlap_available() or _gemm_interface_reason() is not None: + return False + if torch.cuda.get_device_capability() != (10, 7): + return GroupedMLP_CuTeGEMMGLUBf16.is_supported() + # SM 10.7 has no BF16 cuDNN GLU kernels; the EP GEMMs replace them, and this op takes only + # the cuDNN wgrad kernel. + try: + kernel = GroupedMLP_CuTeGEMMGLUBf16.grouped_gemm_wgrad_kernel() + except ImportError: + return False + return getattr(kernel, "supports_bf16_canonical_layouts", False) + + def __init__( + self, + *, + dispatch: MoeDispatch, + fc1: GroupedLinear, + activation: ScaledSwiGLU, + fc2: GroupedLinear, + combine: MoeCombine, + recipe: Optional[Recipe] = None, + _validated: bool = False, + ) -> None: + super().__init__((dispatch, fc1, activation, fc2, combine)) + if not _validated: + reason = _unsupported_reason(dispatch, fc1, activation, fc2, combine, recipe=recipe) + if reason is not None: + raise RuntimeError(f"FusedMoE is not supported: {reason}.") + self._mxfp8 = recipe is not None + # The GEMMs take FC1 gate and up rows in alternating blocks of _GLU_BLOCK. + # TODO(phuonguyen): cuDNN upstream supports glu_interleave_size=None; drop the reorder once + # the rebased cuDNN is upstreamed. + self._reorder_glu = activation.glu_interleave_size is None + self._operands = _Mxfp8Operands() if self._mxfp8 else _Bf16Operands(self._reorder_glu) + # The dispatch and combine share one EpBuffer (see _unsupported_reason); FusedMoE reads it + # from self.basic_ops[0].buffer at each forward. + + def fuser_forward( + self, + basic_op_ctxs: list[OperationContext], + input_: torch.Tensor, + *, + basic_op_extra_inputs: list[tuple[torch.Tensor, ...]], + prev_op_grad_output_quantizer, + next_op_input_quantizer, + basic_op_kwargs: list[dict[str, Any]], + ) -> tuple[torch.Tensor, Sequence[Sequence[torch.Tensor]]]: + del prev_op_grad_output_quantizer, next_op_input_quantizer + if any( + key in kwargs + for kwargs in basic_op_kwargs + for key in (OUTPUT_BUFFER_KEY, GRAD_INPUT_BUFFER_KEY) + ): + raise ValueError("FusedMoE allocates its outputs and gradients; it takes no buffers.") + fc2_op = self.basic_ops[3] + topk_idx, topk_weights = basic_op_extra_inputs[0] + # Splits and scales come from the dispatch inside this op. + for extra_inputs in basic_op_extra_inputs[1:-1]: + if any(t is not None for t in extra_inputs): + raise ValueError( + "FusedMoE takes the splits and routing scales from its dispatch; " + "do not pass them as extra inputs." + ) + + buffer = validate_ep_buffer("FusedMoE", self.basic_ops[0].config, self.basic_ops[0].buffer) + input_shape = _validate_dispatch_input(input_, buffer) + _validate_routing_inputs(topk_idx, topk_weights, device=buffer.device) + if topk_idx.dtype not in (torch.int32, torch.int64): + raise TypeError(f"topk_idx must be int32 or int64, got {topk_idx.dtype}.") + # TODO(phuonguyen): revisit once non-BF16 compute dtypes are supported. + if torch.is_autocast_enabled() and torch.get_autocast_dtype("cuda") != torch.bfloat16: + raise RuntimeError("FusedMoE computes in BF16; keep the autocast dtype BF16.") + if not buffer.eager and buffer.recv_capacity_per_rank % _TILE != 0: + raise ValueError( + f"FusedMoE needs the recv rows ({buffer.recv_capacity_per_rank}) to be a" + f" multiple of {_TILE}." + ) + buffer.num_local_tokens = input_shape[0] + buffer.topk_idx_dtype = topk_idx.dtype + + operands = self._operands + device = buffer.device + hidden = buffer.hidden_dim + ffn = fc2_op.in_features + backward = any(ctx.requires_grad for ctx in basic_op_ctxs) + w1, w2 = (self._weight_operands(idx, backward) for idx in (1, 3)) + w1_data, w1_kwargs = operands.weight(w1) + w2_data, w2_kwargs = operands.weight(w2) + tokens, input_kwargs = operands.dispatch_input(_require_contiguous(input_, "input"), device) + topk_idx = _require_contiguous(topk_idx, "topk_idx") + topk_weights = _require_contiguous(topk_weights, "topk_weights") + + tokens_per_expert = buffer.tokens_per_expert_i32 + if buffer.eager: + # The binding runs the prepare, reads the recv total on the host and allocates the + # recv rows in whole buckets, so the number of compiled GEMMs stays bounded. + recv_tokens, recv_weights, gemm_out, act_out, expert_token_offsets, *scale_list = ( + tex.ep_dispatch_gemm_fwd( + buffer.handle_mem, topk_idx, tokens, topk_weights, w1_data, None, None, + tokens_per_expert, None, None, buffer.top_k, buffer.alignment, + buffer.total_recv_tokens_i32, _EAGER_ROW_BUCKET, **input_kwargs, **w1_kwargs, + ) + ) # fmt: skip + scales = dict(zip(operands.scale_names, scale_list)) + rows = recv_tokens.shape[0] + else: + rows = buffer.recv_capacity_per_rank + recv_tokens, gemm_out, act_out, scales = operands.recv_buffers( + rows, hidden, ffn, device + ) + recv_weights = torch.empty(rows, dtype=torch.float32, device=device) + # The dispatch writes the expert layout the GEMMs read. + expert_token_offsets = tex.ep_dispatch_gemm_fwd( + buffer.handle_mem, topk_idx, tokens, topk_weights, w1_data, recv_tokens, + recv_weights, tokens_per_expert, gemm_out, act_out, buffer.top_k, + buffer.alignment, buffer.total_recv_tokens_i32, **input_kwargs, **scales, + **w1_kwargs, + )[4] # fmt: skip + expert_out = torch.empty(rows, hidden, dtype=torch.bfloat16, device=device) + result = torch.empty(buffer.num_local_tokens, hidden, dtype=torch.bfloat16, device=device) + tex.ep_combine_gemm_fwd( + buffer.handle_mem, act_out, expert_token_offsets, w2_data, expert_out, result, + buffer.top_k, buffer.alignment, buffer.topk_idx_dtype, + **operands.combine_kwargs(recv_weights, scales), **w2_kwargs, + ) # fmt: skip + + row_tensors, other_tensors = operands.saved_tensors( + recv_tokens, recv_weights, gemm_out, act_out, scales, w1, w2, backward + ) + self._save_for_backward(basic_op_ctxs, buffer, row_tensors, other_tensors, topk_weights) + return result, [(tokens_per_expert, recv_weights), (), (), (), ()] + + def _save_for_backward(self, basic_op_ctxs, buffer, row_tensors, other_tensors, topk_weights): + """Save the tensors the backward reads, when any output needs a gradient. The operands of + the weight gradient of a frozen weight are not saved.""" + _, fc1_op, _, fc2_op, _ = self.basic_ops + fc1_ctx, fc2_ctx = basic_op_ctxs[1], basic_op_ctxs[3] + if any(ctx.requires_grad for ctx in basic_op_ctxs): + fc1_ctx.weight_requires_grad = fc1_op.weight.requires_grad + fc2_ctx.weight_requires_grad = fc2_op.weight.requires_grad + fc1_ctx.dtype = fc2_ctx.dtype = torch.bfloat16 + operands = self._operands + row_tensors = list(row_tensors) + for ctx, wgrad_inputs in ( + (fc1_ctx, operands.fc1_wgrad_inputs), + (fc2_ctx, operands.fc2_wgrad_inputs), + ): + if not ctx.weight_requires_grad: + for slot in wgrad_inputs: + row_tensors[slot] = None + # Paged stashing keeps only the received rows of each row-sized tensor. + saved_rows = [t for t in row_tensors if t is not None] + mark_grouped_tensor(*saved_rows) + num_tokens = buffer.tokens_per_expert_i32.sum(0, keepdim=True, dtype=torch.int32) + for tensor in saved_rows: + tensor.grouped_tensor_num_tokens = num_tokens + # Publish the kept recv total to the buffer counter paged stashing reads; only needed + # when saving for backward, as stashing is. + buffer.total_recv_tokens.copy_(num_tokens) + # CPU offload takes the activations, as the unfused ops do, not the routing weights. + # The weight copies saved for backward stay on the GPU, as in TE modules. + if is_cpu_offload_enabled(): + offloaded, kept = [], [] + for slot, tensor in enumerate(row_tensors): + if tensor is not None: + (offloaded if slot in operands.offload_slots else kept).append(tensor) + start_offload(*offloaded) + mark_activation_offload(*offloaded) + mark_not_offload(*kept, *other_tensors) + fc1_ctx.save_for_backward(*row_tensors, *other_tensors) + fc1_ctx.buffer = buffer + fc1_ctx.topk_weights_shape = topk_weights.shape + + def _weight_operands(self, idx, columnwise): + """GEMM operands of the weight of the GroupedLinear at ``idx``: its ``_MxFp8Weight``, or + the BF16 weight. Prepared fresh at each forward.""" + fc_op = self.basic_ops[idx] + # TODO(phuonguyen): drop the FC1 reorder, here and in the backward, once cuDNN upstream + # supports glu_interleave_size=None. + reorder = self._reorder_glu and idx == 1 + if not (self._mxfp8 or reorder): + return _bf16_weight(fc_op, fc_op.num_groups) + if self._mxfp8: + return _mxfp8_weight(fc_op, fc_op.num_groups, columnwise, reorder_glu=reorder) + return _interleave_glu_rows(_bf16_weight(fc_op, fc_op.num_groups)) + + def fuser_backward( + self, + basic_op_ctxs: list[OperationContext], + grad_output: torch.Tensor, + *, + basic_op_grad_extra_outputs: list[tuple[Optional[torch.Tensor], ...]], + **unused, # pylint: disable=unused-argument + ): + # A later op that also reads the dispatch's routing weights delivers their gradient here; + # fold it into the routing-weight gradient the dispatch backward scatters to topk_weights. + grad_recv_weights_extra = basic_op_grad_extra_outputs[0][1] + if self._mxfp8: + return self._backward_mxfp8(basic_op_ctxs, grad_output, grad_recv_weights_extra) + _, fc1_op, _, fc2_op, _ = self.basic_ops + dispatch_ctx, fc1_ctx, _, fc2_ctx, _ = basic_op_ctxs + recv_tokens, gemm_out, act_out, recv_weights, *w1 = fc1_ctx.saved_tensors + buffer = fc1_ctx.buffer + device = buffer.device + num_groups = fc1_op.num_groups + hidden = buffer.hidden_dim + ffn = fc2_op.in_features + rows = gemm_out.shape[0] + tokens_per_expert = buffer.tokens_per_expert_i32 + w1 = w1[0] if w1 else _bf16_weight(fc1_op, num_groups) + w2 = _bf16_weight(fc2_op, num_groups) + grad_result = _bf16_grad_output(grad_output) + num_tokens = grad_result.shape[0] + grad_params = functools.partial( + self._grad_params, device=device, tokens_per_expert=tokens_per_expert + ) + + grad_expert_out = torch.empty(rows, hidden, dtype=torch.bfloat16, device=device) + grad_gemm = torch.empty(rows, 2 * ffn, dtype=torch.bfloat16, device=device) + grad_recv_weights = torch.empty(rows, dtype=torch.float32, device=device) + fc2_grads = None + fc2_wgrad = _CallWgrad() + if fc2_ctx.weight_requires_grad: + fc2_grads = grad_params(fc2_op, fc2_ctx, act_out, grad_expert_out, "FC2", fc2_wgrad) + tex.ep_combine_gemm_bwd( + buffer.handle_mem, grad_result, gemm_out, recv_weights, tokens_per_expert, w2, + grad_expert_out, grad_gemm, grad_recv_weights, buffer.top_k, buffer.alignment, + buffer.topk_idx_dtype, **fc2_wgrad, + ) # fmt: skip + if fc2_grads is None: + fc2_grads = grad_params(fc2_op, fc2_ctx, act_out, grad_expert_out, "FC2") + + # Neither the input nor the routing weights need a gradient: no dispatch backward. + grad_tokens = grad_topk = fc1_grads = None + if dispatch_ctx.requires_grad: + if grad_recv_weights_extra is not None: + grad_recv_weights.add_(grad_recv_weights_extra.to(torch.float32)) + fc1_wgrad = _CallWgrad() + # The weight gradient of reordered FC1 rows is computed after the reorder back. + if not self._reorder_glu and fc1_ctx.weight_requires_grad: + fc1_grads = grad_params(fc1_op, fc1_ctx, recv_tokens, grad_gemm, "FC1", fc1_wgrad) + grad_recv = torch.empty(rows, hidden, dtype=torch.bfloat16, device=device) + grad_tokens = torch.empty(num_tokens, hidden, dtype=torch.bfloat16, device=device) + grad_topk = torch.empty(fc1_ctx.topk_weights_shape, dtype=torch.float32, device=device) + tex.ep_dispatch_gemm_bwd( + buffer.handle_mem, grad_gemm, grad_recv_weights, tokens_per_expert, w1, + grad_recv, grad_tokens, grad_topk, buffer.top_k, buffer.alignment, + buffer.topk_idx_dtype, **fc1_wgrad, + ) # fmt: skip + + if fc1_grads is None: + if fc1_ctx.weight_requires_grad and self._reorder_glu: + grad_gemm = _deinterleave_glu_columns(grad_gemm) + fc1_grads = grad_params(fc1_op, fc1_ctx, recv_tokens, grad_gemm, "FC1") + + clear_tensor_data(recv_tokens, act_out) + return self._finish_backward(grad_tokens, grad_topk, fc1_grads, fc2_grads) + + def _grad_params( + self, fc_op, ctx, grouped_x, grouped_dy, label, wgrad_args=None, *, device, + tokens_per_expert, + ): # fmt: skip + """Parameter gradients of ``fc_op``, in registration order. With ``wgrad_args`` the weight + gradient is computed by the backward call from the operands recorded there; otherwise it + is computed here from ``grouped_x`` and ``grouped_dy``, which a frozen weight does not + read.""" + num_groups = fc_op.num_groups + shape = (fc_op.out_features, fc_op.in_features) + mxfp8 = self._mxfp8 + wgrad_kernel_fn = offsets = factory = None + if ctx.weight_requires_grad: + kernel_class = GroupedMLP_CuTeGEMMGLU if mxfp8 else GroupedMLP_CuTeGEMMGLUBf16 + wgrad_kernel_fn = kernel_class.grouped_gemm_wgrad_kernel() + if wgrad_args is not None: + factory = wgrad_args.gemm_fn_factory(num_groups, shape) + else: + offsets = tokens_per_expert.cumsum(0, dtype=torch.int32) + if not mxfp8: + factory = _bf16_wgrad_fn_factory( + weight_shape=shape, offsets=offsets, wgrad_kernel_fn=wgrad_kernel_fn, + single_grouped_weight=True, num_groups=num_groups, + ) # fmt: skip + grads = _compute_grad_params( + fc_op=fc_op, ctx=ctx, num_groups=num_groups, weight_shape=shape, + grouped_x=grouped_x, grouped_dy=grouped_dy, dtype=torch.bfloat16, device=device, + bias_grads=None, bias_grad_packed=None, label=label, + cudnn_wgrad_kernel_fn=wgrad_kernel_fn, use_nvfp4=False, + data_dtype=torch.float8_e4m3fn if mxfp8 else torch.bfloat16, + scale_view_dtype=torch.float8_e8m0fnu if mxfp8 else None, + sf_vec_size=_SF_VEC if mxfp8 else None, + offsets=offsets, use_dense_single_group=False, wgrad_gemm_fn_factory=factory, + ) # fmt: skip + if wgrad_args is not None and ctx.weight_requires_grad: + wgrad_args.require_recorded() + return grads + + @staticmethod + def _finish_backward(grad_tokens, grad_topk, fc1_grads, fc2_grads): + """Return the gradients; the routing-weight gradient is part of the dispatch's + ``topk_weights`` gradient.""" + return ( + grad_tokens, + [(), fc1_grads, (), fc2_grads, ()], + [(None, grad_topk), (None,), (None,), (None,), (None,)], + ) + + def _backward_mxfp8(self, basic_op_ctxs, grad_output, grad_recv_weights_extra=None): + """Backward with MXFP8 GEMMs and EP transport.""" + _, fc1_op, _, fc2_op, _ = self.basic_ops + dispatch_ctx, fc1_ctx, _, fc2_ctx, _ = basic_op_ctxs + ( + recv_tokens, + recv_scale, + gemm_out, + recv_weights, + w1_col, + w1_col_scale, + w2_col, + w2_col_scale, + ) = fc1_ctx.saved_tensors + buffer = fc1_ctx.buffer + device = buffer.device + num_groups = fc1_op.num_groups + hidden = buffer.hidden_dim + ffn = fc2_op.in_features + rows = gemm_out.shape[0] + tokens_per_expert = buffer.tokens_per_expert_i32 + # GroupedTensor group sizes are int64. + first_dims = tokens_per_expert.long() + grad_result = _bf16_grad_output(grad_output) + num_tokens = grad_result.shape[0] + grad_result, grad_result_scale, symm_input = _quantize_for_dispatch(grad_result, device) + + def fp8_rows(cols): + data = torch.empty(rows, cols, dtype=torch.float8_e4m3fn, device=device) + return data, torch.empty(rows * cols // _SF_VEC, dtype=torch.uint8, device=device) + + grad_expert_out, grad_expert_out_scale = fp8_rows(hidden) + grad_expert_out_scale = grad_expert_out_scale.view(rows, hidden // _SF_VEC) + grad_gemm, grad_gemm_scale = fp8_rows(2 * ffn) + grad_gemm_col, grad_gemm_col_scale = fp8_rows(2 * ffn) + act_col, act_col_scale = fp8_rows(ffn) + grad_recv_weights = torch.empty(rows, dtype=torch.float32, device=device) + + grad_params = functools.partial( + self._grad_params, device=device, tokens_per_expert=tokens_per_expert + ) + + def grouped(cols, data, scale, col_data, col_scale, in_call): + # Expert slabs of a row-sized MXFP8 tensor with GEMM-swizzled scales. A weight + # gradient in a backward call reads no tensor offsets. + return GroupedTensor( + shape=(rows, cols), dtype=torch.bfloat16, num_tensors=num_groups, + quantizer=_ep_quantizer(), data=data, columnwise_data=col_data.view(-1), + scale_inv=scale, columnwise_scale_inv=col_scale, first_dims=first_dims, + tensor_offsets=None if in_call else tex.splits_to_offsets(first_dims, cols), + with_gemm_swizzled_scales=True, + ) # fmt: skip + + def fc1_grad_params(wgrad_args=None): + if not fc1_ctx.weight_requires_grad: + return grad_params(fc1_op, fc1_ctx, None, None, "FC1") + in_call = wgrad_args is not None + if in_call: + # The call writes the columnwise received rows from their rowwise copy. + x_col, x_col_scale = fp8_rows(hidden) + grouped_x = grouped(hidden, None, None, x_col, x_col_scale, True) + wgrad_args.update( + wgrad_input_rowwise=recv_tokens, wgrad_input_rowwise_scale_inv=recv_scale + ) + else: + grouped_x = _columnwise_rows(recv_tokens, recv_scale, first_dims) + grad_gemm_cols = ( + grouped(2 * ffn, None, None, _deinterleave_glu_columns(grad_gemm_col), + _deinterleave_glu_col_scales(grad_gemm_col_scale, tokens_per_expert, + 2 * ffn), in_call) + if self._reorder_glu + else grouped(2 * ffn, grad_gemm.view(-1), grad_gemm_scale, grad_gemm_col, + grad_gemm_col_scale, in_call) + ) # fmt: skip + return grad_params( + fc1_op, fc1_ctx, grouped_x, grad_gemm_cols, "FC1", wgrad_args + ) # fmt: skip + + # The call computes the FC2 weight gradient too, and writes the received rows columnwise + # for it. + fc2_wgrad = _CallWgrad() + grad_expert_out_cols = {} + if fc2_ctx.weight_requires_grad: + grad_expert_out_col, grad_expert_out_col_scale = fp8_rows(hidden) + grad_expert_out_cols = { + "grad_expert_out_columnwise": grad_expert_out_col, + "grad_expert_out_columnwise_scale_inv": grad_expert_out_col_scale, + } + fc2_grads = grad_params( + fc2_op, fc2_ctx, grouped(ffn, None, None, act_col, act_col_scale, True), + grouped(hidden, None, None, grad_expert_out_col, grad_expert_out_col_scale, True), + "FC2", fc2_wgrad, + ) # fmt: skip + else: + fc2_grads = grad_params(fc2_op, fc2_ctx, None, None, "FC2") + tex.ep_combine_gemm_bwd( + buffer.handle_mem, grad_result, gemm_out, + recv_weights, tokens_per_expert, w2_col, grad_expert_out, grad_gemm, + grad_recv_weights, buffer.top_k, buffer.alignment, buffer.topk_idx_dtype, + grad_result_scale_inv=grad_result_scale, + grad_expert_out_scale_inv=grad_expert_out_scale, weight_scale_inv=w2_col_scale, + grad_gemm_out_scale_inv=grad_gemm_scale, grad_gemm_out_columnwise=grad_gemm_col, + grad_gemm_out_columnwise_scale_inv=grad_gemm_col_scale, act_out=act_col, + act_out_scale_inv=act_col_scale, **grad_expert_out_cols, **fc2_wgrad, + symm_input=symm_input, + ) # fmt: skip + + grad_tokens = grad_topk = fc1_grads = None + if dispatch_ctx.requires_grad: + if grad_recv_weights_extra is not None: + grad_recv_weights.add_(grad_recv_weights_extra.to(torch.float32)) + fc1_wgrad = _CallWgrad() + # The weight gradient of reordered FC1 rows is computed after the reorder back. + if not self._reorder_glu and fc1_ctx.weight_requires_grad: + fc1_wgrad.update( + grad_gemm_out_columnwise=grad_gemm_col, + grad_gemm_out_columnwise_scale_inv=grad_gemm_col_scale, + ) + fc1_grads = fc1_grad_params(fc1_wgrad) + grad_recv = torch.empty(rows, hidden, dtype=torch.bfloat16, device=device) + grad_tokens = torch.empty(num_tokens, hidden, dtype=torch.bfloat16, device=device) + grad_topk = torch.empty(fc1_ctx.topk_weights_shape, dtype=torch.float32, device=device) + tex.ep_dispatch_gemm_bwd( + buffer.handle_mem, grad_gemm, grad_recv_weights, tokens_per_expert, w1_col, + grad_recv, grad_tokens, grad_topk, buffer.top_k, buffer.alignment, + buffer.topk_idx_dtype, grad_gemm_out_scale_inv=grad_gemm_scale, + weight_scale_inv=w1_col_scale, **fc1_wgrad, + ) # fmt: skip + + if fc1_grads is None: + fc1_grads = fc1_grad_params() + + clear_tensor_data(recv_tokens, recv_scale) + return self._finish_backward(grad_tokens, grad_topk, fc1_grads, fc2_grads) + + +class _Bf16Operands: + """Operands of the forward GEMM calls with BF16 GEMMs and EP transport.""" + + scale_names = () + # Positions in the saved row tensors: the inputs of the FC1 and FC2 weight gradients, which a + # frozen weight does not need, and the activations CPU offload takes. + fc1_wgrad_inputs = (0,) + fc2_wgrad_inputs = (2,) + offload_slots = (0, 1, 2) + + def __init__(self, reorder_glu: bool) -> None: + self.reorder_glu = reorder_glu + + @staticmethod + def dispatch_input(input_, device): + """Dispatch input and the keyword arguments it adds to the dispatch GEMM call.""" + del device + return input_, {} + + @staticmethod + def weight(weight): + """GEMM operand of a weight and the keyword arguments it adds to the call.""" + return weight, {} + + @staticmethod + def recv_buffers(rows, hidden, ffn, device): + """Receive buffers of a fixed capacity: recv tokens, GEMM output, activation output and + a dict of scale buffers named as the dispatch GEMM call's keyword arguments.""" + return ( + torch.empty(rows, hidden, dtype=torch.bfloat16, device=device), + torch.empty(rows, 2 * ffn, dtype=torch.bfloat16, device=device), + torch.empty(rows, ffn, dtype=torch.bfloat16, device=device), + {}, + ) + + @staticmethod + def combine_kwargs(recv_weights, scales): + """Keyword arguments the combine GEMM call adds.""" + del recv_weights, scales + return {} + + def saved_tensors(self, recv_tokens, recv_weights, gemm_out, act_out, scales, w1, w2, backward): + """Row-sized tensors and the other tensors saved for the backward.""" + del scales, w2, backward + # The BF16 SwiGLU backward GEMM cannot write the SwiGLU output, so the FC2 wgrad reads it. + return (recv_tokens, gemm_out, act_out, recv_weights), (w1,) if self.reorder_glu else () + + +class _Mxfp8Operands: + """Operands of the forward GEMM calls with MXFP8 GEMMs and EP transport.""" + + scale_names = ("recv_scale_inv", "act_out_scale_inv") + fc1_wgrad_inputs = (0, 1) + fc2_wgrad_inputs = () + offload_slots = (0, 1, 2) + + @staticmethod + def dispatch_input(input_, device): + """Dispatch input quantized to MXFP8, with its scales.""" + tokens, tokens_scale, symm_input = _quantize_for_dispatch(input_, device) + return tokens, {"tokens_scale_inv": tokens_scale, "symm_input": symm_input} + + @staticmethod + def weight(weight): + """MXFP8 data of a weight and its scales.""" + return weight.data, {"weight_scale_inv": weight.scale_inv} + + @staticmethod + def recv_buffers(rows, hidden, ffn, device): + """MXFP8 recv tokens and activation output, with their scale buffers.""" + fp8 = torch.float8_e4m3fn + return ( + torch.empty(rows, hidden, dtype=fp8, device=device), + torch.empty(rows, 2 * ffn, dtype=torch.bfloat16, device=device), + torch.empty(rows, ffn, dtype=fp8, device=device), + { + "recv_scale_inv": torch.empty( + rows, hidden // _SF_VEC, dtype=torch.uint8, device=device + ), + "act_out_scale_inv": torch.empty( + rows * ffn // _SF_VEC, dtype=torch.uint8, device=device + ), + }, + ) + + @staticmethod + def combine_kwargs(recv_weights, scales): + """The routing weights scale the second GEMM's output rows.""" + return {"recv_topk_weights": recv_weights, "gemm_in_scale_inv": scales["act_out_scale_inv"]} + + @staticmethod + def saved_tensors(recv_tokens, recv_weights, gemm_out, act_out, scales, w1, w2, backward): + """Tensors saved for the backward; the FC2 dgrad recomputes the SwiGLU output for the FC2 + wgrad, so it is not saved.""" + del act_out + return (recv_tokens, scales["recv_scale_inv"], gemm_out, recv_weights), ( + ( + w1.columnwise_data, + w1.columnwise_scale_inv, + w2.columnwise_data, + w2.columnwise_scale_inv, + ) + if backward + else () + ) + + +def _require_contiguous(tensor: torch.Tensor, name: str) -> torch.Tensor: + """Forward inputs must already be contiguous; making them contiguous here would hide a copy.""" + if not tensor.is_contiguous(): + raise ValueError(f"FusedMoE requires a contiguous {name}, got strides {tensor.stride()}.") + return tensor + + +def _bf16_grad_output(grad_output) -> torch.Tensor: + """Contiguous BF16 gradient of the combine output.""" + if isinstance(grad_output, GroupedTensor): + raise RuntimeError("FusedMoE does not accept a quantized grad output.") + return maybe_dequantize(grad_output, torch.bfloat16).contiguous() + + +class _CallWgrad(dict): + """Keyword arguments of a weight gradient computed inside a backward call, passed as + ``**wgrad``. Its wgrad factory only records the operands; the call runs the kernel later, so + distributed weights, which FusedMoE rejects, do not fit.""" + + def gemm_fn_factory(self, num_groups: int, weight_shape) -> Callable: + """Wgrad factory that records the operands of a weight of shape ``weight_shape``.""" + + def factory(accumulate: bool) -> Callable: + def gemm_fn(grouped_x, grouped_dy, wgrad_output): + del grouped_dy + if isinstance(grouped_x, GroupedTensor): + self.update( + wgrad_input=grouped_x.columnwise_data.view(torch.float8_e4m3fn).view( + -1, weight_shape[1] + ), + wgrad_input_scale_inv=grouped_x.columnwise_scale_inv, + ) + else: + self.update(wgrad_input=grouped_x) + self.update( + weight_grad=wgrad_output.rowwise_data.view(num_groups, *weight_shape), + accumulate_weight_grad=accumulate, + ) + + return gemm_fn + + return factory + + def require_recorded(self) -> None: + """Raise unless the GEMM function ran: the call would otherwise skip the gradient.""" + if "weight_grad" not in self: + raise RuntimeError("FusedMoE: the weight-gradient GEMM function was not called.") + + +class _MxFp8Weight(NamedTuple): + """MXFP8 operands of a weight: data and scales, rowwise and, when prepared, columnwise.""" + + data: torch.Tensor + scale_inv: torch.Tensor + columnwise_data: Optional[torch.Tensor] = None + columnwise_scale_inv: Optional[torch.Tensor] = None + + +def _gemm_interface_reason(mxfp8: bool = False) -> Optional[str]: + """Why the EP grouped GEMM kernel tree does not match Transformer Engine, or ``None``.""" + try: + from ....common.CuTeDSL.ep_gemm._loader import ( # pylint: disable=import-outside-toplevel + gemm_interface_reason, + ) + except ImportError as err: + return f"the CuTeDSL EP grouped GEMMs cannot be imported: {err}" + return gemm_interface_reason(mxfp8) + + +def _ep_quantizer() -> MXFP8Quantizer: + """Rowwise E4M3 quantizer of the MXFP8 EP transport.""" + quantizer = MXFP8Quantizer(tex.DType.kFloat8E4M3, rowwise=True, columnwise=False) + quantizer.internal = True + return quantizer + + +def _quantize_for_dispatch(input_, device): + """MXFP8 data and compact scales of a dispatch input, and whether the dispatch reads them in + place: they are in the EP dispatch window whenever it exists, alike on every rank.""" + window = _dispatch_window(device) + quantized, scale = quantize_for_ep(input_, _ep_quantizer(), window) + return quantized._rowwise_data.view(torch.float8_e4m3fn), scale, window is not None + + +def _columnwise_rows(data, scale, tokens_per_expert): + """Expert slabs of received MXFP8 rows with compact scales, given columnwise data for the + weight gradient.""" + grouped = _make_grouped_mxfp8( + data, scale, tokens_per_expert, tex.DType.kFloat8E4M3, torch.bfloat16 + ) + quantizer = _ep_quantizer() + quantizer.set_usage(rowwise=True, columnwise=True) + quantizer.optimize_for_gemm = True + tex.group_requantize_inplace( + grouped, quantizer, tokens_per_expert.numel(), tokens_per_expert, tex.DType.kBFloat16, + tensor_offsets=grouped.tensor_offsets, + ) # fmt: skip + return grouped + + +def _mxfp8_weight( + fc_op: GroupedLinear, num_groups: int, columnwise: bool, reorder_glu: bool = False +) -> _MxFp8Weight: + """GEMM operands of the weight quantized to MXFP8, with the columnwise ones when asked; data + is [num_groups, out_features, in_features]. + BF16 weights are quantized with GEMM-swizzled scales; the scales of MXFP8 weight parameters + are swizzled into a copy. Each direction is swizzled along its own scaling axis. + ``reorder_glu`` reorders FC1 rows as ``_interleave_glu_rows`` does, data and scales alike.""" + weight = fc_op.weight + shape = (num_groups, fc_op.out_features, fc_op.in_features) + if weight.quantizer is not None: + # Only add usages, never drop: later weight updates keep what this op needs. + weight.quantizer.set_usage(rowwise=True, columnwise=True if columnwise else None) + if columnwise and weight.columnwise_data is None: + raise RuntimeError("FusedMoE needs columnwise data in the MXFP8 weight parameters.") + weight = weight.copy() + if reorder_glu: + # Rowwise scales follow the rows; a columnwise scale row covers one block of rows. + rows, cols = shape[1:] + weight.rowwise_data = _interleave_glu_rows(weight.rowwise_data.view(shape)).view(-1) + weight.scale_inv = _interleave_glu_rows( + weight.scale_inv.view(num_groups, rows, -1) + ).view(-1) + if weight.columnwise_data is not None: + weight.columnwise_data = _interleave_glu_rows( + weight.columnwise_data.view(shape) + ).view(-1) + weight.columnwise_scale_inv = _interleave_glu_rows( + weight.columnwise_scale_inv.view(num_groups, rows // _SF_VEC, cols), + block=_GLU_BLOCK // _SF_VEC, + ).view(-1) + tex.grouped_swizzle_for_gemm(weight, rowwise=True, columnwise=columnwise) + else: + quantizer = fc_op.get_quantizer("forward", 1).copy() + quantizer.set_usage(rowwise=True, columnwise=columnwise) + quantizer.optimize_for_gemm = True + data = weight.rowwise_data.view(shape) + if reorder_glu: + data = _interleave_glu_rows(data) + weight = tex.group_quantize(data.view(weight.logical_shape), quantizer, num_groups, None) + fp8 = torch.float8_e4m3fn + operands = _MxFp8Weight(weight.rowwise_data.view(fp8).view(shape), weight.scale_inv.reshape(-1)) + if columnwise: + operands = operands._replace( + columnwise_data=weight.columnwise_data.view(fp8).view(shape), + columnwise_scale_inv=weight.columnwise_scale_inv.reshape(-1), + ) + return operands + + +def _bf16_weight(fc_op: GroupedLinear, num_groups: int) -> torch.Tensor: + """Expert-major BF16 weight of a packed GroupedLinear weight, cast when its data has another + dtype, as after ``Module.to(torch.bfloat16)`` on FP32 weights.""" + return _bf16_packed_weight(fc_op, num_groups).to(torch.bfloat16) + + +# TODO(phuonguyen): the cuDNN GEMMs require the interleaved GLU layout, so FC1 weights are reordered +# here. Drop this reorder and pass the non-interleaved layout through once cuDNN supports it. +def _interleave_glu_rows(t: torch.Tensor, block: int = _GLU_BLOCK) -> torch.Tensor: + """Copy of per-expert rows [experts, 2 * n, ...], gate rows then up rows, with gate and up + alternating in blocks of ``block`` rows, the GLU layout of ``glu_interleave_size=32``.""" + experts, rows = t.shape[:2] + blocks = t.reshape(experts, 2, rows // (2 * block), block, *t.shape[2:]) + return blocks.transpose(1, 2).reshape(t.shape) + + +def _deinterleave_glu_columns(t: torch.Tensor) -> torch.Tensor: + """Copy of [rows, 2 * n] with gate and up in alternating column blocks, gate columns first.""" + rows, cols = t.shape + # Moved in 16-byte words (complex128); a column block spans whole words. + words = t.view(torch.complex128) + blocks = words.reshape(rows, cols // (2 * _GLU_BLOCK), 2, _GLU_BLOCK * t.element_size() // 16) + return blocks.transpose(1, 2).reshape(rows, -1).view(t.dtype) + + +def _deinterleave_glu_col_scales(scale, tokens_per_expert, cols): + """Columnwise MXFP8 scales, swizzled per expert, of a tensor reordered by + ``_deinterleave_glu_columns``.""" + tiles = cols // 128 + blocks = scale.view(torch.int32).view(-1, 128) + units = blocks.shape[0] // tiles # 128-row units + device = scale.device + # First unit and unit count of each unit's expert; the rows after the experts form a last group. + ends = tokens_per_expert.cumsum(0) // 128 + starts = torch.nn.functional.pad(ends, (1, 0)) + stops = torch.nn.functional.pad(ends, (0, 1), value=units) + unit = torch.arange(units, device=device) + group = torch.searchsorted(stops, unit, right=True) + first = starts[group] + count = stops[group] - first + # Block of each (tile, unit) in the slabs. + tile = torch.arange(tiles, device=device)[:, None] + index = (torch.add(unit, first, alpha=tiles - 1) + tile * count).view(-1) + # Tile 2 * i + h holds column blocks 8 * i + 4 * h + 2 * j + g, of gate (g = 0) or up (g = 1), + # which go to tile g * tiles / 2 + i at slot 2 * h + j. + src = blocks[index].view(tiles // 2, 2, units, 32, 2, 2) + out = torch.empty_like(blocks) + out[index] = src.permute(5, 0, 2, 3, 1, 4).reshape(-1, 128) + return out.view(torch.uint8).view(scale.shape) + + +def _routing_extras_internal(dispatch, fc1, activation, fc2) -> bool: + """Whether tokens_per_expert and the routing weights flow from the dispatch to the MLP.""" + channels = dispatch._extra_output_channels + return ( + not any(dispatch._extra_output_to_caller) + and channels[0] is not None + and channels[1] is not None + and fc1._extra_input_channels[0] == channels[0] + and fc2._extra_input_channels[0] == channels[0] + and activation._extra_input_channels[0] == channels[1] + ) + + +def moe_overlap_unsupported_reason( + config: EpConfig, + ffn_hidden_size: int, + *, + params_dtype: torch.dtype, + activation: str = "swiglu", + glu_interleave_size: Optional[int] = None, + bias: bool = False, + single_grouped_weight: bool = False, + recipe: Optional[Recipe] = None, + primary_weights_in_fp8: bool = False, +) -> Optional[str]: + """Why a ``Sequential`` of ``MoeDispatch``, ``GroupedLinear``, ``ScaledSwiGLU``, + ``GroupedLinear`` and ``MoeCombine`` built with these settings does not run as one + ``FusedMoE``, or ``None`` when it does. The reason names an unsupported setting or the + grouped GEMM backend failing to load on this device. See ``moe_overlap_supported`` for what + the query covers. + + Parameters + ---------- + config : EpConfig + EP configuration shared by the dispatch and the combine. + ffn_hidden_size : int + Output features of the activation, input features of the second GroupedLinear. + params_dtype : torch.dtype + Dtype of the GroupedLinear weights. + activation : str, default = "swiglu" + Activation between the GroupedLinear ops. + glu_interleave_size : int, optional + ``glu_interleave_size`` of the ``ScaledSwiGLU``, ``None`` or 32. + bias : bool, default = ``False`` + Whether the GroupedLinear ops have biases. + single_grouped_weight : bool, default = ``False`` + ``single_grouped_weight`` of the GroupedLinear ops. + recipe : Recipe, optional + Quantization recipe the ops run under, ``None`` for BF16. Under ``MXFP8BlockScaling`` the + EP transport is MXFP8; ``config``'s transport recipes must be MXFP8BlockScaling or unset. + primary_weights_in_fp8 : bool, default = ``False`` + Whether the GroupedLinear weights are quantized parameters (``quantized_model_init``). + They must be MXFP8 and need the ``MXFP8BlockScaling`` recipe. + """ + if not FusedMoE.is_supported(): + reason = ( + "needs SM 10.0, 10.3 or 10.7, NVTE_ENABLE_CUTEDSL_BACKEND=1, NVTE_MOE_OVERLAP and" + " the BF16 cuDNN grouped GEMM kernels" + ) + mismatch = _gemm_interface_reason() if _moe_overlap_available() else None + return f"{reason}: {mismatch}" if mismatch else reason + # TODO(phuonguyen): drop this gate once the routing-weight gradient is reworked to avoid the + # atomic reduction, which makes it reproducible under deterministic execution. + if _deterministic_algorithms_required(): + return ( + "deterministic execution was requested, and the routing-weight gradient is reduced" + " with atomics" + ) + if torch.is_autocast_enabled() and torch.get_autocast_dtype("cuda") != torch.bfloat16: + return "needs a BF16 autocast dtype" + if config.payload_dtype is not torch.bfloat16: + return "needs a BF16 payload" + alignments = (64, 128, _TILE) + if isinstance(recipe, MXFP8BlockScaling): + # The SM 10.7 MXFP8 GEMMs have no tail tiles. + alignments = (_TILE,) if torch.cuda.get_device_capability() == (10, 7) else (128, _TILE) + if config.alignment not in alignments: + return f"the EP alignment must be one of {alignments}" + if config.zero_copy: + return "zero-copy EP is not supported" + if recipe is not None: + if not isinstance(recipe, MXFP8BlockScaling): + return "quantized GEMMs other than MXFP8BlockScaling are not supported" + if not GroupedMLP_CuTeGEMMGLU.is_supported(): + return "MXFP8 needs the MXFP8 cuDNN grouped GEMM kernels" + mismatch = _gemm_interface_reason(mxfp8=True) + if mismatch: + return mismatch + if recipe.fp8_format != Format.E4M3 or recipe.backward_override is not None: + return "MXFP8 needs fp8_format E4M3 and no backward_override" + # MXFP8 FusedMoE quantizes the EP transport itself, so the transport recipes need not be + # set; if set they must be MXFP8, not a different recipe. + if any( + r is not None and not isinstance(r, MXFP8BlockScaling) + for r in (config.dispatch_fwd_quant_recipe, config.combine_bwd_quant_recipe) + ): + return ( + "MXFP8 FusedMoE uses MXFP8 EP transport; dispatch_fwd_quant_recipe and" + " combine_bwd_quant_recipe must be MXFP8BlockScaling or unset" + ) + if config.hidden_dim % 512 != 0 or ffn_hidden_size % _TILE != 0: + return f"MXFP8 needs hidden_dim a multiple of 512 and ffn_hidden_size of {_TILE}" + elif ( + config.dispatch_fwd_quant_recipe is not None or config.combine_bwd_quant_recipe is not None + ): + return "BF16 FusedMoE cannot use a quantized EP transport recipe" + if config.hidden_dim % _TILE != 0: + return f"hidden_dim must be a multiple of {_TILE}" + capacity = config.recv_capacity_per_rank + if capacity is not None and capacity % _TILE != 0: + return f"recv_capacity_per_rank must be a multiple of {_TILE}" + if ffn_hidden_size % 64 != 0: + return "ffn_hidden_size must be a multiple of 64" + if activation != "swiglu": + return "needs the SwiGLU activation" + if glu_interleave_size not in (None, _GLU_BLOCK): + return f"needs glu_interleave_size None or {_GLU_BLOCK}" + if not single_grouped_weight: + return "needs single_grouped_weight=True" + if bias: + return "biases are not supported" + if params_dtype != torch.bfloat16: + return "needs BF16 weights" + if primary_weights_in_fp8 and recipe is None: + return "quantized weight parameters need the MXFP8BlockScaling recipe" + return None + + +def moe_overlap_supported( + config: EpConfig, + ffn_hidden_size: int, + *, + params_dtype: torch.dtype, + activation: str = "swiglu", + glu_interleave_size: Optional[int] = None, + bias: bool = False, + single_grouped_weight: bool = False, + recipe: Optional[Recipe] = None, + primary_weights_in_fp8: bool = False, +) -> bool: + """Whether a ``Sequential`` of ``MoeDispatch``, ``GroupedLinear``, ``ScaledSwiGLU``, + ``GroupedLinear`` and ``MoeCombine`` built with these settings runs as one ``FusedMoE``; + ``moe_overlap_unsupported_reason`` gives the reason when it does not and takes the same + parameters. + + Call it after ``ep_bootstrap``. It only queries the device. Deterministic execution + (``NVTE_ALLOW_NONDETERMINISTIC_ALGO=0`` or ``torch.use_deterministic_algorithms``) and an + autocast dtype other than BF16 are unsupported; the answer follows the settings in effect at + the call. GroupedLinear settings it does not take, such as ``delay_wgrad_compute`` or + ``accumulate_into_main_grad``, can still make the ops unsupported. + """ + return ( + moe_overlap_unsupported_reason( + config, + ffn_hidden_size, + params_dtype=params_dtype, + activation=activation, + glu_interleave_size=glu_interleave_size, + bias=bias, + single_grouped_weight=single_grouped_weight, + recipe=recipe, + primary_weights_in_fp8=primary_weights_in_fp8, + ) + is None + ) + + +def _unsupported_reason(dispatch, fc1, activation, fc2, combine, recipe=None) -> Optional[str]: + """Why a window cannot use the overlapped ops, or ``None`` when it can.""" + config = dispatch.config + dtypes = {w.dtype for fc in (fc1, fc2) for w in fc._get_weight_tensors()} + reason = moe_overlap_unsupported_reason( + config, + fc2.in_features, + params_dtype=dtypes.pop() if len(dtypes) == 1 else None, + activation="swiglu" if isinstance(activation, ScaledSwiGLU) else type(activation).__name__, + glu_interleave_size=activation.glu_interleave_size, + bias=fc1.has_bias or fc2.has_bias, + single_grouped_weight=fc1.single_grouped_weight and fc2.single_grouped_weight, + recipe=recipe, + primary_weights_in_fp8=any( + getattr(w, "quantizer", None) is not None + for fc in (fc1, fc2) + for w in fc._get_weight_tensors() + ), + ) + if reason is not None: + return reason + if any( + not isinstance(getattr(fc.weight, "quantizer", None), (type(None), MXFP8Quantizer)) + for fc in (fc1, fc2) + ): + return "quantized weight parameters must be MXFP8" + if combine.config != config: + return "dispatch and combine must use the same EpConfig" + if dispatch.buffer is not combine.buffer: + return "dispatch and combine must share one EpBuffer" + if not _routing_extras_internal(dispatch, fc1, activation, fc2): + return "the dispatch extra outputs must feed the grouped MLP and not the caller" + if any(is_distributed_weight(fc.weight) for fc in (fc1, fc2)): + return "distributed (sharded) weights are not supported" + if any( + fc.wgrad_store is not None and fc.wgrad_store.delay_wgrad_compute() for fc in (fc1, fc2) + ): + return "delayed weight gradient computation (delay_wgrad_compute) is not supported" + try: + # The GLU layout is checked above. + validate_grouped_mlp_dims(fc1, ScaledSwiGLU(glu_interleave_size=_GLU_BLOCK), fc2) + except (TypeError, ValueError) as err: + return str(err) + if fc1.in_features != config.hidden_dim or fc2.out_features != config.hidden_dim: + return "the GroupedLinear sizes do not match the EP hidden_dim" + if ( + recipe is not None + and torch.cuda.get_device_capability() == (10, 7) + and config.recv_capacity_per_rank == _TILE + ): + # Some SM 10.7 MXFP8 weight gradients need more than one receive tile; one into + # main_grad counts as added. + from ....common.CuTeDSL.ep_gemm import ( # pylint: disable=import-outside-toplevel + wgrad_gemm, + ) + + for fc in (fc1, fc2): + cfg = wgrad_gemm.WgradConfig( + _TILE, fc.out_features, fc.in_features, config.num_local_experts, 1, + accumulate=fc._accumulate_into_main_grad, + scaling_mode=wgrad_gemm.MXFP8_1D_SCALING, + rows_alignment=config.alignment, + routed_rows=config.max_tokens_per_rank * config.top_k, + ) # fmt: skip + try: + wgrad_gemm.build_kernel(cfg) + except ValueError as err: + return str(err) + return None + + +# The GLU activations of the grouped MLP; the unsupported ones are rejected with a reason. +_WINDOW = ( + MoeDispatch, + GroupedLinear, + (ScaledSwiGLU, ScaledClampedQGeGLU, ScaledSiTUGLU), + GroupedLinear, + MoeCombine, +) + + +def fuse_moe_overlap_ops( + ops: list[FusibleOperation], + *, + recipe=None, + **unused, # pylint: disable=unused-argument +) -> list[FusibleOperation]: + """Fuse dispatch, grouped MLP and combine. A window that cannot be fused raises when the + overlap is enabled and keeps the unfused ops otherwise.""" + out = [] + idx = 0 + while idx < len(ops): + window = ops[idx : idx + 5] + if len(window) == len(_WINDOW) and all(map(isinstance, window, _WINDOW)): + reason = _unsupported_reason(*window, recipe=recipe) + if reason is None: + out.append(FusedMoE( + dispatch=window[0], fc1=window[1], activation=window[2], + fc2=window[3], combine=window[4], recipe=recipe, _validated=True, + )) # fmt: skip + idx += 5 + continue + # Without the overlap enabled the unfused ops are the expected ones. + if _moe_overlap_available(): + raise RuntimeError(f"FusedMoE is not supported: {reason}.") + out.append(ops[idx]) + idx += 1 + return out + + +register_forward_backward_fusion(fuse_moe_overlap_ops, prepend=True) diff --git a/transformer_engine/pytorch/ops/fuser.py b/transformer_engine/pytorch/ops/fuser.py index 6d13ba43942..f6a2f93e4ea 100644 --- a/transformer_engine/pytorch/ops/fuser.py +++ b/transformer_engine/pytorch/ops/fuser.py @@ -8,6 +8,7 @@ from collections.abc import Callable, Iterable, Sequence import copy import itertools +import os from typing import Any, Optional, TypeAlias import torch @@ -51,7 +52,7 @@ def _is_graph_capturing() -> bool: "Callable[tuple[list[FusibleOperation], ...], list[FusibleOperation]]" ) _FusedOpList: TypeAlias = list[tuple[FusibleOperation, list[int]]] -_FusionParams: TypeAlias = tuple[str, int] +_FusionParams: TypeAlias = tuple[str, int, tuple] class _OperationFuserAutogradFunction(torch.autograd.Function): @@ -701,9 +702,19 @@ def maybe_fuse_ops( # backward boundary in the key, but pay construction cost only once for # each configuration. Full recompute therefore builds at most one # no-grad plan and one grad-enabled plan for a stable recipe. + # Runtime settings that fusions may fall back on are part of the key. + runtime_policy = ( + torch.are_deterministic_algorithms_enabled(), + os.getenv("NVTE_ALLOW_NONDETERMINISTIC_ALGO", "1"), + torch.get_autocast_dtype("cuda") if torch.is_autocast_enabled() else None, + tuple( + op.need_backward_dw() for op in self._basic_ops if hasattr(op, "need_backward_dw") + ), + ) fusion_params: _FusionParams = ( str(recipe) if recipe is not None else "", first_op_requiring_backward, + runtime_policy, ) cached_ops = self._fused_ops_cache.get(fusion_params) if cached_ops is not None: From f21a6bb25f9d4a82cb34dfa54c52a5fad1fc0ec5 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Tue, 24 Nov 2026 05:02:52 +0000 Subject: [PATCH 02/67] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- tests/pytorch/test_ep_gemm.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/tests/pytorch/test_ep_gemm.py b/tests/pytorch/test_ep_gemm.py index b5d6b257bff..dab7f7328a2 100644 --- a/tests/pytorch/test_ep_gemm.py +++ b/tests/pytorch/test_ep_gemm.py @@ -68,8 +68,7 @@ def _run_gemm(rows_per_expert, rows_alignment, mxfp8, tail_clusters, device_layo if num_clusters == 0: continue name = ( - f"test_ep_gemm_{rows}_{rows_alignment}_{int(mxfp8)}_{num_clusters}" - f"_{int(device_layout)}" + f"test_ep_gemm_{rows}_{rows_alignment}_{int(mxfp8)}_{num_clusters}_{int(device_layout)}" ) assert dispatch_gemm.get_ep_dispatch_gemm_function( name, From cd2cac7fae4e34eb8082e0f39df2f5adecb07389 Mon Sep 17 00:00:00 2001 From: Phuong Nguyen Date: Mon, 23 Nov 2026 22:15:02 -0800 Subject: [PATCH 03/67] [Common] Follow the NCCL EP signal unit rename and pass whole push tiles as combine chunks Signed-off-by: Phuong Nguyen --- transformer_engine/common/ep/ep_backend.cpp | 6 +++--- transformer_engine/common/ep/ep_gemm_api.cpp | 21 ++++++++++++-------- 2 files changed, 16 insertions(+), 11 deletions(-) diff --git a/transformer_engine/common/ep/ep_backend.cpp b/transformer_engine/common/ep/ep_backend.cpp index 1dbff30af45..7613166ec87 100644 --- a/transformer_engine/common/ep/ep_backend.cpp +++ b/transformer_engine/common/ep/ep_backend.cpp @@ -602,7 +602,7 @@ void EPBackend::issue_dispatch_locked( SignalDesc dispatch_signal_desc; out_struct.dispatch_signal = - dispatch_signal_desc.attach(dispatch_signal, NCCL_EP_SIGNAL_UNIT_TILE_ROWS, "dispatch"); + dispatch_signal_desc.attach(dispatch_signal, NCCL_EP_SIGNAL_UNIT_ROWS, "dispatch"); ncclEpDispatchConfig_t dispatch_cfg = NCCL_EP_DISPATCH_CONFIG_INIT; dispatch_cfg.pass_direction = is_forward ? NCCL_EP_FWD_PASS : NCCL_EP_BWD_PASS; @@ -707,7 +707,7 @@ void EPBackend::combine(NVTETensor handle_mem, const NVTETensor expert_out, SignalDesc combine_signal_desc; in_struct.combine_signal = - combine_signal_desc.attach(combine_signal, NCCL_EP_SIGNAL_UNIT_CHUNK_ELEMS, "combine"); + combine_signal_desc.attach(combine_signal, NCCL_EP_SIGNAL_UNIT_COLUMNS, "combine"); ncclEpCombineOutputs_t out_struct = NCCL_EP_COMBINE_OUTPUTS_INIT; out_struct.tokens = &nccl_result_out; @@ -750,7 +750,7 @@ void EPBackend::dispatch_bwd(NVTETensor handle_mem, const NVTETensor grad, SignalDesc combine_signal_desc; in_struct.combine_signal = - combine_signal_desc.attach(combine_signal, NCCL_EP_SIGNAL_UNIT_CHUNK_ELEMS, "combine"); + combine_signal_desc.attach(combine_signal, NCCL_EP_SIGNAL_UNIT_COLUMNS, "combine"); ncclEpCombineOutputs_t out_struct = NCCL_EP_COMBINE_OUTPUTS_INIT; out_struct.tokens = &nccl_tok_out; diff --git a/transformer_engine/common/ep/ep_gemm_api.cpp b/transformer_engine/common/ep/ep_gemm_api.cpp index d6ea3a48c04..7d79bce18eb 100644 --- a/transformer_engine/common/ep/ep_gemm_api.cpp +++ b/transformer_engine/common/ep/ep_gemm_api.cpp @@ -113,11 +113,16 @@ void check_mxfp8_dims(size_t hidden, size_t ffn, size_t alignment) { kRowsPerTile); } -// Columns per combine flag: 1024 when it divides n, else the whole row; both are chunks NCCL EP -// accepts for bfloat16 rows. +// Columns of one combine flag over the whole row: the row rounded up to whole NCCL EP push tiles +// (1024 bfloat16 elements, or the row when shorter). NCCL EP takes a chunk past the row as one. +size_t whole_row_chunk(size_t n) { + return transformer_engine::DIVUP_TO_MULTIPLE(n, std::min(n, 1024)); +} + +// Columns per combine flag: 1024 when it divides n, else one flag over the whole row. size_t combine_chunk(size_t n) { NVTE_CHECK(n % kTileN == 0, "output columns (", n, ") must be a multiple of ", kTileN); - return n % 1024 == 0 ? 1024 : n; + return n % 1024 == 0 ? 1024 : whole_row_chunk(n); } // The combine (or dispatch backward) starts at the GEMM's entry and waits on its chunk flags. @@ -786,7 +791,7 @@ void nvte_ep_combine_gemm_fwd(NVTETensor handle_mem, const NVTETensor gemm_in, // expert_token_offsets the dispatch wrote. GemmScratch scratch = claim_scratch(ws_base, ws_bytes, layout.total_bytes, num_experts, rows, !weighted, 0); - set_chunk_words(scratch, layout, n / n_chunk, layout.signal); + set_chunk_words(scratch, layout, DIVUP(n, n_chunk), layout.signal); ep::reset_workspace(scratch.reset, stream); // The GEMM fills the flags; the combine is its programmatic dependent. @@ -808,7 +813,7 @@ void nvte_ep_combine_gemm_fwd(NVTETensor handle_mem, const NVTETensor gemm_in, } NVTECommWindow no_window{}; - TensorWrapper signal(scratch.base + layout.signal, std::vector{n / n_chunk}, + TensorWrapper signal(scratch.base + layout.signal, std::vector{DIVUP(n, n_chunk)}, DType::kInt32); const ep::EpSignal combine_signal{signal.data(), n_chunk}; ctx.backend.combine(handle_mem, expert_out, no_window, result, &combine_signal, &ctx.layer_cfg, @@ -998,7 +1003,7 @@ void nvte_ep_dispatch_gemm_bwd(NVTETensor handle_mem, const NVTETensor grad_gemm // the one flag of the whole row is reset to 0, published. const bool plain = wgrad && ctx.num_clusters > 0; const size_t n_chunk = plain ? 0 : combine_chunk(hidden); - const size_t chunk = plain ? hidden : n_chunk; + const size_t chunk = plain ? whole_row_chunk(hidden) : n_chunk; // With the weight gradient the GEMM runs alone on every SM, and the weight gradient beside the // dispatch backward. @@ -1016,7 +1021,7 @@ void nvte_ep_dispatch_gemm_bwd(NVTETensor handle_mem, const NVTETensor grad_gemm const tvm::ffi::Function gemm = get_gemm(config, &layout); GemmScratch scratch = claim_scratch(ws_base, ws_bytes, layout.total_bytes, num_experts, rows, true, wgrad ? wgrad->layout.total_bytes : 0); - set_chunk_words(scratch, layout, plain ? 0 : hidden / chunk, + set_chunk_words(scratch, layout, plain ? 0 : DIVUP(hidden, chunk), plain ? layout.total_bytes : layout.signal); if (wgrad) { scratch.reset.fill(scratch.wgrad + wgrad->layout.counter, 1, ep::kFillZero); @@ -1054,7 +1059,7 @@ void nvte_ep_dispatch_gemm_bwd(NVTETensor handle_mem, const NVTETensor grad_gemm } NVTECommWindow no_window{}; - TensorWrapper signal(scratch.base + layout.signal, std::vector{hidden / chunk}, + TensorWrapper signal(scratch.base + layout.signal, std::vector{DIVUP(hidden, chunk)}, DType::kInt32); const ep::EpSignal combine_signal{signal.data(), chunk}; ctx.backend.dispatch_bwd(handle_mem, grad_recv_tokens, no_window, grad_recv_topk_weights, From 1a69da36a139b55fda3d2f4e03179ca5e5d629a6 Mon Sep 17 00:00:00 2001 From: Phuong Nguyen Date: Wed, 25 Nov 2026 13:14:57 -0800 Subject: [PATCH 04/67] [Common] Default the NCCL EP combine last-chunk push to 64 SMs Signed-off-by: Phuong Nguyen --- transformer_engine/common/ep/ep_backend.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/transformer_engine/common/ep/ep_backend.cpp b/transformer_engine/common/ep/ep_backend.cpp index 7613166ec87..890e2b41aed 100644 --- a/transformer_engine/common/ep/ep_backend.cpp +++ b/transformer_engine/common/ep/ep_backend.cpp @@ -441,6 +441,9 @@ void EPBackend::init(ncclComm_t ep_comm, NVTEEpGroupConfig group_config) { std::snprintf(sm_buf, sizeof(sm_buf), "%d", device_sms); setenv("NCCL_EP_SHUFFLE_SMS", sm_buf, /*overwrite=*/0); setenv("NCCL_EP_PREPROCESS_NUM_SMS", sm_buf, /*overwrite=*/0); + // The signaled combine pushes its last chunk on its own SMs; 64 of them saturate NVLink. + constexpr char kCombinePushLastChunkSms[] = "64"; + setenv("NCCL_EP_HT_COMBINE_PUSH_LAST_CHUNK_SMS", kCombinePushLastChunkSms, /*overwrite=*/0); }); NVTE_CHECK_NCCL(nccl_ep::create_group(&ep_group_, ep_comm, &cfg)); From 6f9500f90c4e4780bfcbf21ebfe084b617166f79 Mon Sep 17 00:00:00 2001 From: Phuong Nguyen Date: Mon, 30 Nov 2026 20:19:25 -0800 Subject: [PATCH 05/67] Move the CuTeDSL EP scaling modes to the shared util and make the MoE overlap support check internal Signed-off-by: Phuong Nguyen --- docs/api/pytorch.rst | 8 +-- tests/pytorch/distributed/run_ep.py | 5 +- .../common/CuTeDSL/ep_gemm/_loader.py | 3 -- .../common/CuTeDSL/ep_gemm/combine_gemm.py | 3 +- .../common/CuTeDSL/ep_gemm/dispatch_gemm.py | 3 +- .../common/CuTeDSL/ep_gemm/wgrad_gemm.py | 3 +- transformer_engine/common/CuTeDSL/utils.py | 5 ++ transformer_engine/pytorch/ops/__init__.py | 1 - .../pytorch/ops/fused/__init__.py | 7 +-- .../pytorch/ops/fused/moe_overlap.py | 51 +++---------------- 10 files changed, 20 insertions(+), 69 deletions(-) diff --git a/docs/api/pytorch.rst b/docs/api/pytorch.rst index 37d739a7b3a..2881da54ea7 100644 --- a/docs/api/pytorch.rst +++ b/docs/api/pytorch.rst @@ -151,17 +151,13 @@ NCCL-based dispatch and combine for experts sharded across ranks. See an ``EpBuffer``. A buffer holds the routing state of one call until its backward has run, so several calls in flight (for example pipeline microbatches) each need their own ``EpBuffer`` and op instance. The guide shows how to connect the per-expert counts and routing weights through the -sequence's extra-tensor channels. ``moe_overlap_supported`` tells whether such a sequence runs as -one fused op. +sequence's extra-tensor channels. With the overlap enabled (``NVTE_MOE_OVERLAP``) such a sequence +fuses into one op, or raises an error naming the reason when its settings are unsupported. .. autoapiclass:: transformer_engine.pytorch.ops.MoeDispatch .. autoapiclass:: transformer_engine.pytorch.ops.MoeCombine -.. autoapifunction:: transformer_engine.pytorch.ops.moe_overlap_supported - -.. autoapifunction:: transformer_engine.pytorch.ops.moe_overlap_unsupported_reason - .. autoapiclass:: transformer_engine.pytorch.ep.EpConfig .. autoapifunction:: transformer_engine.pytorch.ep.ep_bootstrap diff --git a/tests/pytorch/distributed/run_ep.py b/tests/pytorch/distributed/run_ep.py index b2ec1199238..c4e545a890b 100644 --- a/tests/pytorch/distributed/run_ep.py +++ b/tests/pytorch/distributed/run_ep.py @@ -19,6 +19,7 @@ from ep_reference import BlockScaledTensor, MoeEpReference, MoeFormat, quantize_blockwise import transformer_engine.pytorch as te from transformer_engine.pytorch import ops as te_ops +from transformer_engine.pytorch.ops.fused.moe_overlap import _moe_overlap_unsupported_reason from transformer_engine.common.recipe import MXFP8BlockScaling from transformer_engine.pytorch.ep import ( EpBuffer, @@ -851,12 +852,12 @@ def pack(tensor): self.assertTrue(out[4], "fusion selection") # The launcher requires this line from every rank of an overlap pass. print(f"OVERLAP_EXECUTED rank={self.cfg.rank}", flush=True) - supported = te_ops.moe_overlap_supported( + reason = _moe_overlap_unsupported_reason( config, ffn, params_dtype=torch.bfloat16, glu_interleave_size=glu_interleave_size, single_grouped_weight=True, recipe=recipe, primary_weights_in_fp8=quantized_weights, ) # fmt: skip - self.assertTrue(supported, "moe_overlap_supported matches the fuser") + self.assertIsNone(reason, "the fuser selects FusedMoE but the support check rejects it") # Row tensors saved: recv tokens (and their scales), the FC1 output and the routing # weights, plus the SwiGLU output in BF16. A frozen weight leaves out the input of its # weight gradient: the recv tokens and scales for FC1, the SwiGLU output (BF16) for FC2. diff --git a/transformer_engine/common/CuTeDSL/ep_gemm/_loader.py b/transformer_engine/common/CuTeDSL/ep_gemm/_loader.py index bfaa5c1789d..7ff72cd29f4 100644 --- a/transformer_engine/common/CuTeDSL/ep_gemm/_loader.py +++ b/transformer_engine/common/CuTeDSL/ep_gemm/_loader.py @@ -32,9 +32,6 @@ ROWS_PER_TILE = MMA_TILER_MN[0] // 2 * CLUSTER_MN[0] # Values per MXFP8 E8M0 scale. SF_VEC_SIZE = 32 -# Operand scaling modes (NVTEScalingMode): BF16 operands carry the delayed default, MXFP8 the 1D. -DELAYED_TENSOR_SCALING = 0 -MXFP8_1D_SCALING = 1 @dataclass(frozen=True) diff --git a/transformer_engine/common/CuTeDSL/ep_gemm/combine_gemm.py b/transformer_engine/common/CuTeDSL/ep_gemm/combine_gemm.py index cd7259029bf..1f28ad7cad3 100644 --- a/transformer_engine/common/CuTeDSL/ep_gemm/combine_gemm.py +++ b/transformer_engine/common/CuTeDSL/ep_gemm/combine_gemm.py @@ -24,12 +24,11 @@ from cutlass import cute from cutlass.cute.nvgpu import OperandMajorMode +from ..utils import DELAYED_TENSOR_SCALING, MXFP8_1D_SCALING from ._loader import ( device_compute_capability, CLUSTER_MN, - DELAYED_TENSOR_SCALING, MMA_TILER_MN, - MXFP8_1D_SCALING, ROWS_PER_TILE, blockscaled_kwargs, compile_launch, diff --git a/transformer_engine/common/CuTeDSL/ep_gemm/dispatch_gemm.py b/transformer_engine/common/CuTeDSL/ep_gemm/dispatch_gemm.py index 001419e51a7..1076690b59a 100644 --- a/transformer_engine/common/CuTeDSL/ep_gemm/dispatch_gemm.py +++ b/transformer_engine/common/CuTeDSL/ep_gemm/dispatch_gemm.py @@ -31,12 +31,11 @@ from cutlass import cute from cutlass.cute.nvgpu import OperandMajorMode +from ..utils import DELAYED_TENSOR_SCALING, MXFP8_1D_SCALING from ._loader import ( device_compute_capability, CLUSTER_MN, - DELAYED_TENSOR_SCALING, MMA_TILER_MN, - MXFP8_1D_SCALING, ROWS_PER_TILE, blockscaled_kwargs, compile_launch, diff --git a/transformer_engine/common/CuTeDSL/ep_gemm/wgrad_gemm.py b/transformer_engine/common/CuTeDSL/ep_gemm/wgrad_gemm.py index 2137dea46fe..151985b455d 100644 --- a/transformer_engine/common/CuTeDSL/ep_gemm/wgrad_gemm.py +++ b/transformer_engine/common/CuTeDSL/ep_gemm/wgrad_gemm.py @@ -24,13 +24,12 @@ import cutlass from cutlass import cute +from ..utils import DELAYED_TENSOR_SCALING, MXFP8_1D_SCALING from ._loader import ( compile_launch, device_compute_capability, CLUSTER_MN, - DELAYED_TENSOR_SCALING, MMA_TILER_MN, - MXFP8_1D_SCALING, SF_VEC_SIZE, fake_tensor, fp8_fake, diff --git a/transformer_engine/common/CuTeDSL/utils.py b/transformer_engine/common/CuTeDSL/utils.py index b121fdc91aa..b92d57d352c 100644 --- a/transformer_engine/common/CuTeDSL/utils.py +++ b/transformer_engine/common/CuTeDSL/utils.py @@ -24,6 +24,11 @@ } _STR_FROM_CUTLASS_DTYPE = {v: k for k, v in _CUTLASS_DTYPE_FROM_STR.items()} +# Operand scaling modes, mirroring the C NVTEScalingMode enum (transformer_engine.h): BF16 operands +# carry the delayed default, MXFP8 the 1D scaling. +DELAYED_TENSOR_SCALING = 0 +MXFP8_1D_SCALING = 1 + logger = logging.getLogger("transformer_engine.cutedsl.utils") diff --git a/transformer_engine/pytorch/ops/__init__.py b/transformer_engine/pytorch/ops/__init__.py index 4fbbe2c5e8e..5e21bb39e8d 100644 --- a/transformer_engine/pytorch/ops/__init__.py +++ b/transformer_engine/pytorch/ops/__init__.py @@ -18,4 +18,3 @@ from .op import BasicOperation, FusedOperation, FusibleOperation from .sequential import Sequential from . import fused -from .fused import moe_overlap_supported, moe_overlap_unsupported_reason diff --git a/transformer_engine/pytorch/ops/fused/__init__.py b/transformer_engine/pytorch/ops/fused/__init__.py index d1b0b1b715f..0af33f3b18e 100644 --- a/transformer_engine/pytorch/ops/fused/__init__.py +++ b/transformer_engine/pytorch/ops/fused/__init__.py @@ -15,7 +15,6 @@ from .userbuffers_backward_linear import UserbuffersBackwardLinear from .userbuffers_forward_linear import UserbuffersForwardLinear - # Register forward fusions register_forward_fusion(UserbuffersForwardLinear.fuse_forward_ops) register_forward_fusion(ForwardLinearBiasAdd.fuse_forward_ops) @@ -36,8 +35,4 @@ GroupedMLP_CuTeGEMMUnary, GroupedMLP_CuTeGEMMGLUBf16, ) -from .moe_overlap import ( # pylint: disable=wrong-import-position - FusedMoE, - moe_overlap_supported, - moe_overlap_unsupported_reason, -) +from .moe_overlap import FusedMoE # pylint: disable=wrong-import-position diff --git a/transformer_engine/pytorch/ops/fused/moe_overlap.py b/transformer_engine/pytorch/ops/fused/moe_overlap.py index e262749bc6d..202d27e8ce1 100644 --- a/transformer_engine/pytorch/ops/fused/moe_overlap.py +++ b/transformer_engine/pytorch/ops/fused/moe_overlap.py @@ -83,8 +83,7 @@ class FusedMoE(FusedOperation): Notes: - With the overlap enabled (``NVTE_MOE_OVERLAP``), a ``Sequential`` of these ops that does not - meet the requirements raises an error naming the reason, instead of running unfused; - ``moe_overlap_unsupported_reason`` gives it beforehand. + meet the requirements raises an error naming the reason, instead of running unfused. - Each GEMM allocates a small uint8 workspace for its flags and state in the binding, freed after the call; the calls of an EP group must run on one CUDA stream. - With a fixed receive capacity the op can be captured in a CUDA graph after a warmup call; @@ -871,7 +870,7 @@ def _routing_extras_internal(dispatch, fc1, activation, fc2) -> bool: ) -def moe_overlap_unsupported_reason( +def _moe_overlap_unsupported_reason( config: EpConfig, ffn_hidden_size: int, *, @@ -886,8 +885,9 @@ def moe_overlap_unsupported_reason( """Why a ``Sequential`` of ``MoeDispatch``, ``GroupedLinear``, ``ScaledSwiGLU``, ``GroupedLinear`` and ``MoeCombine`` built with these settings does not run as one ``FusedMoE``, or ``None`` when it does. The reason names an unsupported setting or the - grouped GEMM backend failing to load on this device. See ``moe_overlap_supported`` for what - the query covers. + grouped GEMM backend failing to load on this device. It only queries the device; + deterministic execution and an autocast dtype other than BF16 are unsupported, and the answer + follows the settings in effect at the call. Parameters ---------- @@ -986,50 +986,11 @@ def moe_overlap_unsupported_reason( return None -def moe_overlap_supported( - config: EpConfig, - ffn_hidden_size: int, - *, - params_dtype: torch.dtype, - activation: str = "swiglu", - glu_interleave_size: Optional[int] = None, - bias: bool = False, - single_grouped_weight: bool = False, - recipe: Optional[Recipe] = None, - primary_weights_in_fp8: bool = False, -) -> bool: - """Whether a ``Sequential`` of ``MoeDispatch``, ``GroupedLinear``, ``ScaledSwiGLU``, - ``GroupedLinear`` and ``MoeCombine`` built with these settings runs as one ``FusedMoE``; - ``moe_overlap_unsupported_reason`` gives the reason when it does not and takes the same - parameters. - - Call it after ``ep_bootstrap``. It only queries the device. Deterministic execution - (``NVTE_ALLOW_NONDETERMINISTIC_ALGO=0`` or ``torch.use_deterministic_algorithms``) and an - autocast dtype other than BF16 are unsupported; the answer follows the settings in effect at - the call. GroupedLinear settings it does not take, such as ``delay_wgrad_compute`` or - ``accumulate_into_main_grad``, can still make the ops unsupported. - """ - return ( - moe_overlap_unsupported_reason( - config, - ffn_hidden_size, - params_dtype=params_dtype, - activation=activation, - glu_interleave_size=glu_interleave_size, - bias=bias, - single_grouped_weight=single_grouped_weight, - recipe=recipe, - primary_weights_in_fp8=primary_weights_in_fp8, - ) - is None - ) - - def _unsupported_reason(dispatch, fc1, activation, fc2, combine, recipe=None) -> Optional[str]: """Why a window cannot use the overlapped ops, or ``None`` when it can.""" config = dispatch.config dtypes = {w.dtype for fc in (fc1, fc2) for w in fc._get_weight_tensors()} - reason = moe_overlap_unsupported_reason( + reason = _moe_overlap_unsupported_reason( config, fc2.in_features, params_dtype=dtypes.pop() if len(dtypes) == 1 else None, From 445e222c0534add84025e21787d0db658fc1c120 Mon Sep 17 00:00:00 2001 From: Phuong Nguyen Date: Mon, 30 Nov 2026 20:19:25 -0800 Subject: [PATCH 06/67] Reuse the shared grouped MXFP8 requant with PDL for the EP weight gradients Signed-off-by: Phuong Nguyen --- tests/pytorch/test_ep_gemm.py | 100 +----- transformer_engine/common/CuTeDSL/__init__.py | 2 - .../CuTeDSL/cast/mxfp8/requantize_mxfp8.py | 31 +- .../common/CuTeDSL/ep_gemm/__init__.py | 3 +- .../common/CuTeDSL/ep_gemm/requantize.py | 331 ------------------ .../cast/mxfp8/requantize_mxfp8_cutedsl.cuh | 24 +- transformer_engine/common/ep/ep_gemm_api.cpp | 77 ++-- transformer_engine/common/ep/ep_gemm_config.h | 26 -- .../common/ep/ep_overlap_workspace.cu | 6 + .../common/ep/ep_overlap_workspace.h | 4 + 10 files changed, 103 insertions(+), 501 deletions(-) delete mode 100644 transformer_engine/common/CuTeDSL/ep_gemm/requantize.py diff --git a/tests/pytorch/test_ep_gemm.py b/tests/pytorch/test_ep_gemm.py index dab7f7328a2..5dd057c6a1d 100644 --- a/tests/pytorch/test_ep_gemm.py +++ b/tests/pytorch/test_ep_gemm.py @@ -22,7 +22,6 @@ from transformer_engine.common.CuTeDSL.ep_gemm import ( combine_gemm, dispatch_gemm, - requantize, wgrad_gemm, ) @@ -84,7 +83,7 @@ def _run_gemm(rows_per_expert, rows_alignment, mxfp8, tail_clusters, device_layo ) launches.append(tvm_ffi.get_global_func(name)) - gen = torch.Generator(device=device).manual_seed(0) + gen = torch.Generator(device=device).manual_seed(7) dtype = torch.float8_e4m3fn if mxfp8 else torch.bfloat16 a = torch.rand(rows, hidden, device=device, generator=gen).to(dtype) b = (torch.rand(experts, n, hidden, device=device, generator=gen) * 2 * hidden**-0.5).to(dtype) @@ -194,7 +193,7 @@ def _run_combine(rows_per_expert, rows_alignment, mxfp8, backward): ) gemm = tvm_ffi.get_global_func(name) - gen = torch.Generator(device=device).manual_seed(0) + gen = torch.Generator(device=device).manual_seed(7) dtype = torch.float8_e4m3fn if mxfp8 else torch.bfloat16 w_shape = (experts, k, n) if backward else (experts, n, k) a = torch.rand(rows, k, device=device, generator=gen).to(dtype) @@ -266,7 +265,7 @@ def _run_wgrad(rows_per_expert, mxfp8, fp32_out, accumulate): assert wgrad_gemm.get_ep_wgrad_function(name + "_desc", *desc) launches.insert(0, tvm_ffi.get_global_func(name + "_desc")) - gen = torch.Generator(device=device).manual_seed(0) + gen = torch.Generator(device=device).manual_seed(7) dtype = torch.float8_e4m3fn if mxfp8 else torch.bfloat16 # Powers of two keep every product and sum exact in float32; signs on grad add cancellation. signs = 1 - 2 * torch.randint(0, 2, (rows, m), device=device, generator=gen) @@ -324,96 +323,3 @@ def test_wgrad_gemm_matches_reference(mxfp8, fp32_out, accumulate, rows_per_expe tol = 2.0**-16 if fp32_out else 2.0**-8 err = (weight_grad - ref).abs() / ref.abs().clamp_min(1e-6) assert err.max() <= tol - - -def _read_col_scales(words, rows_per_expert, cols, device): - """Columnwise E8M0 scale per row and column from the GEMM-swizzled per-expert scale words.""" - scale = torch.ones(sum(rows_per_expert), cols, device=device) - col = torch.arange(cols, device=device) - start = 0 - for count in rows_per_expert: - if count: - r = torch.arange(start, start + count, device=device) - group = r // 128 - start // 128 - index = ( - start * (cols // 128) - + (col // 128) * count - + group[:, None] * 128 - + (col % 32)[None, :] * 4 - + ((col // 32) % 4)[None, :] - ) - block = (r // 32) % 4 - e8m0 = (words[index] >> (8 * block[:, None])) & 0xFF - scale[start : start + count] = torch.pow(2.0, e8m0.float() - 127) - start += count - return scale - - -def _run_requant(rows_per_expert, cols, ready_slot_rows=0, nan_scale=None): - """Launch the MXFP8 rowwise-to-columnwise requant and return (codes, col_codes, scale words, - used). Row scales are unit, so the rowwise values are the codes themselves. With - ``ready_slot_rows``, the rows and then their dispatch flags arrive late, on another stream. - ``nan_scale`` is a (row, 32-column block) whose rowwise scale is the E8M0 NaN.""" - device = torch.device("cuda") - experts = len(rows_per_expert) - # Spare rows, a whole slot: the capacity exceeds the rows in use. - rows = sum(rows_per_expert) + max(128, ready_slot_rows) - name = f"test_ep_requant_{rows}_{cols}_{ready_slot_rows}" - assert requantize.get_ep_requant_function(name, rows, cols, experts, ready_slot_rows) - fn = tvm_ffi.get_global_func(name) - - gen = torch.Generator(device=device).manual_seed(0) - # Powers of two: the columnwise requant represents them exactly, so it costs no tolerance. - exps = torch.randint(-2, 2, (rows, cols), device=device, generator=gen).float() - signs = 1 - 2 * torch.randint(0, 2, (rows, cols), device=device, generator=gen) - codes = (signs * torch.pow(2.0, exps)).to(torch.float8_e4m3fn) - row_scales = _unit_e8m0(rows * cols // 32, device) - if nan_scale is not None: - row_scales.view(torch.uint8)[nan_scale[0] * (cols // 32) + nan_scale[1]] = 255 - col_codes = torch.zeros(rows, cols, dtype=torch.float8_e4m3fn, device=device) - col_scales = _unit_e8m0(rows * cols // 32, device) - ends = torch.tensor(rows_per_expert, device=device).cumsum(0).to(torch.int32) - stream = ctypes.c_void_p(torch.cuda.current_stream().cuda_stream) - if ready_slot_rows: - received = torch.zeros_like(codes) - signal = torch.full((rows // ready_slot_rows,), -1, dtype=torch.int32, device=device) - # Enqueued first, so a run that serializes kernels does not hang. - arrival = torch.cuda.Stream() - arrival.wait_stream(torch.cuda.current_stream()) - with torch.cuda.stream(arrival): - torch.cuda._sleep(10**7) - received.copy_(codes) - signal.fill_(0) - fn(received, row_scales, col_codes, col_scales, ends, signal, stream) - else: - fn(codes, row_scales, col_codes, col_scales, ends, stream) - torch.cuda.synchronize() - words = col_scales.view(torch.uint8).view(torch.int32) - return codes.float(), col_codes.float(), words, sum(rows_per_expert) - - -@pytest.mark.parametrize("ready_slot_rows", [0, 128, 256]) -@pytest.mark.parametrize( - "cols,rows_per_expert", - [ - (256, [128, 256, 0, 128]), - (512, [256, 0, 128, 128]), - ], -) -def test_requantize_matches_reference(cols, rows_per_expert, ready_slot_rows): - """MXFP8 rowwise-to-columnwise requant reproduces the dequantized rows exactly for power-of-two - values; rows past the last expert stay 0. With ``ready_slot_rows``, it waits for rows that - arrive after its launch.""" - codes, col_codes, words, used = _run_requant(rows_per_expert, cols, ready_slot_rows) - scale = _read_col_scales(words, rows_per_expert, cols, codes.device) - assert torch.equal(col_codes[:used] * scale, codes[:used]) - assert torch.count_nonzero(col_codes[used:]) == 0 - - -def test_requantize_nan_scale(): - """A rowwise E8M0 scale of 255 makes its 32 values NaN and leaves every other value finite.""" - cols, row, block = 256, 5, 2 - _, col_codes, _, used = _run_requant([128], cols, nan_scale=(row, block)) - expected = torch.zeros(used, cols, dtype=torch.bool, device=col_codes.device) - expected[row, block * 32 : (block + 1) * 32] = True - assert torch.equal(col_codes[:used].isnan(), expected) diff --git a/transformer_engine/common/CuTeDSL/__init__.py b/transformer_engine/common/CuTeDSL/__init__.py index 4243d6b418f..ab845848858 100644 --- a/transformer_engine/common/CuTeDSL/__init__.py +++ b/transformer_engine/common/CuTeDSL/__init__.py @@ -32,7 +32,6 @@ def _register_ep_backends(): from transformer_engine.common.CuTeDSL.ep_gemm import ( # pylint: disable=import-outside-toplevel dispatch_gemm, combine_gemm, - requantize, wgrad_gemm, ) @@ -44,7 +43,6 @@ def _register_ep_backends(): wgrad_gemm.get_ep_wgrad_function, wgrad_gemm.get_ep_wgrad_workspace_layout, wgrad_gemm.get_ep_wgrad_reads_descriptors, - requantize.get_ep_requant_function, ): tvm_ffi.register_global_func(function.__name__, function, override=True) except Exception as e: # pylint: disable=broad-exception-caught diff --git a/transformer_engine/common/CuTeDSL/cast/mxfp8/requantize_mxfp8.py b/transformer_engine/common/CuTeDSL/cast/mxfp8/requantize_mxfp8.py index 935e4a5c890..ce6221fb7c0 100644 --- a/transformer_engine/common/CuTeDSL/cast/mxfp8/requantize_mxfp8.py +++ b/transformer_engine/common/CuTeDSL/cast/mxfp8/requantize_mxfp8.py @@ -1019,8 +1019,9 @@ class GroupedRequantizeWarpTile: BlocksPerTile = 4 def __init__( - self, hidden, *, input_dtype=cutlass.Float8E4M3FN, swizzled=True, rowwise_output=True - ): + self, hidden, *, input_dtype=cutlass.Float8E4M3FN, swizzled=True, rowwise_output=True, + pdl=False, + ): # fmt: skip if hidden <= 0 or hidden % self.TILE: raise ValueError("Grouped MXFP8 requantization requires a 128-aligned hidden size") if input_dtype not in (cutlass.Float8E4M3FN, cutlass.Float8E5M2): @@ -1030,6 +1031,9 @@ def __init__( self.use_scaled_cvt = _supports_scaled_bf16_conversion() self.swizzled = bool(swizzled) self.rowwise_output = bool(rowwise_output and swizzled) + # Run as a programmatic dependent (PDL) so it can overlap a producing kernel on the SMs + # that kernel frees, instead of waiting for it to finish. + self.pdl = bool(pdl) @cute.jit def __call__( @@ -1050,6 +1054,7 @@ def __call__( # At most 96 registers: ten CTAs per SM keep enough loads in flight. min_blocks_per_mp=10, stream=stream, + use_pdl=self.pdl, ) @cute.kernel @@ -1067,6 +1072,8 @@ def kernel( tiles_x = cutlass.const_expr(cols // self.TILE) sf_stride = cutlass.const_expr(cols // 32) rows_per_lane = cutlass.const_expr(self.RowsPerLane) + if cutlass.const_expr(self.pdl): + cute.arch.griddepcontrol_launch_dependents() tid, _, _ = cute.arch.thread_idx() bid, _, _ = cute.arch.block_idx() lane = tid % 32 @@ -1234,10 +1241,14 @@ def kernel( ), cute.make_layout((1,)), )[0] = Uint8(col_scales[pair] >> (block * 8)) + if cutlass.const_expr(self.pdl): + # The grid completes after the producing kernel: CTA 0 waits for it at exit. + if bid == 0: + cute.arch.griddepcontrol_wait() @functools.lru_cache(maxsize=None) -def _compile_warp_tile_requantization(input_dtype, hidden, swizzled, rowwise_output): +def _compile_warp_tile_requantization(input_dtype, hidden, swizzled, rowwise_output, pdl): """Compile the warp-tile kernel once for every row and group count.""" rows = cute.sym_int32(divisibility=128) scales = cute.sym_int32() @@ -1253,7 +1264,11 @@ def tensor(element_type, shape): compiled = cute.compile( GroupedRequantizeWarpTile( - hidden, input_dtype=input_dtype, swizzled=swizzled, rowwise_output=rowwise_output + hidden, + input_dtype=input_dtype, + swizzled=swizzled, + rowwise_output=rowwise_output, + pdl=pdl, ), tensor(input_dtype, (rows, hidden)), tensor(cutlass.Float8E8M0FNU, (rows, hidden // 32)), @@ -1280,8 +1295,10 @@ def get_mxfp8_requantization_function( rowwise_output, return_dequantized, sm_count, + pdl=False, ): - """Compile/register one common C API specialization, or request CUDA fallback.""" + """Compile/register one common C API specialization, or request CUDA fallback. + ``pdl`` runs the warp-tile kernel as a programmatic dependent (EP overlap).""" if tvm_ffi.get_global_func(fn_name, allow_missing=True) is not None: return True try: @@ -1290,11 +1307,13 @@ def get_mxfp8_requantization_function( tvm_ffi.register_global_func( fn_name, _compile_warp_tile_requantization( - input_dtype, hidden, bool(swizzled), bool(rowwise_output) + input_dtype, hidden, bool(swizzled), bool(rowwise_output), bool(pdl) ), override=True, ) return True + if pdl: + raise ValueError("PDL grouped MXFP8 requantization is not supported for now") kernel = GroupedRequantize( hidden, groups, diff --git a/transformer_engine/common/CuTeDSL/ep_gemm/__init__.py b/transformer_engine/common/CuTeDSL/ep_gemm/__init__.py index 2e9e21a1314..75a51debf7c 100644 --- a/transformer_engine/common/CuTeDSL/ep_gemm/__init__.py +++ b/transformer_engine/common/CuTeDSL/ep_gemm/__init__.py @@ -7,7 +7,6 @@ dispatch_gemm: reads row tiles as a dispatch delivers them (FC1 forward, FC2 data gradient). combine_gemm: publishes column chunks for a combine to send (FC2 forward, FC1 data gradient). wgrad_gemm: weight gradients chained behind the backward GEMMs. -requantize: columnwise MXFP8 operands of the weight gradients from received rowwise rows. """ -from . import dispatch_gemm, combine_gemm, requantize, wgrad_gemm +from . import dispatch_gemm, combine_gemm, wgrad_gemm diff --git a/transformer_engine/common/CuTeDSL/ep_gemm/requantize.py b/transformer_engine/common/CuTeDSL/ep_gemm/requantize.py deleted file mode 100644 index 2cf7b2b94a6..00000000000 --- a/transformer_engine/common/CuTeDSL/ep_gemm/requantize.py +++ /dev/null @@ -1,331 +0,0 @@ -# Copyright (c) 2022-2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. -# -# See LICENSE for license information. - -"""EP weight-gradient requantizer for the received rows. - -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. - -Rowwise MXFP8 rows ([rows, cols] E4M3 data with compact E8M0 scales, one per 32 columns of a row) -become columnwise MXFP8 ([rows, cols] E4M3 data with one scale per 32 rows of a column, scales -GEMM-swizzled per expert slab), the operand layout of the MXFP8 weight gradients. Each value is -dequantized and quantized again with TE's MXFP8 rule. Operands: ``codes``, ``row_scales``, -``col_codes``, ``col_scales``, ``expert_row_ends`` [experts] int32 (every slab a multiple of 128 -rows), optional ``signal`` [rows / ready_slot_rows] int32, stream. - -A launch is one CTA per (128-row, 256-column) tile of the receive capacity, a programmatic dependent -of the kernel before it that lets the kernel behind it start at once. CTAs past the last expert row -end exit; with ``signal``, a tile starts once the dispatch has set the slots of its rows. The grid -completes after the kernel before it. -""" - -import math -from dataclasses import dataclass -from typing import Optional - -import cuda.bindings.driver as cuda -import cutlass -from cutlass import Float32, Float8E4M3FN, Int32, Int64, Uint8, Uint16, Uint32, cute -from cutlass.experimental.primitives import cvt_packfloat_f32 - -from ._loader import ( - compile_launch, - SF_VEC_SIZE, - fake_tensor, - fp8_fake, - import_gemm_modules, - register_function, -) - -# A thread's rows of a 32-row block, its bytes per row and the warps per CTA. -ROWS_PER_THREAD, VEC, NUM_WARPS = 16, 8, 2 -# Lanes that share a group of VEC columns, each with its own rows of a block. -ROW_LANES = SF_VEC_SIZE // ROWS_PER_THREAD -# Columns per tile. -TILE_COLUMNS = 32 // ROW_LANES * VEC * NUM_WARPS -# Scale blocks along the rows per tile: one 128-row scale atom. -BLOCKS_PER_TILE = 4 -# Rows per tile. -TILE_ROWS = BLOCKS_PER_TILE * SF_VEC_SIZE -# fp32(1 / 448), the reciprocal of the largest E4M3 value. -E4M3_MAX_RCP = 1.0 / 448.0 -# 2^-127, the multiplier of E8M0 0. -E8M0_ZERO_MULTIPLIER = 2.0**-127 -# Order of a thread's four column pairs. Any order gives the same bytes; this one takes 128 -# registers, which fits 8 CTAs per SM. -PAIR_ORDER = (0, 3, 1, 2) - - -@dataclass(frozen=True) -class Mxfp8RequantConfig: - """Static configuration of one compiled MXFP8 requant launch.""" - - rows: int # receive capacity in rows - cols: int # columns - num_experts: int # local experts - ready_slot_rows: int = 0 # wait until signal[] is set for every slot of a tile's rows - - -class _Mxfp8RequantKernel: - """MXFP8 requant of a ``cfg`` operand, one CTA per tile.""" - - def __init__(self, cfg: Mxfp8RequantConfig): - self.cfg = cfg - if cfg.ready_slot_rows: - scheduler = import_gemm_modules("moe_streaming_input_block_tile_scheduler")[0] - self.poll_until_at_least = scheduler._poll_until_at_least - self.wait_slots_ready = scheduler.wait_slots_ready - - @cute.jit - def __call__( - self, - codes: cute.Pointer, - row_scales: cute.Pointer, - col_codes: cute.Pointer, - col_scales: cute.Pointer, - expert_row_ends: cute.Pointer, - signal: Optional[cute.Pointer], - stream: cuda.CUstream, - ): - self.tile_kernel(codes, row_scales, col_codes, col_scales, expert_row_ends, signal).launch( - grid=[self.cfg.rows // TILE_ROWS * (self.cfg.cols // TILE_COLUMNS), 1, 1], - block=[32 * NUM_WARPS, 1, 1], - stream=stream, - use_pdl=True, - ) - - @cute.kernel - def tile_kernel( - self, - codes: cute.Pointer, - row_scales: cute.Pointer, - col_codes: cute.Pointer, - col_scales: cute.Pointer, - expert_row_ends: cute.Pointer, - signal: Optional[cute.Pointer], - ): - """Tile ``blockIdx.x`` if it ends at or before the last expert end; CTA 0 waits for the - kernel before it at exit, so the grid completes after that one.""" - num_experts = self.cfg.num_experts - cute.arch.griddepcontrol_launch_dependents() - ends = cute.make_tensor(expert_row_ends, cute.make_layout((num_experts,))) - num_tiles = ends[num_experts - 1] // TILE_ROWS * (self.cfg.cols // TILE_COLUMNS) - bidx, _, _ = cute.arch.block_idx() - if bidx < num_tiles: - if cutlass.const_expr(signal is not None): - self.wait_rows_ready(signal, Int32(bidx)) - self.tile(codes, row_scales, col_codes, col_scales, expert_row_ends, Int32(bidx)) - if bidx == 0: - cute.arch.griddepcontrol_wait() - - @cute.jit - def wait_rows_ready(self, signal: cute.Pointer, tile: Int32): - """Wait until the dispatch has set the ``signal`` slots of the rows of tile ``tile``: warp 0 - polls them relaxed, then acquires them once.""" - slot_rows = self.cfg.ready_slot_rows - num_slots = max(TILE_ROWS // slot_rows, 1) - tidx, _, _ = cute.arch.thread_idx() - if tidx < 32: - slots = signal + tile // (self.cfg.cols // TILE_COLUMNS) * TILE_ROWS // slot_rows - for j in cutlass.range_constexpr((num_slots + 31) // 32): - self.poll_until_at_least(slots + cutlass.min(tidx + j * 32, num_slots - 1), 0) - self.wait_slots_ready(slots, Int32(num_slots)) - cute.arch.sync_threads() - - @cute.jit - def tile( - self, - codes: cute.Pointer, - row_scales: cute.Pointer, - col_codes: cute.Pointer, - col_scales: cute.Pointer, - expert_row_ends: cute.Pointer, - tile: Int32, - ): - """Requantize tile ``tile`` and write its scale words.""" - # pylint: disable=too-many-locals - R, V, COLS = ROWS_PER_THREAD, VEC, self.cfg.cols - num_experts = self.cfg.num_experts - tidx, _, _ = cute.arch.thread_idx() - # A thread owns VEC columns of the tile and every ROW_LANES-th row of each 32-row block. - lane_row, lane_column = tidx % ROW_LANES, tidx // ROW_LANES - row_group = tile // (COLS // TILE_COLUMNS) - column = (tile % (COLS // TILE_COLUMNS)) * TILE_COLUMNS + lane_column * V - warp_first_column = (tile % (COLS // TILE_COLUMNS)) * TILE_COLUMNS + (tidx // 32) * (R * V) - access = cute.make_copy_atom(cute.nvgpu.CopyUniversalOp(), Uint16, num_bits_per_copy=8 * V) - r_codes = cute.make_rmem_tensor((V // 2, R), Uint16) - r_out = cute.make_rmem_tensor((V // 2, R), Uint16) - pair_row, pair_broadcast = cute.make_layout((2,)), cute.make_layout((2,), stride=(0,)) - codes_e4m3 = cute.recast_tensor(r_codes, Float8E4M3FN) - out_e4m3 = cute.recast_tensor(r_out, Float8E4M3FN) - r_values = cute.make_rmem_tensor((2, R), Float32) - r_scales = cute.make_rmem_tensor((R,), Uint8) - row_multiplier_bits = cute.make_rmem_tensor((R,), Int32) - row_multiplier = cute.recast_tensor(row_multiplier_bits, Float32) - multiplier_bits = cute.make_rmem_tensor((2,), Int32) - multiplier = cute.recast_tensor(multiplier_bits, Float32) - scaled_amax = cute.make_rmem_tensor((2,), Float32) - # One word per column pair: this lane's column of the pair, one scale byte per 32-row block. - packed = cute.make_rmem_tensor((V // 2,), Uint32) - packed.fill(0) - for block in cutlass.range(BLOCKS_PER_TILE, unroll=1): - first_row = Int64(row_group) * TILE_ROWS + block * SF_VEC_SIZE + lane_row - rows = cute.make_layout((V // 2, R), stride=(1, ROW_LANES * COLS // 2)) - offset = cute.assume(first_row * COLS + column, divby=V) - cute.copy( - access, - cute.make_tensor(cute.recast_ptr(codes + offset, dtype=Uint16), rows), - r_codes, - ) - # Prefetch the next block's codes and row scales into L2. - if block < BLOCKS_PER_TILE - 1: - next_row = Int64(row_group) * TILE_ROWS + (block + 1) * SF_VEC_SIZE + tidx % 32 - cute.arch.prefetch( - (codes + (next_row * COLS + warp_first_column)).llvm_ptr, cache_level="L2" - ) - cute.arch.prefetch( - ( - row_scales - + (next_row * (COLS // SF_VEC_SIZE) + warp_first_column // SF_VEC_SIZE) - ).llvm_ptr, - cache_level="L2", - ) - cute.autovec_copy( - cute.make_tensor( - row_scales + (first_row * (COLS // SF_VEC_SIZE) + column // SF_VEC_SIZE), - cute.make_layout((R,), stride=(ROW_LANES * (COLS // SF_VEC_SIZE),)), - ), - r_scales, - ) - # 2^(s - 127) from its bits; s = 0 gives 2^-127 and s = 255 NaN. - for i in cutlass.range_constexpr(R): - row_multiplier_bits[i] = Int32(r_scales[i]) << 23 - row_multiplier[i] = cute.arch.fmax(row_multiplier[i], E8M0_ZERO_MULTIPLIER) - row_multiplier_bits[i] = row_multiplier_bits[i] | ( - ((Int32(r_scales[i]) + 1) >> 8) << 22 - ) - for q in PAIR_ORDER: - for i in cutlass.range_constexpr(R): - pair_codes = cute.make_tensor(codes_e4m3.iterator + 2 * q + V * i, pair_row) - pair_row_multiplier = cute.make_tensor( - row_multiplier.iterator + i, pair_broadcast - ) - cute.make_tensor(r_values.iterator + 2 * i, pair_row).store( - pair_codes.load().to(Float32) * pair_row_multiplier.load() - ) - for v in cutlass.range_constexpr(2): - # The amax ignores NaN; the column's other rows sit in the neighboring lanes. - amax = Float32(0.0) - for i in cutlass.range_constexpr(R): - amax = cute.arch.fmax(amax, abs(r_values[v, i])) - for k in cutlass.range_constexpr(int(math.log2(ROW_LANES))): - amax = cute.arch.fmax( - amax, cute.arch.shuffle_sync_bfly(amax, offset=1 << k) - ) - scaled_amax[v] = amax * E4M3_MAX_RCP - # E8M0 of both columns of the pair, rounded up, the first column in the high byte. - pair = cvt_packfloat_f32( - scaled_amax[0], scaled_amax[1], 0, "ue8m0x2", rnd="rp", sat="satfinite" - ) - packed[q] = (packed[q] >> 8) | (Uint32(pair >> (8 * (1 - lane_row))) << 24) - inverse = 0xFEFE - pair - for h in cutlass.range_constexpr(2): - multiplier_bits[h] = cutlass.max( - ((inverse >> (8 * (1 - h))) & 0xFF) << 23, Int32(0x00400000) - ) - for i in cutlass.range_constexpr(R): - pair_values = cute.make_tensor(r_values.iterator + 2 * i, pair_row) - cute.make_tensor(out_e4m3.iterator + 2 * q + V * i, pair_row).store( - (pair_values.load() * multiplier.load()).to(Float8E4M3FN) - ) - cute.copy( - access, - r_out, - cute.make_tensor(cute.recast_ptr(col_codes + offset, dtype=Uint16), rows), - ) - # The tile's expert by a branchless lower bound over the row ends, then its start row. - ends = cute.make_tensor(expert_row_ends, cute.make_layout((num_experts,))) - group_row = row_group * TILE_ROWS - expert, n = Int32(0), num_experts - for _ in cutlass.range_constexpr(int(math.ceil(math.log2(num_experts)))): - half = n // 2 - expert = cutlass.select_(ends[expert + half - 1] <= group_row, expert + half, expert) - n -= half - expert = cutlass.select_(ends[expert] <= group_row, expert + 1, expert) - if expert < num_experts: - start = cutlass.select_(expert > 0, ends[cutlass.max(expert - 1, Int32(0))], Int32(0)) - count = ends[expert] - start - local_group = Int64(row_group - start // TILE_ROWS) - # Int32 word of the expert's swizzled scales: its start, the 128-column atom, the - # 128-row group in it, the column in its 32 and which of the four 32-column groups. - c = column + lane_row - index = ( - Int64(start) * (COLS // 128) - + Int64(c // 128) * count - + local_group * 128 - + (c % 32) * 4 - + (c // 32) % 4 - ) - for j in cutlass.range_constexpr(V // 2): - word = cute.make_tensor( - col_scales + index + j * ROW_LANES * 4, cute.make_layout((1,)) - ) - word[0] = packed[j] - - -def _compile(cfg: Mxfp8RequantConfig): - """Compile the launch wrapper of ``cfg`` with TVM-FFI.""" - assert cfg.rows % TILE_ROWS == 0 and cfg.cols % TILE_COLUMNS == 0, (cfg.rows, cfg.cols) - slot_rows = cfg.ready_slot_rows - # A tile waits for whole slots: one, or the slots it spans; the capacity is whole slots. - assert not slot_rows or ( - (TILE_ROWS % slot_rows == 0 or slot_rows % TILE_ROWS == 0) and cfg.rows % slot_rows == 0 - ), (cfg.rows, slot_rows) - requant = _Mxfp8RequantKernel(cfg) - - @cute.jit - def launch(codes, row_scales, col_codes, col_scales, expert_row_ends, stream): - requant( - cute.recast_ptr(codes.iterator, dtype=Uint8), - cute.recast_ptr(row_scales.iterator, dtype=Uint8), - cute.recast_ptr(col_codes.iterator, dtype=Uint8), - cute.recast_ptr(col_scales.iterator, dtype=Int32), - expert_row_ends.iterator, - None, - stream, - ) - - @cute.jit - def launch_ready(codes, row_scales, col_codes, col_scales, expert_row_ends, signal, stream): - requant( - cute.recast_ptr(codes.iterator, dtype=Uint8), - cute.recast_ptr(row_scales.iterator, dtype=Uint8), - cute.recast_ptr(col_codes.iterator, dtype=Uint8), - cute.recast_ptr(col_scales.iterator, dtype=Int32), - expert_row_ends.iterator, - signal.iterator, - stream, - ) - - rows, cols = cfg.rows, cfg.cols - scales = rows * cols // SF_VEC_SIZE - signal_fake = (fake_tensor(Int32, (rows // slot_rows,), (0,), 4),) if slot_rows else () - return compile_launch( - launch_ready if slot_rows else launch, - fp8_fake((rows, cols), (1, 0)), - fake_tensor(cutlass.Float8E8M0FNU, (scales,), (0,), 16), - fp8_fake((rows, cols), (1, 0)), - fake_tensor(cutlass.Float8E8M0FNU, (scales,), (0,), 16), - fake_tensor(Int32, (cfg.num_experts,), (0,), 16), - *signal_fake, - ) - - -def get_ep_requant_function(fn_name, rows, cols, num_experts, ready_slot_rows=0) -> bool: - """Compile and register the requant of this configuration as ``fn_name``; return whether it - is. ``ready_slot_rows`` > 0: the function takes ``signal`` before the stream.""" - cfg = Mxfp8RequantConfig(rows, cols, num_experts, ready_slot_rows) - return register_function(fn_name, lambda: _compile(cfg), "EP MXFP8 requant") diff --git a/transformer_engine/common/cast/mxfp8/requantize_mxfp8_cutedsl.cuh b/transformer_engine/common/cast/mxfp8/requantize_mxfp8_cutedsl.cuh index aa7b4e63ea6..13b4af4bd2b 100644 --- a/transformer_engine/common/cast/mxfp8/requantize_mxfp8_cutedsl.cuh +++ b/transformer_engine/common/cast/mxfp8/requantize_mxfp8_cutedsl.cuh @@ -23,6 +23,7 @@ struct MXFP8RequantConfig { DType dtype; size_t rows, hidden, groups, uniform_rows; bool swizzled, rowwise_output, return_dequantized; + bool pdl = false; // run the warp-tile kernel as a programmatic dependent (EP overlap) int sm_arch = cuda::sm_arch(); int sm_count = cuda::sm_count(); @@ -31,7 +32,7 @@ struct MXFP8RequantConfig { "_" + std::to_string(hidden) + "_" + std::to_string(groups) + "_" + std::to_string(uniform_rows) + "_" + std::to_string(swizzled) + "_" + std::to_string(rowwise_output) + "_" + std::to_string(return_dequantized) + "_" + - std::to_string(sm_arch) + "_" + std::to_string(sm_count); + std::to_string(pdl) + "_" + std::to_string(sm_arch) + "_" + std::to_string(sm_count); } bool retrieve_func_from_python(const std::string &name) const { @@ -40,7 +41,7 @@ struct MXFP8RequantConfig { return (*entrypoint)(tvm::ffi::String(name), tvm::ffi::String(to_string(dtype)), static_cast(rows), static_cast(hidden), static_cast(groups), static_cast(uniform_rows), swizzled, - rowwise_output, return_dequantized, sm_count) + rowwise_output, return_dequantized, sm_count, pdl) .try_cast() .value_or(false); } @@ -72,7 +73,7 @@ struct MXFP8RequantConfig { }; inline bool mxfp8_requantize_cutedsl(const GroupedTensor &input, GroupedTensor *output, - Tensor *dequantized, cudaStream_t stream) { + Tensor *dequantized, cudaStream_t stream, bool pdl = false) { using namespace tvm_ffi_bridge; if (!TVMFFICentral::getInstance().get_cutedsl_backend_enabled() || !input.all_same_last_dim()) return false; @@ -81,14 +82,18 @@ inline bool mxfp8_requantize_cutedsl(const GroupedTensor &input, GroupedTensor * const size_t groups = input.num_tensors; const bool return_dequantized = dequantized != nullptr && dequantized->data.dptr != nullptr; // Varying first dims without BF16 output use the warp-tile kernel, which loads scales as words. - const bool warp_tile = !input.all_same_shape() && !return_dequantized; + // PDL is a warp-tile-only overlap, so pdl forces it regardless of whether the groups match. + const bool warp_tile = pdl || (!input.all_same_shape() && !return_dequantized); + if (pdl && return_dequantized) return false; if (rows == 0 || hidden == 0 || rows % 128 || hidden % 128 || (!warp_tile && hidden >= 512 && hidden % 512)) return false; // TMA's compact scale matrix requires a 16-byte row stride for wide tensors. // The narrow specializations copy full-width compact scales as 1D bulk data. - if (input.all_same_shape() && (rows % groups || (rows / groups) % 128)) return false; - if (!input.all_same_shape() && + if (!warp_tile && input.all_same_shape() && (rows % groups || (rows / groups) % 128)) + return false; + // The warp-tile kernel reads per-group boundaries from element offsets. + if (warp_tile && (input.tensor_offsets.dptr == nullptr || input.tensor_offsets.numel() < groups + 1)) { return false; } @@ -102,10 +107,11 @@ inline bool mxfp8_requantize_cutedsl(const GroupedTensor &input, GroupedTensor * warp_tile ? 0 : rows, hidden, warp_tile ? 0 : groups, - input.all_same_shape() ? rows / groups : 0, + (!warp_tile && input.all_same_shape()) ? rows / groups : 0, output->with_gemm_swizzled_scales, rowwise, - return_dequantized}; + return_dequantized, + pdl}; auto kernel = config.get_kernel(); if (!kernel) return false; @@ -117,7 +123,7 @@ inline bool mxfp8_requantize_cutedsl(const GroupedTensor &input, GroupedTensor * DType::kFloat8E8M0); DLTensorWrapper mSrc(src, false, device), mSf(sf, false, device), mDst(dst, false, device), mColSf(col_sf, false, device), mOffsets, mRowSf, mDequantized; - if (!input.all_same_shape()) { + if (warp_tile) { const SimpleTensor offsets(input.tensor_offsets.dptr, {groups + 1}, DType::kInt64); mOffsets = DLTensorWrapper(offsets, false, device); } diff --git a/transformer_engine/common/ep/ep_gemm_api.cpp b/transformer_engine/common/ep/ep_gemm_api.cpp index 7d79bce18eb..ef6e61ea7e8 100644 --- a/transformer_engine/common/ep/ep_gemm_api.cpp +++ b/transformer_engine/common/ep/ep_gemm_api.cpp @@ -19,6 +19,7 @@ #include #include +#include "../cast/mxfp8/requantize_mxfp8_cutedsl.cuh" #include "../common.h" #include "../util/cuda_runtime.h" #include "ep_backend.h" @@ -249,10 +250,11 @@ ep::EpCombineGemmConfig combine_fwd_config(const EpGemmContext& ctx, size_t rows // without a buffer, and claim_scratch uses it to resolve the pointers in GemmScratch. struct ScratchLayout { size_t row_ends; // [num_experts] int32 per-expert row ends, the grouped GEMM layout operand - size_t alpha; // [num_experts] float32 per-expert output scale, set to 1 (reused as norm_const) - size_t ones; // [rows] float32 of 1, the probability operand when the GEMM is unweighted - size_t wgrad; // backward weight-gradient accumulation workspace, empty when no weight gradient - size_t total; // end offset: the bytes the caller must provide + size_t alpha; // [num_experts] float32 per-expert output scale, set to 1 (reused as norm_const) + size_t ones; // [rows] float32 of 1, the probability operand when the GEMM is unweighted + size_t offsets; // [num_experts + 1] int64 element offsets of the MXFP8 requant grouped tensor + size_t wgrad; // backward weight-gradient accumulation workspace, empty when no weight gradient + size_t total; // end offset: the bytes the caller must provide }; ScratchLayout scratch_layout(size_t gemm_bytes, size_t num_experts, size_t rows, bool unit_probs, @@ -261,7 +263,8 @@ ScratchLayout scratch_layout(size_t gemm_bytes, size_t num_experts, size_t rows, l.row_ends = align_up(gemm_bytes + sizeof(int32_t)); l.alpha = l.row_ends + align_up(sizeof(int32_t) * num_experts); l.ones = l.alpha + align_up(sizeof(float) * num_experts); - l.wgrad = l.ones + (unit_probs ? align_up(sizeof(float) * rows) : 0); + l.offsets = l.ones + (unit_probs ? align_up(sizeof(float) * rows) : 0); + l.wgrad = l.offsets + align_up(sizeof(int64_t) * (num_experts + 1)); l.total = l.wgrad + align_up(wgrad_bytes); return l; } @@ -274,6 +277,7 @@ struct GemmScratch { int32_t* row_ends = nullptr; // [num_experts] float* alpha = nullptr; // [num_experts] float* ones = nullptr; // [rows] + int64_t* offsets = nullptr; // [num_experts + 1] requant grouped-tensor element offsets int32_t* signal = nullptr; // [signal_capacity] readiness flags int signal_capacity = 0; int num_experts = 0; @@ -291,6 +295,7 @@ GemmScratch claim_scratch(uint8_t* base, size_t workspace_bytes, size_t gemm_byt } scratch.row_ends = reinterpret_cast(base + l.row_ends); scratch.alpha = reinterpret_cast(base + l.alpha); + scratch.offsets = reinterpret_cast(base + l.offsets); scratch.num_experts = static_cast(num_experts); scratch.reset.fill(scratch.alpha, scratch.num_experts, ep::kFillOne); if (unit_probs) { @@ -502,27 +507,36 @@ void launch_wgrad(const Wgrad& wgrad, const GemmScratch& scratch, int num_cluste } // The columnwise MXFP8 copy of t's received rows, requantized from its rowwise data and compact -// scales; columnwise scales GEMM-swizzled per expert slab. A programmatic dependent of the kernel -// before it. ready_slot_rows > 0: a tile starts once the dispatch has set the flags of its rows. +// scales into GEMM-swizzled columnwise scales per expert slab. The shared grouped MXFP8 requant +// runs as a programmatic dependent (PDL): it overlaps the producing GEMM on the SMs the reverse +// dispatch frees. The expert slabs are given by the element offsets reset_workspace scans from the +// row ends. void launch_requant(NVTETensor t, const GemmScratch& scratch, size_t rows, size_t cols, - size_t num_experts, size_t ready_slot_rows, cudaStream_t stream) { - const ep::EpRequantConfig config{rows, cols, num_experts, ready_slot_rows}; - const auto kernel = config.get_kernel(); - NVTE_CHECK(kernel.has_value(), + size_t num_experts, cudaStream_t stream) { + using namespace transformer_engine; + const NVTEBasicTensor row_data{nvte_tensor_data(t), nvte_tensor_type(t), nvte_tensor_shape(t)}; + const NVTEBasicTensor row_sf = nvte_get_tensor_param(t, kNVTERowwiseScaleInv); + const NVTEBasicTensor col_data = nvte_get_tensor_param(t, kNVTEColumnwiseData); + const NVTEBasicTensor col_sf = nvte_get_tensor_param(t, kNVTEColumnwiseScaleInv); + const std::vector shape{rows, cols}; + const std::vector scale_shape{rows * cols / 32}; + const std::vector offset_shape{num_experts + 1}; + GroupedTensorWrapper input(num_experts, shape, NVTE_MXFP8_1D_SCALING); + input.set_rowwise_data(row_data.data_ptr, static_cast(row_data.dtype), shape); + input.set_rowwise_scale_inv(row_sf.data_ptr, DType::kFloat8E8M0, scale_shape); + input.set_tensor_offsets(scratch.offsets, DType::kInt64, offset_shape); + GroupedTensorWrapper output(num_experts, shape, NVTE_MXFP8_1D_SCALING); + output.set_columnwise_data(col_data.data_ptr, static_cast(col_data.dtype), shape); + output.set_columnwise_scale_inv(col_sf.data_ptr, DType::kFloat8E8M0, scale_shape); + output.set_tensor_offsets(scratch.offsets, DType::kInt64, offset_shape); + output.set_with_gemm_swizzled_scales(true); + GroupedTensor* const in = convertNVTEGroupedTensorCheck(input.data()); + GroupedTensor* const out = convertNVTEGroupedTensorCheck(output.data()); + const bool ok = + cutedsl_backend::mxfp8_requantize_cutedsl(*in, out, nullptr, stream, /*pdl=*/true); + NVTE_CHECK(ok, "the EP MXFP8 requant is not available: needs NVTE_ENABLE_CUTEDSL_BACKEND=1, " "NVTE_MOE_OVERLAP and SM 10.0, 10.3 or 10.7"); - auto codes = wrap_rowwise(t, true); - auto row_scales = wrap_scales(t, false, rows, cols); - auto col_codes = wrap_columnwise(t, true); - auto col_scales = wrap_scales(t, true, rows, cols); - auto row_ends = wrap_raw(scratch.row_ends, kNVTEInt32, num_experts); - if (ready_slot_rows > 0) { - auto signal = wrap_raw(scratch.signal, kNVTEInt32, rows / ready_slot_rows); - (*kernel)(&codes, &row_scales, &col_codes, &col_scales, &row_ends, &signal, - static_cast(stream)); - return; - } - (*kernel)(&codes, &row_scales, &col_codes, &col_scales, &row_ends, static_cast(stream)); } // Bytes of the chained weight-gradient workspace of a backward GEMM over num_experts slabs of @@ -888,6 +902,10 @@ void nvte_ep_combine_gemm_bwd(NVTETensor handle_mem, const NVTETensor grad_resul scratch.reset.fill(nvte_tensor_data(grad_recv_topk_weights), static_cast(rows), ep::kFillZero); set_row_ends(scratch, recv_tokens_per_expert); + if (requant) { + scratch.reset.offsets = scratch.offsets; + scratch.reset.offsets_cols = static_cast(hidden); + } ep::reset_workspace(scratch.reset, stream); if (wgrad && needs_descriptors(*wgrad)) { launch_wgrad(*wgrad, scratch, 1, false, 0, stream, true); @@ -924,11 +942,10 @@ void nvte_ep_combine_gemm_bwd(NVTETensor handle_mem, const NVTETensor grad_resul auto norm_const = wrap_raw(scratch.alpha, kNVTEFloat32, 1); gemm(&a, &b, &sfb, &sfa, &c, &d, &d_col, &sfd_row, &sfd_col, &h, &sfh_col, &dprob, &row_ends, &alpha, &prob, &norm_const, &ws, static_cast(stream)); - // The columnwise grad_expert_out, a dependent of the GEMM, which starts it at entry: each - // tile waits for the reverse dispatch's flags of its rows. + // The columnwise grad_expert_out, a dependent of the GEMM. It runs on the SMs the reverse + // dispatch frees, so its rows are already delivered and it needs no per-tile readiness signal. if (requant) { - launch_requant(grad_expert_out, scratch, rows, hidden, num_experts, ctx.ready_slot_rows(), - stream); + launch_requant(grad_expert_out, scratch, rows, hidden, num_experts, stream); } // Its tail on the SMs the reverse dispatch frees takes the tiles the GEMM has not claimed. const int tail_clusters = ctx.all_clusters - ctx.num_clusters; @@ -1027,13 +1044,17 @@ void nvte_ep_dispatch_gemm_bwd(NVTETensor handle_mem, const NVTETensor grad_gemm scratch.reset.fill(scratch.wgrad + wgrad->layout.counter, 1, ep::kFillZero); } set_row_ends(scratch, recv_tokens_per_expert); + if (requant) { + scratch.reset.offsets = scratch.offsets; + scratch.reset.offsets_cols = static_cast(hidden); + } ep::reset_workspace(scratch.reset, stream); if (wgrad && needs_descriptors(*wgrad)) { launch_wgrad(*wgrad, scratch, 1, false, 0, stream, true); } // The columnwise wgrad_input, before the GEMM. if (requant) { - launch_requant(wgrad_input, scratch, rows, hidden, num_experts, 0, stream); + launch_requant(wgrad_input, scratch, rows, hidden, num_experts, stream); } // The GEMM fills the flags; the dispatch backward is its programmatic dependent. diff --git a/transformer_engine/common/ep/ep_gemm_config.h b/transformer_engine/common/ep/ep_gemm_config.h index 8d182e5c529..814d145addf 100644 --- a/transformer_engine/common/ep/ep_gemm_config.h +++ b/transformer_engine/common/ep/ep_gemm_config.h @@ -287,32 +287,6 @@ struct EpWgradConfig { } }; -// Rowwise to columnwise MXFP8 requant of received rows for a weight gradient: one CTA per tile of -// the receive capacity. -struct EpRequantConfig { - static constexpr const char *kEntrypointName = "get_ep_requant_function"; - - size_t rows; // receive capacity - size_t cols; - size_t num_experts; - size_t ready_slot_rows; // wait for the dispatch flags of a tile's rows, this many each; 0: none - - // In the parameter order of the get_ep_* function of CuTeDSL/ep_gemm/requantize.py. - auto args() const { - return std::make_tuple(static_cast(rows), static_cast(cols), - static_cast(num_experts), - static_cast(ready_slot_rows)); - } - - std::string to_key() const { return config_key("ep_requant", args()); } - - bool retrieve_func_from_python(const std::string &fn_name) const { - return retrieve_from_python(*this, fn_name); - } - - std::optional get_kernel() const { return get_cached_kernel(*this); } -}; - } // namespace ep } // namespace transformer_engine diff --git a/transformer_engine/common/ep/ep_overlap_workspace.cu b/transformer_engine/common/ep/ep_overlap_workspace.cu index 02f38f3f249..4d78c6b662a 100644 --- a/transformer_engine/common/ep/ep_overlap_workspace.cu +++ b/transformer_engine/common/ep/ep_overlap_workspace.cu @@ -33,6 +33,9 @@ __global__ void reset_workspace_kernel(WorkspaceReset reset) { return; } // Inclusive prefix sum, kThreads experts per step. + if (reset.offsets != nullptr && tid == 0) { + reset.offsets[0] = 0; + } using BlockScan = cub::BlockScan; __shared__ typename BlockScan::TempStorage scan_storage; int32_t running = 0; @@ -44,6 +47,9 @@ __global__ void reset_workspace_kernel(WorkspaceReset reset) { BlockScan(scan_storage).InclusiveSum(count, row_end, step_total); if (e < reset.num_experts) { reset.row_ends[e] = running + row_end; + if (reset.offsets != nullptr) { + reset.offsets[e + 1] = static_cast(running + row_end) * reset.offsets_cols; + } } running += step_total; __syncthreads(); diff --git a/transformer_engine/common/ep/ep_overlap_workspace.h b/transformer_engine/common/ep/ep_overlap_workspace.h index 820cb35ef3e..c5cdd047d63 100644 --- a/transformer_engine/common/ep/ep_overlap_workspace.h +++ b/transformer_engine/common/ep/ep_overlap_workspace.h @@ -33,6 +33,10 @@ struct WorkspaceReset { const int32_t* counts = nullptr; // [num_experts] padded counts; null: no row ends int32_t* row_ends = nullptr; // [num_experts] row ends int num_experts = 0; + // Optional [num_experts + 1] element offsets of the requant grouped tensor: [0, row_ends * cols]. + // Written alongside the row ends when offsets is non-null. + int64_t* offsets = nullptr; + int64_t offsets_cols = 0; // Fill count words from words with value (a kFill* pattern); a zero count adds nothing. void fill(void* words, int count, int32_t value); From 0e36fa6d7c6d712b1682f057be990c5836f4a5b1 Mon Sep 17 00:00:00 2001 From: Phuong Nguyen Date: Mon, 30 Nov 2026 20:19:26 -0800 Subject: [PATCH 07/67] Add an activation-type parameter to the EP GEMM calls and move their requirements into the call docstrings Signed-off-by: Phuong Nguyen --- transformer_engine/common/ep/ep_backend.h | 3 +- transformer_engine/common/ep/ep_gemm_api.cpp | 27 ++-- .../include/transformer_engine/ep_gemm.h | 151 ++++++++++++------ .../pytorch/csrc/extensions/ep.cpp | 4 +- 4 files changed, 118 insertions(+), 67 deletions(-) diff --git a/transformer_engine/common/ep/ep_backend.h b/transformer_engine/common/ep/ep_backend.h index 2991a7df1ee..dce53315ddb 100644 --- a/transformer_engine/common/ep/ep_backend.h +++ b/transformer_engine/common/ep/ep_backend.h @@ -29,8 +29,7 @@ namespace ep { /*! \brief Readiness flags of an overlapped op: 1D int32, one flag per `granularity` units of the * signaled tensor (rows of recv_tokens for a dispatch, hidden columns for a combine). */ struct EpSignal { - // int32 readiness signal, one entry per granularity units; reset to -1, set to the slot index i - // when that unit is ready (consumer waits for signal[s] == s). + // Reset to -1; slot s is set to s once its unit is ready (consumer waits for ready[s] == s). NVTETensor ready; size_t granularity; }; diff --git a/transformer_engine/common/ep/ep_gemm_api.cpp b/transformer_engine/common/ep/ep_gemm_api.cpp index ef6e61ea7e8..6c71164482e 100644 --- a/transformer_engine/common/ep/ep_gemm_api.cpp +++ b/transformer_engine/common/ep/ep_gemm_api.cpp @@ -639,9 +639,12 @@ void nvte_ep_dispatch_gemm_fwd(NVTETensor handle_mem, const NVTETensor topk_idx, NVTETensor gemm_out, NVTETensor act_out, NVTETensor recv_tokens_per_expert, NVTETensor expert_token_offsets, NVTETensor total_recv_tokens, NVTETensor workspace, - const NVTEEpLayerConfig* layer_cfg, cudaStream_t stream) { + NVTE_Activation_Type activation, const NVTEEpLayerConfig* layer_cfg, + cudaStream_t stream) { NVTE_API_CALL(nvte_ep_dispatch_gemm_fwd); using namespace transformer_engine; + NVTE_CHECK(activation == NVTE_Activation_Type::SWIGLU, + "nvte_ep_dispatch_gemm_fwd supports only the SwiGLU activation"); const EpGemmContext ctx = make_context(layer_cfg, &NVTEEpGroupConfig::dispatch_fwd_num_sms); checkCuDriverContext(stream); const auto [ws_base, ws_bytes] = workspace_span(workspace); @@ -834,17 +837,17 @@ void nvte_ep_combine_gemm_fwd(NVTETensor handle_mem, const NVTETensor gemm_in, stream); } -void nvte_ep_combine_gemm_bwd(NVTETensor handle_mem, const NVTETensor grad_result, - NVTECommWindow grad_result_win, const NVTETensor gemm_out, - const NVTETensor recv_topk_weights, - const NVTETensor recv_tokens_per_expert, const NVTETensor weight, - const NVTETensor wgrad_input, NVTETensor grad_expert_out, - NVTETensor grad_gemm_out, NVTETensor grad_recv_topk_weights, - NVTETensor act_out, NVTETensor weight_grad, - int accumulate_weight_grad, NVTETensor workspace, - const NVTEEpLayerConfig* layer_cfg, cudaStream_t stream) { +void nvte_ep_combine_gemm_bwd( + NVTETensor handle_mem, const NVTETensor grad_result, NVTECommWindow grad_result_win, + const NVTETensor gemm_out, const NVTETensor recv_topk_weights, + const NVTETensor recv_tokens_per_expert, const NVTETensor weight, const NVTETensor wgrad_input, + NVTETensor grad_expert_out, NVTETensor grad_gemm_out, NVTETensor grad_recv_topk_weights, + NVTETensor act_out, NVTETensor weight_grad, int accumulate_weight_grad, NVTETensor workspace, + NVTE_Activation_Type activation, const NVTEEpLayerConfig* layer_cfg, cudaStream_t stream) { NVTE_API_CALL(nvte_ep_combine_gemm_bwd); using namespace transformer_engine; + NVTE_CHECK(activation == NVTE_Activation_Type::SWIGLU, + "nvte_ep_combine_gemm_bwd supports only the SwiGLU activation"); const EpGemmContext ctx = make_context(layer_cfg, &NVTEEpGroupConfig::dispatch_bwd_num_sms); checkCuDriverContext(stream); const auto [ws_base, ws_bytes] = workspace_span(workspace); @@ -1113,7 +1116,7 @@ size_t nvte_ep_overlap_workspace_size(size_t, size_t, size_t, size_t, int, int, void nvte_ep_dispatch_gemm_fwd(NVTETensor, NVTETensor, NVTETensor, NVTECommWindow, NVTETensor, NVTETensor, NVTETensor, NVTETensor, NVTETensor, NVTETensor, - NVTETensor, NVTETensor, NVTETensor, NVTETensor, + NVTETensor, NVTETensor, NVTETensor, NVTETensor, NVTE_Activation_Type, const NVTEEpLayerConfig*, cudaStream_t) { ep_gemm_not_built(); } @@ -1127,7 +1130,7 @@ void nvte_ep_combine_gemm_fwd(NVTETensor, NVTETensor, NVTETensor, NVTETensor, NV void nvte_ep_combine_gemm_bwd(NVTETensor, NVTETensor, NVTECommWindow, NVTETensor, NVTETensor, NVTETensor, NVTETensor, NVTETensor, NVTETensor, NVTETensor, NVTETensor, NVTETensor, NVTETensor, int, NVTETensor, - const NVTEEpLayerConfig*, cudaStream_t) { + NVTE_Activation_Type, const NVTEEpLayerConfig*, cudaStream_t) { ep_gemm_not_built(); } diff --git a/transformer_engine/common/include/transformer_engine/ep_gemm.h b/transformer_engine/common/include/transformer_engine/ep_gemm.h index 8f1477a0fb7..885fe815a1b 100644 --- a/transformer_engine/common/include/transformer_engine/ep_gemm.h +++ b/transformer_engine/common/include/transformer_engine/ep_gemm.h @@ -7,44 +7,27 @@ /*! \file ep_gemm.h * \brief Expert-parallel grouped GEMMs overlapped with the NCCL EP dispatch and combine. * - * Each call overlaps the grouped GEMMs of one expert-MLP stage with an NCCL EP call: the EP call - * signals its progress in chunks and the GEMM follows chunk by chunk. The backward calls also - * run the stage's weight-gradient GEMM, weight_grad[e] = grad^T wgrad_input over the rows of - * expert e, beside the EP call when weight_grad is given (null skips it). + * Each call overlaps an expert-MLP stage's grouped GEMMs with an NCCL EP transfer on disjoint SMs; + * the backward calls also run the stage's weight gradient (weight_grad[e] = grad^T wgrad_input, + * null skips it). T = tokens this rank dispatches; row-sized tensors have recv_capacity rows. * * entry GEMMs EP call SMs of the EP call * nvte_ep_dispatch_gemm_fwd FC1 + SwiGLU dispatch dispatch_fwd_num_sms - * [dispatch on its SMs] || [FC1 + SwiGLU on the rest, tile by tile as rows arrive] * nvte_ep_combine_gemm_fwd FC2 combine combine_fwd_num_sms - * [FC2 on the rest, chunk by chunk] || [combine on its SMs] * nvte_ep_combine_gemm_bwd FC2 dgrad + SwiGLU bwd, wgrad dispatch bwd dispatch_bwd_num_sms - * [FC2 dgrad + SwiGLU bwd (+ wgrad) on the rest] || [dispatch bwd on its SMs] * nvte_ep_dispatch_gemm_bwd FC1 dgrad, wgrad combine bwd combine_bwd_num_sms - * [FC1 dgrad (+ wgrad) on the rest] || [combine bwd on its SMs] - * - * The SM counts are NVTEEpGroupConfig fields. A GEMM runs on the SMs its EP call leaves and, in - * its tail, on the SMs the EP call frees as it ends. A combine readiness flag spans - * 1024 hidden columns when that divides hidden_dim, else the whole row. - * - * Each call takes a caller-owned uint8 workspace of nvte_ep_overlap_workspace_size bytes for its - * readiness flags and GEMM state; it is read only during the call, so the caller may allocate it - * per call or reuse one buffer across the calls of a group. - * - * Requirements: SM 10.0, 10.3 or 10.7, EP within one NVLink domain, num_comm_sms > 0, zero_copy - * off, dispatch_output_per_expert_alignment 256, 128 (not MXFP8 on SM 10.7) or (bfloat16 only) - * 64, and NVTE_ENABLE_CUTEDSL_BACKEND=1 with NVTE_MOE_OVERLAP. MXFP8 needs hidden_dim a multiple - * of 512 and ffn_dim a multiple of 256. The first call per shape compiles the GEMM: make it at - * warmup, outside CUDA graph capture. Issue the calls of one EP group on one stream, in the same - * order on every rank. A call throws when a requirement does not hold. - * - * A symm-mem window (tokens_win, grad_result_win) lets peers read the input in place. Either every - * rank passes a window, at the same data and scale offsets, or none does. The input must not be - * written until the call's dispatch completes, and then only from a launch with no programmatic - * dependency on the stream. - * - * Row-sized tensors have recv_capacity rows, a multiple of the alignment. Under MXFP8: tokens and - * received rows carry compact rowwise scales; weights and GEMM inputs carry GEMM-swizzled scales; - * the backward reads the weights and wgrad operands columnwise. + * + * Overlap (each call draws its own schedule): + * - Dispatch side: the dispatch leads, signaling each row tile; the GEMM consumes tiles beside + * it, then tails onto the SMs it frees. + * - Combine side: the GEMM leads. The forward combine follows the GEMM's hidden-column chunks + * and takes the SMs it frees; the backward combine is unsignaled and overlaps only the weight + * gradient. + * - Backward C names overlap the opposite transfer (see the EP call column). + * + * SM budgets: NVTEEpGroupConfig *_num_sms fields (ep.h), set at nvte_ep_initialize, not layer_cfg. + * Workspace: caller-owned uint8, nvte_ep_overlap_workspace_size bytes. Each call resets it before + * use, so one buffer can be reused across the group's calls. */ #ifndef TRANSFORMER_ENGINE_EP_GEMM_H_ @@ -52,6 +35,7 @@ #include #include +#include #include #include @@ -66,6 +50,19 @@ extern "C" { * gemm_out. MXFP8 tokens: tokens, recv_tokens, weight and act_out are MXFP8 and act_out is * silu(gate) * up, the routing weights left to nvte_ep_combine_gemm_fwd. * + * Schedule (dispatch leads, row tiles; dispatch_fwd_num_sms; time --->): + * dispatch |--- deliver tiles ---| + * FC1+SwiGLU |--- head ------------|--- tail ---| + * + * Requirements: + * - SM 10.0, 10.3 or 10.7; EP within one NVLink domain; num_comm_sms > 0; zero_copy off. + * - dispatch_output_per_expert_alignment: bfloat16 is 64, 128 or 256; MXFP8 is 256, or 128 + * except on SM 10.7. + * - NVTE_ENABLE_CUTEDSL_BACKEND=1 and NVTE_MOE_OVERLAP set. + * - MXFP8: hidden_dim a multiple of 512, ffn_dim a multiple of 256. + * - First call per shape compiles its GEMM: run it at warmup, outside CUDA graph capture. + * - A group's calls on one stream, same order on every rank. A call throws otherwise. + * * \param[in,out] handle_mem uint8 routing-state buffer. * \param[in] topk_idx [T, top_k] int32 or int64 routing indices. * \param[in] tokens [T, hidden_dim] input tokens. @@ -79,9 +76,9 @@ extern "C" { * \param[out] gemm_out [recv_capacity, 2 * ffn_dim] GEMM output. * \param[out] act_out [recv_capacity, ffn_dim] SwiGLU output. * \param[in,out] recv_tokens_per_expert [num_local_experts] int32 padded counts. Eager mode - * provides them to build the expert layout. Capacity mode - * writes them: the dispatch without drops and with at most - * 2048 local experts, otherwise the routing prepare. + * provides them to build the expert layout; capacity mode + * writes them, from the dispatch when there are no drops and + * at most 2048 local experts, else from the routing prepare. * \param[out] expert_token_offsets [num_local_experts + 1] int32 expert layout in tokens * (rows): expert 0's start (0), then each expert's padded * row end, the GEMM operand. expert_token_offsets[1:] must @@ -94,6 +91,8 @@ extern "C" { * expert_token_offsets, where expert_token_offsets[-1] is * the padded total of the kept rows. * \param[in,out] workspace uint8 scratch, nvte_ep_overlap_workspace_size bytes. + * \param[in] activation Activation between the grouped GEMMs; only + * NVTE_Activation_Type::SWIGLU is supported. * \param[in] layer_cfg Per-layer EP configuration. * \param[in] stream CUDA stream. */ @@ -104,7 +103,8 @@ void nvte_ep_dispatch_gemm_fwd(NVTETensor handle_mem, const NVTETensor topk_idx, NVTETensor gemm_out, NVTETensor act_out, NVTETensor recv_tokens_per_expert, NVTETensor expert_token_offsets, NVTETensor total_recv_tokens, NVTETensor workspace, - const NVTEEpLayerConfig* layer_cfg, cudaStream_t stream); + NVTE_Activation_Type activation, const NVTEEpLayerConfig* layer_cfg, + cudaStream_t stream); /*! \brief Second grouped GEMM overlapped with the combine. * @@ -113,6 +113,19 @@ void nvte_ep_dispatch_gemm_fwd(NVTETensor handle_mem, const NVTETensor topk_idx, * activation, so recv_topk_weights is null here; MXFP8 leaves them off the activation and applies * them to this FC2 output. * + * Schedule (FC2 leads, hidden chunks; combine_fwd_num_sms; time --->): + * FC2 |--- head ---------------| + * combine |--- push chunks -----------------------------| + * + * Requirements: + * - SM 10.0, 10.3 or 10.7; EP within one NVLink domain; num_comm_sms > 0; zero_copy off. + * - dispatch_output_per_expert_alignment: bfloat16 is 64, 128 or 256; MXFP8 is 256, or 128 + * except on SM 10.7. + * - NVTE_ENABLE_CUTEDSL_BACKEND=1 and NVTE_MOE_OVERLAP set. + * - MXFP8: hidden_dim a multiple of 512, ffn_dim a multiple of 256. + * - First call per shape compiles its GEMM: run it at warmup, outside CUDA graph capture. + * - A group's calls on one stream, same order on every rank. A call throws otherwise. + * * \param[in,out] handle_mem uint8 routing-state buffer. * \param[in] gemm_in [recv_capacity, ffn_dim] act_out of * nvte_ep_dispatch_gemm_fwd, bfloat16 or MXFP8. @@ -134,10 +147,10 @@ void nvte_ep_combine_gemm_fwd(NVTETensor handle_mem, const NVTETensor gemm_in, NVTETensor expert_out, NVTETensor result, NVTETensor workspace, const NVTEEpLayerConfig* layer_cfg, cudaStream_t stream); -/*! \brief Backward of nvte_ep_combine_gemm_fwd and of the SwiGLU: the combine backward - * overlapped with the second GEMM's data gradient, SwiGLU backward in its epilogue. +/*! \brief Backward of nvte_ep_combine_gemm_fwd and of the SwiGLU: the second GEMM's data gradient, + * SwiGLU backward in its epilogue, overlapped with the backward dispatch. * - * The combine backward scatters grad_result to the expert rows as grad_expert_out (dy). SwiGLU + * The backward dispatch scatters grad_result to the expert rows as grad_expert_out (dy). SwiGLU * backward over gemm_out = [gate | up] (gate and up in alternating 32-column blocks) gives * grad_gemm_out, scaled by recv_topk_weights (MXFP8) or carrying it from the activation (BF16). * Over expert e's rows, with W2 its forward weight and wgrad_input the route-weighted activation: @@ -148,6 +161,19 @@ void nvte_ep_combine_gemm_fwd(NVTETensor handle_mem, const NVTETensor gemm_in, * grad_recv_topk_weights uses the unweighted activation silu(gate) * up. weight_grad is written * only when non-null; accumulate_weight_grad adds to it instead of overwriting it. * + * Schedule (backward dispatch leads, dY tiles; dispatch_bwd_num_sms; time --->): + * bwd dispatch |--- deliver tiles ---| + * dGLU |--- head ------------|--- tail ---| + * + * Requirements: + * - SM 10.0, 10.3 or 10.7; EP within one NVLink domain; num_comm_sms > 0; zero_copy off. + * - dispatch_output_per_expert_alignment: bfloat16 is 64, 128 or 256; MXFP8 is 256, or 128 + * except on SM 10.7. + * - NVTE_ENABLE_CUTEDSL_BACKEND=1 and NVTE_MOE_OVERLAP set. + * - MXFP8: hidden_dim a multiple of 512, ffn_dim a multiple of 256. + * - First call per shape compiles its GEMM: run it at warmup, outside CUDA graph capture. + * - A group's calls on one stream, same order on every rank. A call throws otherwise. + * * \param[in,out] handle_mem uint8 routing-state buffer. * \param[in] grad_result [T, hidden_dim] gradient of result. * \param[in] grad_result_win Optional symm-mem window for grad_result (MXFP8: and, @@ -175,21 +201,44 @@ void nvte_ep_combine_gemm_fwd(NVTETensor handle_mem, const NVTETensor gemm_in, * float32 gradient of weight, or null. * \param[in] accumulate_weight_grad Add to weight_grad instead of writing it. * \param[in,out] workspace uint8 scratch, nvte_ep_overlap_workspace_size bytes. + * \param[in] activation Activation whose backward runs between the grouped GEMMs; + * only NVTE_Activation_Type::SWIGLU is supported. * \param[in] layer_cfg Per-layer EP configuration. * \param[in] stream CUDA stream. */ -void nvte_ep_combine_gemm_bwd(NVTETensor handle_mem, const NVTETensor grad_result, - NVTECommWindow grad_result_win, const NVTETensor gemm_out, - const NVTETensor recv_topk_weights, - const NVTETensor recv_tokens_per_expert, const NVTETensor weight, - const NVTETensor wgrad_input, NVTETensor grad_expert_out, - NVTETensor grad_gemm_out, NVTETensor grad_recv_topk_weights, - NVTETensor act_out, NVTETensor weight_grad, - int accumulate_weight_grad, NVTETensor workspace, - const NVTEEpLayerConfig* layer_cfg, cudaStream_t stream); +void nvte_ep_combine_gemm_bwd( + NVTETensor handle_mem, const NVTETensor grad_result, NVTECommWindow grad_result_win, + const NVTETensor gemm_out, const NVTETensor recv_topk_weights, + const NVTETensor recv_tokens_per_expert, const NVTETensor weight, const NVTETensor wgrad_input, + NVTETensor grad_expert_out, NVTETensor grad_gemm_out, NVTETensor grad_recv_topk_weights, + NVTETensor act_out, NVTETensor weight_grad, int accumulate_weight_grad, NVTETensor workspace, + NVTE_Activation_Type activation, const NVTEEpLayerConfig* layer_cfg, cudaStream_t stream); -/*! \brief Backward of nvte_ep_dispatch_gemm_fwd: the first GEMM's data gradient overlapped with - * the dispatch backward. +/*! \brief Backward of nvte_ep_dispatch_gemm_fwd: the first GEMM's data and weight gradients, the + * backward combine overlapping the weight gradient. + * + * Over expert e's rows, with W1 its forward weight and wgrad_input the received tokens: + * + * grad_recv_tokens = grad_gemm_out @ W1 [recv_capacity, hidden_dim] + * weight_grad[e] = grad_gemm_out^T @ wgrad_input [2 * ffn_dim, hidden_dim] + * + * The backward combine then returns grad_recv_tokens as grad_tokens and reduces + * grad_recv_topk_weights into grad_topk_weights. weight_grad is written only when non-null; + * accumulate_weight_grad adds to it instead of overwriting it. + * + * Schedule (FC1 dgrad, then unsignaled combine overlaps wgrad; combine_bwd_num_sms; time --->): + * FC1 dgrad |--- all SMs ---| + * combine | |--- return dX, dprob ---| + * FC1 wgrad | |--- head ---------------|--- tail ---| + * + * Requirements: + * - SM 10.0, 10.3 or 10.7; EP within one NVLink domain; num_comm_sms > 0; zero_copy off. + * - dispatch_output_per_expert_alignment: bfloat16 is 64, 128 or 256; MXFP8 is 256, or 128 + * except on SM 10.7. + * - NVTE_ENABLE_CUTEDSL_BACKEND=1 and NVTE_MOE_OVERLAP set. + * - MXFP8: hidden_dim a multiple of 512, ffn_dim a multiple of 256. + * - First call per shape compiles its GEMM: run it at warmup, outside CUDA graph capture. + * - A group's calls on one stream, same order on every rank. A call throws otherwise. * * \param[in,out] handle_mem uint8 routing-state buffer. * \param[in] grad_gemm_out [recv_capacity, 2 * ffn_dim] from @@ -229,7 +278,7 @@ void nvte_ep_dispatch_gemm_bwd(NVTETensor handle_mem, const NVTETensor grad_gemm * \param[in] hidden_dim Hidden size. * \param[in] ffn_dim Expert FFN size. * \param[in] num_local_experts Experts held by this rank. - * \param[in] recv_capacity Rows of the receive buffers (recv_capacity). + * \param[in] recv_capacity Rows of the receive buffers. * \param[in] with_weight_grad Nonzero to fit the backward weight-gradient workspace. * \param[in] mxfp8 Nonzero for MXFP8 operands instead of bfloat16. * \param[in] layer_cfg Per-layer EP configuration. diff --git a/transformer_engine/pytorch/csrc/extensions/ep.cpp b/transformer_engine/pytorch/csrc/extensions/ep.cpp index e2fc2857039..51e93b873da 100644 --- a/transformer_engine/pytorch/csrc/extensions/ep.cpp +++ b/transformer_engine/pytorch/csrc/extensions/ep.cpp @@ -984,7 +984,7 @@ std::vector ep_dispatch_gemm_fwd( recv_topk_weights_te.data(), gemm_out_te.data(), act_out_te.data(), tokens_per_expert_te.data(), expert_token_offsets_te.data(), report_total ? total_recv_tokens_te.data() : nullptr, - workspace_te.data(), &layer_cfg, stream); + workspace_te.data(), NVTE_Activation_Type::SWIGLU, &layer_cfg, stream); if (mxfp8) { return {recv_tokens, recv_topk_weights, gemm_out, act_out, expert_token_offsets, *recv_scale_inv, *act_out_scale_inv}; @@ -1140,7 +1140,7 @@ void ep_combine_gemm_bwd( recv_topk_weights_te.data(), tokens_per_expert_te.data(), weight_te.data(), wgrad.input(), grad_expert_out_te.data(), grad_gemm_out_te.data(), grad_recv_topk_weights_te.data(), mxfp8 ? act_out_te.data() : nullptr, wgrad.output(), accumulate_weight_grad, - workspace_te.data(), &layer_cfg, stream); + workspace_te.data(), NVTE_Activation_Type::SWIGLU, &layer_cfg, stream); } void ep_dispatch_gemm_bwd( From 38dba2ea245d662dbec2d1acff48f0207702e9f8 Mon Sep 17 00:00:00 2001 From: Phuong Nguyen Date: Mon, 30 Nov 2026 20:19:26 -0800 Subject: [PATCH 08/67] Load the EP CuTeDSL grouped GEMMs from the cuDNN frontend package and share the weight-gradient tile counter Signed-off-by: Phuong Nguyen --- tests/pytorch/distributed/run_test_ep.sh | 26 +- tests/pytorch/distributed/test_ep.py | 28 ++- tests/pytorch/test_ep_gemm.py | 24 +- .../common/CuTeDSL/ep_gemm/_loader.py | 205 +++++++--------- .../common/CuTeDSL/ep_gemm/combine_gemm.py | 39 +-- .../common/CuTeDSL/ep_gemm/dispatch_gemm.py | 80 +++---- .../common/CuTeDSL/ep_gemm/wgrad_gemm.py | 224 +++++------------- transformer_engine/common/ep/ep_gemm_api.cpp | 69 +++--- transformer_engine/common/ep/ep_gemm_config.h | 28 +-- .../pytorch/ops/fused/moe_overlap.py | 24 +- 10 files changed, 315 insertions(+), 432 deletions(-) diff --git a/tests/pytorch/distributed/run_test_ep.sh b/tests/pytorch/distributed/run_test_ep.sh index b8a5bc86128..9ed58792cfd 100755 --- a/tests/pytorch/distributed/run_test_ep.sh +++ b/tests/pytorch/distributed/run_test_ep.sh @@ -39,6 +39,19 @@ SCRIPT="${SCRIPT_DIR}/run_ep.py" RET=0 +# With NVTE_TEST_EP_PRINT_BUDGET set, no pass runs: the launcher prints the time its passes may take. +BUDGET_S=0 +# Seconds `timeout --kill-after` may add per pass. +KILL_AFTER_S=10 + +finish() { + if [ -n "${NVTE_TEST_EP_PRINT_BUDGET:-}" ]; then + echo "EP_TEST_BUDGET_S=${BUDGET_S}" + exit 0 + fi + exit "${RET}" +} + # Run the suite once per IO mode. Modes can't be mixed in one process # (ep_bootstrap is once-per-process), so zero-copy gets its own run; only the # zero-copy-capable tests execute there (the rest self-skip). @@ -54,11 +67,15 @@ run_pass() { # The overlap passes compile CuTeDSL GEMMs on first use and need a longer timeout. local timeout_s="${TEST_TIMEOUT_S}" if [ "${overlap}" = "1" ] && [ "${timeout_s}" -lt 600 ]; then timeout_s=600; fi + if [ -n "${NVTE_TEST_EP_PRINT_BUDGET:-}" ]; then + BUDGET_S=$((BUDGET_S + timeout_s + KILL_AFTER_S)) + return + fi echo "=== Running ${SCRIPT} [${label}] on ${NUM_RANKS} GPUs (timeout=${timeout_s}s) ===" # setsid + kill-after so SIGKILL takes down the whole process group, not just torchrun. NVTE_EP_ZERO_COPY="${zc}" NVTE_EP_EAGER="${eager}" NVTE_EP_OVERFLOW="${overflow}" \ NVTE_EP_MXFP8_PASS="${mxfp8}" NVTE_EP_FUSED_PREPARE_DISPATCH="${fused}" NVTE_EP_OVERLAP="${overlap}" \ - setsid timeout --foreground --kill-after=10 --signal=TERM "${timeout_s}" \ + setsid timeout --foreground --kill-after="${KILL_AFTER_S}" --signal=TERM "${timeout_s}" \ torchrun --standalone --nnodes=1 --nproc-per-node="${NUM_RANKS}" \ "${SCRIPT}" 2>&1 | tee "${log}" local rc=${PIPESTATUS[0]} @@ -106,7 +123,7 @@ if [ "${NVTE_TEST_EP_CLASSIC_PG:-0}" = "1" ]; then exit 1 fi TORCH_DIST_USE_NCCL2=0 run_pass "classic_pg" 0 - exit $RET + finish fi run_pass "default" 0 @@ -129,6 +146,9 @@ run_pass "fused_mxfp8" 0 0 0 1 1 # Overlapped MoE ops (ep_gemm.h, te.ops FusedMoE): alignment 256, capacity and eager IO. Run only # when the overlap is available (NVTE_ENABLE_CUTEDSL_BACKEND=1, NVTE_MOE_OVERLAP and SM 10.x). +# TODO(phuonguyen): once TE builds CuTeDSL by default and ships the cuDNN FE grouped GEMM kernels, +# set NVTE_ENABLE_CUTEDSL_BACKEND=1 and NVTE_MOE_OVERLAP here so the overlap passes run in CI +# instead of self-skipping. PROBE_ERR=$(mktemp) OVERLAP_AVAILABLE=$(python3 -c \ "import transformer_engine.pytorch.ep as ep; print(int(ep._moe_overlap_available()))" 2>"${PROBE_ERR}") @@ -164,4 +184,4 @@ else done fi -exit $RET +finish diff --git a/tests/pytorch/distributed/test_ep.py b/tests/pytorch/distributed/test_ep.py index 3978c6908cd..3e068348db8 100644 --- a/tests/pytorch/distributed/test_ep.py +++ b/tests/pytorch/distributed/test_ep.py @@ -4,6 +4,7 @@ """Pytest driver — spawns run_ep.py under torchrun and asserts the suite passed.""" import os +import re import subprocess from pathlib import Path @@ -15,14 +16,21 @@ LAUNCHER = TEST_ROOT / "run_test_ep.sh" -def _count_launcher_passes() -> int: - # Count run_pass invocations so the outer timeout scales as passes are added. - n = 0 - for line in LAUNCHER.read_text().splitlines(): - s = line.strip() - if s.startswith("run_pass ") or s.startswith("run_pass\t"): - n += 1 - return max(n, 1) +def _launcher_budget_s(per_pass_s: int) -> int: + """Seconds the launcher's passes may take in total, as the launcher reports for the passes it + selects: each pass has its own timeout, and the overlap passes need longer than ``per_pass_s``. + """ + proc = subprocess.run( + ["bash", str(LAUNCHER)], + env={**os.environ, "TEST_TIMEOUT_S": str(per_pass_s), "NVTE_TEST_EP_PRINT_BUDGET": "1"}, + capture_output=True, + text=True, + timeout=300, + check=False, + ) + match = re.search(r"^EP_TEST_BUDGET_S=(\d+)$", proc.stdout, re.MULTILINE) + # No budget means the launcher skipped itself (too few GPUs, no NVLink) and runs nothing. + return int(match.group(1)) if match else 0 @pytest.mark.skipif(torch.cuda.device_count() < 4, reason="EP requires >= 4 GPUs") @@ -30,10 +38,10 @@ def test_multi_process_ep(): """Launch the EP unit-test suite across all visible GPUs. Per-pass timeout stays short so a hang on any rank surfaces fast; the outer - pytest budget scales with the number of passes the launcher runs. + pytest budget is the sum of the per-pass timeouts the launcher selects. """ per_pass_s = int(os.environ.get("NVTE_TEST_EP_TIMEOUT_S", "180")) - outer_s = per_pass_s * _count_launcher_passes() + 60 + outer_s = _launcher_budget_s(per_pass_s) + 60 proc = subprocess.run( ["bash", str(LAUNCHER)], env={**os.environ, "KEEP_EP_LOGS": "1", "TEST_TIMEOUT_S": str(per_pass_s)}, diff --git a/tests/pytorch/test_ep_gemm.py b/tests/pytorch/test_ep_gemm.py index 5dd057c6a1d..aec7c951594 100644 --- a/tests/pytorch/test_ep_gemm.py +++ b/tests/pytorch/test_ep_gemm.py @@ -59,7 +59,7 @@ def _run_gemm(rows_per_expert, rows_alignment, mxfp8, tail_clusters, device_layo experts, num_clusters=8, scaling_mode=scaling_mode, - rows_alignment=rows_alignment, + token_alignment=rows_alignment, device_layout=device_layout, ) launches = [] @@ -138,16 +138,8 @@ def _run_gemm(rows_per_expert, rows_alignment, mxfp8, tail_clusters, device_layo [ (TILE, False, [2 * TILE, TILE, 0, 3 * TILE]), (TILE, True, [2 * TILE, TILE, 0, 3 * TILE]), - # Tail tiles: an expert of only a tail, a tail after full tiles, an empty expert. - (128, False, [128, 2 * TILE + 128, 0, TILE]), - pytest.param( - 128, - True, - [128, 2 * TILE + 128, 0, TILE], - marks=pytest.mark.skipif(not MXFP8_TAILS, reason="no MXFP8 tail tiles on SM 10.7"), - ), - # Every tail height, and the tails that run inside the last full tile of their expert. - (64, False, [64, 128, 192, 2 * TILE + 64, 2 * TILE + 128, 0, TILE]), + # TODO(phuonguyen): cuDNN FE has no tail-tile kernels yet; restore the 64/128 alignment + # cases (experts padded below a full tile) once they land. ], ) @pytest.mark.parametrize("tail_clusters", [0, 4]) @@ -226,8 +218,8 @@ def _run_combine(rows_per_expert, rows_alignment, mxfp8, backward): (False, True, TILE, [2 * TILE, TILE, 0, 3 * TILE]), (True, False, TILE, [2 * TILE, TILE, 0, 3 * TILE]), (True, True, TILE, [2 * TILE, TILE, 0, 3 * TILE]), - # Tail tiles: an expert of only a tail, a tail after full tiles, an empty expert. - (False, False, 128, [128, 2 * TILE + 128, 0, TILE]), + # TODO(phuonguyen): cuDNN FE has no tail-tile kernels yet; restore the 128 alignment case + # once they land. ], ) def test_combine_gemm_matches_reference(backward, mxfp8, rows_alignment, rows_per_expert): @@ -284,15 +276,17 @@ def _run_wgrad(rows_per_expert, mxfp8, fp32_out, accumulate): ends = torch.tensor(rows_per_expert, device=device).cumsum(0).to(torch.int32) ws_bytes = wgrad_gemm.get_ep_wgrad_workspace_layout(*args)[0] workspace = torch.zeros(ws_bytes, dtype=torch.uint8, device=device) + # Shared tile counter the launches claim from; the kernel does not reset it. + counter = torch.zeros(1, dtype=torch.int32, device=device) stream = ctypes.c_void_p(torch.cuda.current_stream().cuda_stream) for gemm in launches: if mxfp8: gemm( grad, x, _unit_e8m0(rows * m // 32, device), _unit_e8m0(rows * n // 32, device), - weight_grad, ends, workspace, stream, + weight_grad, ends, workspace, counter, stream, ) # fmt: skip else: - gemm(grad, x, weight_grad, ends, workspace, stream) + gemm(grad, x, weight_grad, ends, workspace, counter, stream) torch.cuda.synchronize() base = init if accumulate else torch.zeros_like(init) return grad.float(), x.float(), base, weight_grad.float() diff --git a/transformer_engine/common/CuTeDSL/ep_gemm/_loader.py b/transformer_engine/common/CuTeDSL/ep_gemm/_loader.py index 7ff72cd29f4..af36fef9ddc 100644 --- a/transformer_engine/common/CuTeDSL/ep_gemm/_loader.py +++ b/transformer_engine/common/CuTeDSL/ep_gemm/_loader.py @@ -2,18 +2,15 @@ # # See LICENSE for license information. -"""Loading of the EP grouped GEMMs: kernel tree, fake operands and TVM-FFI registration. +"""Loading of the EP grouped GEMMs from the cuDNN frontend package, with TVM-FFI registration. -The kernels are loaded from ``NVTE_MOE_OVERLAP`` (a ``gemm/`` tree with ``blackwell/``, -``rubin/`` and ``utils/``), compiled once per configuration and registered under a name chosen by -C++. +The kernels ship in the installed nvidia-cudnn-frontend package (``cudnn.gemm.cutedsl.grouped``), +compiled once per configuration and registered under a name chosen by C++. """ import functools import importlib import logging -import os -import sys from dataclasses import dataclass from typing import Optional @@ -23,9 +20,6 @@ logger = logging.getLogger(__name__) -# Points at an external CuTeDSL kernel tree the GEMMs are imported from. -# TODO(phuonguyen): drop this kernel-root path once the kernels are upstreamed into cuDNN. -GEMM_PATH_ENV = "NVTE_MOE_OVERLAP" MMA_TILER_MN = (256, 256) CLUSTER_MN = (2, 1) # Rows per M tile. A smaller expert alignment ends an expert in a tail tile. @@ -33,47 +27,62 @@ # Values per MXFP8 E8M0 scale. SF_VEC_SIZE = 32 +# cuDNN frontend package holding the EP grouped GEMM kernels. +# TODO(phuonguyen): gate on a cuDNN FE minimum version once the kernels ship versioned. +_PKG = "cudnn.gemm.cutedsl.grouped" + +# Dotted path within _PKG for each module name the kernels load. +_MODULE_PATHS = { + "moe_utils": "moe_utils", + "moe_kernel_helpers": "moe_kernel_helpers", + "moe_streaming_output_chunk_tile_scheduler": "moe_streaming_output_chunk_tile_scheduler", + # MXFP8 kernels (the BF16 path does not load these). + "moe_blockscaled_grouped_gemm_quant_sm100": "quant.grouped_gemm_quant", + "moe_blockscaled_grouped_gemm_quant_rubin": "quant.moe_blockscaled_grouped_gemm_quant_rubin", + "moe_blockscaled_grouped_gemm_glu_rubin": "glu.moe_blockscaled_grouped_gemm_glu_rubin", + "moe_blockscaled_grouped_gemm_glu_bias": "glu.moe_blockscaled_grouped_gemm_glu_bias", + "moe_blockscaled_grouped_gemm_dglu_dbias": "dglu.moe_blockscaled_grouped_gemm_dglu_dbias", + "moe_blockscaled_grouped_gemm_dglu_rubin": "dglu.moe_blockscaled_grouped_gemm_dglu_rubin", + "moe_blockscaled_grouped_gemm_wgrad": "wgrad.moe_blockscaled_grouped_gemm_wgrad", + "moe_blockscaled_grouped_gemm_wgrad_rubin": "wgrad.moe_blockscaled_grouped_gemm_wgrad_rubin", + "moe_grouped_gemm_wgrad": "wgrad.moe_grouped_gemm_wgrad", +} + @dataclass(frozen=True) class GemmArch: - """The kernels of one architecture: their subdirectories of the GEMM path, searched in order, - and the BF16 kernels as ``module.Class``.""" + """BF16 grouped GEMM kernels of one architecture as ``module.Class`` paths under ``_PKG``.""" - subdirs: tuple dispatch_fwd: str # FC1 + SwiGLU dispatch_bwd: str # FC2 data gradient + SwiGLU backward combine: str # FC2, FC1 data gradient - mxfp8_tail_tiles: bool # MXFP8 kernels for experts padded to fewer rows than a tile - mxfp8_modules: tuple # modules of the MXFP8 kernels + # MXFP8 kernel module names, loaded on demand by the MXFP8 paths. + mxfp8_modules: tuple _SM100 = GemmArch( - subdirs=("blackwell",), - dispatch_fwd="moe_grouped_gemm_glu_sm100.MoEGroupedGemmGluBiasBf16Kernel", - dispatch_bwd="moe_grouped_gemm_dglu_dbias.MoEGroupedGemmDgluDbiasBf16Kernel", - combine="moe_grouped_gemm_sm100.MoEGroupedGemmBf16Kernel", - mxfp8_tail_tiles=True, + dispatch_fwd="glu.moe_grouped_gemm_glu_bias.MoEGroupedGemmGluBiasBf16Kernel", + dispatch_bwd="dglu.moe_grouped_gemm_dglu_dbias.MoEGroupedGemmDgluDbiasBf16Kernel", + combine="unfused.moe_grouped_gemm.MoEGroupedGemmBf16Kernel", mxfp8_modules=( "moe_blockscaled_grouped_gemm_quant_sm100", + "moe_blockscaled_grouped_gemm_glu_bias", "moe_blockscaled_grouped_gemm_dglu_dbias", "moe_blockscaled_grouped_gemm_wgrad", - "moe_blockscaled_grouped_gemm_wgrad_dense", - "moe_blockscaled_grouped_gemm_wgrad_reuse", ), ) -# The SM 10.7 kernels build on the SM 10.0 ones. +# SM 10.7 (Rubin) has no BF16 kernels in cuDNN FE yet, so the BF16 roles reuse the SM 10.0 ones. +# TODO(phuonguyen): point these at real Rubin BF16 kernels when cuDNN FE adds them; validate on +# Rubin hardware. _SM107 = GemmArch( - subdirs=("rubin", "blackwell"), - dispatch_fwd="moe_grouped_gemm_glu_sm107.MoEGroupedGemmGluBiasBf16Kernel", - dispatch_bwd="moe_grouped_gemm_sm107.MoEGroupedGemmDgluDbiasBf16Kernel", - combine="moe_grouped_gemm_sm107.MoEGroupedGemmBf16Kernel", - mxfp8_tail_tiles=False, + dispatch_fwd=_SM100.dispatch_fwd, + dispatch_bwd=_SM100.dispatch_bwd, + combine=_SM100.combine, mxfp8_modules=( "moe_blockscaled_grouped_gemm_quant_rubin", - "moe_blockscaled_grouped_gemm_dglu_rubin", "moe_blockscaled_grouped_gemm_glu_rubin", + "moe_blockscaled_grouped_gemm_dglu_rubin", "moe_blockscaled_grouped_gemm_wgrad_rubin", - "moe_blockscaled_grouped_gemm_wgrad_reuse_rubin", ), ) # Kernels by compute capability; other architectures run the unfused ops. @@ -87,24 +96,36 @@ def gemm_arch(): def is_sm107(): """Whether the current device runs the SM 10.7 kernels.""" - return gemm_arch() is _SM107 + return device_compute_capability() == (10, 7) -_LOADED_ROOT: list = [] +def import_gemm_modules(*names): + """Import the named modules of the kernel package (and ``moe_utils`` last).""" + out = [] + for name in (*names, "moe_utils"): + out.append(importlib.import_module(f"{_PKG}.{_MODULE_PATHS.get(name, name)}")) + return tuple(out) + -# What TE reads from the kernel tree, module by module (dotted names are nested attributes). +def import_bf16_kernel(role): + """The current device's BF16 kernel class of ``role`` (a ``GemmArch`` field) and + ``moe_utils``.""" + module_name, class_name = getattr(gemm_arch(), role).rsplit(".", 1) + module = importlib.import_module(f"{_PKG}.{module_name}") + return getattr(module, class_name), importlib.import_module(f"{_PKG}.moe_utils") + + +# What TE reads from the kernel package, module by module (dotted names are nested attributes). _SHARED_INTERFACE = { - "moe_utils": ("MoEWeightMode.DENSE", "WGradInputOrder.Tensor2D", "WgradTileClaim.COUNTER"), - "moe_tail_tiles": ("FUSED_TAIL_MAX_ROWS",), - "moe_signal_helpers": ("signal_workspace_offsets",), + "moe_utils": ("MoEWeightMode.DENSE", "WGradInputOrder.Tensor2D"), + "moe_kernel_helpers": ("streaming_signal_workspace_offsets",), "moe_streaming_output_chunk_tile_scheduler": ( - "OutputNotifyConfig", - "OutputNotifyMode.N_CHUNK", - "output_notify_capacity", - "output_notify_offsets", + "StreamingOutputNotifyConfig", + "StreamingOutputNotifyMode.N_CHUNK", + "streaming_output_notify_capacity", + "streaming_output_notify_offsets", ), } -_WGRAD_CLASSES = ("MoEGroupedGemmWgradBF16Kernel", "MoEGroupedGemmWgradWideBF16Kernel") def _missing(obj, dotted_names): @@ -120,8 +141,8 @@ def _missing(obj, dotted_names): @functools.lru_cache(maxsize=None) -def _gemm_interface_reason(root, capability, mxfp8): - del root, capability # The cache key: the tree and the architecture the checks ran on. +def _gemm_interface_reason(capability, mxfp8): + del capability # The cache key: the architecture the checks ran on. problems = [] try: for name, attributes in _SHARED_INTERFACE.items(): @@ -130,70 +151,27 @@ def _gemm_interface_reason(root, capability, mxfp8): problems.append(f"{name} lacks {', '.join(missing)}") arch = gemm_arch() for role in ("dispatch_fwd", "dispatch_bwd", "combine"): - module_name, class_name = getattr(arch, role).split(".") - kernel = getattr(import_gemm_modules(module_name)[0], class_name, None) - if kernel is None: + module_name, class_name = getattr(arch, role).rsplit(".", 1) + module = importlib.import_module(f"{_PKG}.{module_name}") + if getattr(module, class_name, None) is None: problems.append(f"{module_name} lacks {class_name}") - elif role == "dispatch_fwd" and not hasattr(kernel, "FC1_TAIL_AT_SLOTS_READY"): - problems.append(f"{class_name} lacks FC1_TAIL_AT_SLOTS_READY") if mxfp8: for module_name in arch.mxfp8_modules: import_gemm_modules(module_name) - names = ( - ("moe_grouped_gemm_sm107",) * 2 - if is_sm107() - else ("moe_grouped_gemm_wgrad", "moe_grouped_gemm_wgrad_wide") - ) - for module_name, class_name in zip(names, _WGRAD_CLASSES): - if getattr(import_gemm_modules(module_name)[0], class_name, None) is None: - problems.append(f"{module_name} lacks {class_name}") except ImportError as e: problems.append(f"cannot import {e.name or e}") if problems: - return "the EP grouped GEMM kernel tree does not match Transformer Engine: " + "; ".join( - problems + return ( + "the cuDNN frontend grouped GEMM kernels do not match Transformer Engine: " + + "; ".join(problems) ) return None -# TODO(phuonguyen): check the kernel tree's version (cudnn-frontend release or EPCompOverlap -# commit) against a minimum once the kernels ship in a versioned package; for now the tree is -# only checked for the names TE reads. def gemm_interface_reason(mxfp8=False) -> Optional[str]: - """Why the kernel tree at ``NVTE_MOE_OVERLAP`` lacks what the EP grouped GEMMs read, or None; - ``mxfp8`` also checks the MXFP8 kernels. Checked once per tree, architecture and recipe; the - tree's version is not otherwise identified.""" - return _gemm_interface_reason(os.environ.get(GEMM_PATH_ENV), device_compute_capability(), mxfp8) - - -def import_gemm_modules(*names): - """Import the named modules of the kernel tree (and ``moe_utils`` last) from the GEMM path.""" - root = os.environ.get(GEMM_PATH_ENV) - if not root: - raise ModuleNotFoundError( - f"{GEMM_PATH_ENV} is not set: the EP grouped GEMMs are not available" - ) - if _LOADED_ROOT and _LOADED_ROOT[0] != root: - # The modules are imported by name, so those of the first tree stay in sys.modules. - raise RuntimeError( - f"{GEMM_PATH_ENV} changed from {_LOADED_ROOT[0]} to {root} after the EP grouped GEMMs" - " were loaded; restart the process to use the other kernel tree." - ) - _LOADED_ROOT[:] = [root] - for sub in reversed(("", *gemm_arch().subdirs, "utils")): - path = os.path.join(root, sub) if sub else root - if path not in sys.path: - sys.path.insert(0, path) - importlib.invalidate_caches() - return tuple(importlib.import_module(name) for name in (*names, "moe_utils")) - - -def import_bf16_kernel(role): - """The current device's BF16 kernel class of ``role`` (a ``GemmArch`` field) and - ``moe_utils``.""" - module_name, class_name = getattr(gemm_arch(), role).split(".") - module, moe_utils = import_gemm_modules(module_name) - return getattr(module, class_name), moe_utils + """Why the installed cuDNN frontend lacks what the EP grouped GEMMs read, or None; ``mxfp8`` + also checks the MXFP8 kernels. Checked once per architecture and recipe.""" + return _gemm_interface_reason(device_compute_capability(), mxfp8) def unsupported_device_reason(what): @@ -205,19 +183,6 @@ def unsupported_device_reason(what): return f"The {what} needs SM {supported}, got SM {major}.{minor}." -def device_smem_optin(): - """Opt-in shared memory per block of the current CUDA device, in bytes.""" - from cuda.bindings import runtime as cudart # pylint: disable=import-outside-toplevel - - err, device = cudart.cudaGetDevice() - assert err == cudart.cudaError_t.cudaSuccess, err - err, smem = cudart.cudaDeviceGetAttribute( - cudart.cudaDeviceAttr.cudaDevAttrMaxSharedMemoryPerBlockOptin, device - ) - assert err == cudart.cudaError_t.cudaSuccess, err - return smem - - def fake_tensor(dtype, shape, order, align): """A compact fake gmem tensor to compile against.""" from cutlass import cute # pylint: disable=import-outside-toplevel @@ -290,26 +255,18 @@ def blockscaled_kwargs(num_experts): } -def tail_tile_kwargs(rows_alignment, fused=False): - """Constructor arguments for experts padded to ``rows_alignment`` rows; ``fused`` runs the - smallest tails inside their expert's last full tile (BF16 forward GEMMs).""" - if rows_alignment >= ROWS_PER_TILE: - return {} - kwargs = {"tail_rows_alignment": rows_alignment} - if fused: - tail_tiles = import_gemm_modules("moe_tail_tiles")[0] - kwargs["fused_tail_max_rows"] = tail_tiles.FUSED_TAIL_MAX_ROWS - return kwargs +def tail_tile_kwargs(token_alignment, fused=False): + """Constructor arguments for experts padded to ``token_alignment`` rows.""" + del token_alignment, fused + # TODO(phuonguyen): cuDNN FE has no sub-tile (tail) kernels, so experts pad to a full row tile + # and no tail arguments are passed. Restore the tail arguments once tail-tiles land. + return {} -def mxfp8_tail_tile_kwargs(rows_alignment): +def mxfp8_tail_tile_kwargs(token_alignment): """``tail_tile_kwargs`` of the MXFP8 kernels.""" - if gemm_arch().mxfp8_tail_tiles: - return tail_tile_kwargs(rows_alignment) - if rows_alignment < ROWS_PER_TILE: - raise ValueError( - f"The MXFP8 kernels of this device need experts padded to {ROWS_PER_TILE} rows." - ) + del token_alignment + # TODO(phuonguyen): see tail_tile_kwargs; cuDNN FE has no MXFP8 tail kernels yet. return {} diff --git a/transformer_engine/common/CuTeDSL/ep_gemm/combine_gemm.py b/transformer_engine/common/CuTeDSL/ep_gemm/combine_gemm.py index 1f28ad7cad3..5fe96eb650a 100644 --- a/transformer_engine/common/CuTeDSL/ep_gemm/combine_gemm.py +++ b/transformer_engine/common/CuTeDSL/ep_gemm/combine_gemm.py @@ -61,7 +61,7 @@ class CombineGemmConfig: dependents_at_entry: bool # the combine may start at the GEMM's entry (signaled combine only) backward: bool = False scaling_mode: int = DELAYED_TENSOR_SCALING # operand scaling (NVTEScalingMode) - rows_alignment: int = ROWS_PER_TILE # rows per expert slab are a multiple of it + token_alignment: int = ROWS_PER_TILE # rows per expert slab are a multiple of it grid_clusters: int = 0 # clusters launched (0: num_clusters), extras stop after the first chunk # Kernels, workspace layouts and compiled functions are specific to the device architecture. capability: tuple = field(default_factory=device_compute_capability) @@ -77,12 +77,12 @@ def build_kernel(cfg: CombineGemmConfig): comb, moe_utils = import_gemm_modules("moe_streaming_output_chunk_tile_scheduler") notify = None if cfg.n_chunk: - notify = comb.OutputNotifyConfig( - comb.OutputNotifyMode.N_CHUNK, + notify = comb.StreamingOutputNotifyConfig( + comb.StreamingOutputNotifyMode.N_CHUNK, cfg.n_chunk, - comb.output_notify_capacity(cfg.n_chunk, cfg.n), + comb.streaming_output_notify_capacity(cfg.n_chunk, cfg.n), caller_reset=True, - clusters_beside_combine=cfg.num_clusters, + clusters_beside_consumer=cfg.num_clusters, ) if cfg.mxfp8: rubin = is_sm107() @@ -95,11 +95,11 @@ def build_kernel(cfg: CombineGemmConfig): generate_sfd=False, discrete_col_sfd=False, enable_bias=False, - output_notify=notify, - launch_dependents_at_entry=cfg.dependents_at_entry, + streaming_output_notify=notify, + launch_pdl_dependents_at_entry=cfg.dependents_at_entry, **({"generate_c": False} if rubin else {}), **blockscaled_kwargs(cfg.num_experts), - **mxfp8_tail_tile_kwargs(cfg.rows_alignment), + **mxfp8_tail_tile_kwargs(cfg.token_alignment), ) kernel_class, _ = import_bf16_kernel("combine") return kernel_class( @@ -113,9 +113,9 @@ def build_kernel(cfg: CombineGemmConfig): expert_cnt=cfg.num_experts, weight_mode=moe_utils.MoEWeightMode.DENSE, use_dynamic_sched=True, - output_notify=notify, - launch_dependents_at_entry=cfg.dependents_at_entry, - **tail_tile_kwargs(cfg.rows_alignment, fused=not cfg.backward), + streaming_output_notify=notify, + launch_pdl_dependents_at_entry=cfg.dependents_at_entry, + **tail_tile_kwargs(cfg.token_alignment, fused=not cfg.backward), ) @@ -126,7 +126,7 @@ def workspace_layout(cfg: CombineGemmConfig): if not cfg.n_chunk: signal = -(-build_kernel(cfg).get_workspace_bytes() // 4) * 4 return signal + 4, signal, 1 - offsets = comb.output_notify_offsets(build_kernel(cfg)) + offsets = comb.streaming_output_notify_offsets(build_kernel(cfg)) return offsets["total_bytes"], offsets["signal"], offsets["capacity"] @@ -166,11 +166,12 @@ def _compile_mxfp8(cfg: CombineGemmConfig): @cute.jit def launch(a, b, sfb, sfa, d, expert_row_ends, alpha, prob, workspace, stream): weight = weight_view(b, n, k, experts, n_major=backward) + # The kernel builds a TMA atom for d_col but does not write it (no sfd), so alias it to d. d3 = rows_view(d, rows, n) kernel( rows_view(a, rows, k), weight, sfb, cutlass.Int32(0), cutlass.Int32(0), cutlass.Int64(0), OperandMajorMode.K, workspace.iterator, d3, d3, sfa, None, None, - None, None, expert_row_ends, alpha, None, None, prob_view(prob, rows), None, + None, None, expert_row_ends, alpha, None, None, prob_view(prob, rows), num_clusters, stream, ) # fmt: skip @@ -198,34 +199,34 @@ def launch_rubin(a, b, sfb, sfa, d, expert_row_ends, alpha, prob, workspace, str def _config( rows, k, n, num_experts, num_clusters, n_chunk, dependents_at_entry, backward, scaling_mode, - rows_alignment, grid_clusters, + token_alignment, grid_clusters, ): # fmt: skip """Build a CombineGemmConfig from the entry-point arguments.""" return CombineGemmConfig( rows, k, n, num_experts, num_clusters, n_chunk, bool(dependents_at_entry), bool(backward), - int(scaling_mode), rows_alignment, grid_clusters, + int(scaling_mode), token_alignment, grid_clusters, ) # fmt: skip def get_ep_combine_gemm_workspace_layout( rows, k, n, num_experts, num_clusters, n_chunk, dependents_at_entry, backward, - scaling_mode=DELAYED_TENSOR_SCALING, rows_alignment=ROWS_PER_TILE, grid_clusters=0, + scaling_mode=DELAYED_TENSOR_SCALING, token_alignment=ROWS_PER_TILE, grid_clusters=0, ): # fmt: skip """[total bytes, signal offset, signal entries] of the workspace of this configuration.""" return list(workspace_layout(_config( rows, k, n, num_experts, num_clusters, n_chunk, dependents_at_entry, backward, scaling_mode, - rows_alignment, grid_clusters, + token_alignment, grid_clusters, ))) # fmt: skip def get_ep_combine_gemm_function( fn_name, rows, k, n, num_experts, num_clusters, n_chunk, dependents_at_entry, backward, - scaling_mode=DELAYED_TENSOR_SCALING, rows_alignment=ROWS_PER_TILE, grid_clusters=0, + scaling_mode=DELAYED_TENSOR_SCALING, token_alignment=ROWS_PER_TILE, grid_clusters=0, ) -> bool: # fmt: skip """Compile and register the GEMM of this configuration as ``fn_name``; return whether it is.""" cfg = _config( rows, k, n, num_experts, num_clusters, n_chunk, dependents_at_entry, backward, scaling_mode, - rows_alignment, grid_clusters, + token_alignment, grid_clusters, ) # fmt: skip compile_fn = _compile_mxfp8 if cfg.mxfp8 else _compile return register_function(fn_name, lambda: compile_fn(cfg), "EP grouped GEMM combine") diff --git a/transformer_engine/common/CuTeDSL/ep_gemm/dispatch_gemm.py b/transformer_engine/common/CuTeDSL/ep_gemm/dispatch_gemm.py index 1076690b59a..f7d7435b558 100644 --- a/transformer_engine/common/CuTeDSL/ep_gemm/dispatch_gemm.py +++ b/transformer_engine/common/CuTeDSL/ep_gemm/dispatch_gemm.py @@ -17,7 +17,7 @@ Common operands: ``expert_row_ends`` [E] int32, ``alpha`` [E] FP32, ``prob`` [rows] FP32, ``workspace`` uint8, stream. With ``device_layout`` the forward also waits for the dispatch to write ``expert_row_ends`` and the word before it (expert 0's offset), both -1 beforehand. The -kernel tree must wait until they are at least 0 (EPC fc1db0b8 or later). +kernel waits until they are at least 0. MXFP8 scales: ``sfa`` is compact (as the dispatch delivers it) and ``sfb`` swizzled. The forward takes no ``prob`` and a ``norm_const`` [1] FP32 of 1. The backward writes ``sfd_row`` (swizzled), @@ -39,7 +39,6 @@ ROWS_PER_TILE, blockscaled_kwargs, compile_launch, - device_smem_optin, fake_tensor, fp8_fake, import_bf16_kernel, @@ -57,8 +56,6 @@ # Activation of the FC1 GLU to the activation function of its backward epilogue. _BACKWARD_ACTIVATIONS = {"swiglu": "dswiglu"} -# A/B stages of the SM 10.7 forward GEMMs, BF16 and MXFP8 with compact scales read by TMA. -_RUBIN_FC1_AB_STAGES = 8 @dataclass(frozen=True) @@ -72,7 +69,7 @@ class DispatchGemmConfig: num_clusters: int # persistent clusters beside the dispatch's SMs backward: bool = False scaling_mode: int = DELAYED_TENSOR_SCALING # operand scaling (NVTEScalingMode) - rows_alignment: int = ROWS_PER_TILE # rows per expert slab are a multiple of it + token_alignment: int = ROWS_PER_TILE # rows per expert slab are a multiple of it device_layout: bool = False # forward: the dispatch writes the expert row ends activation: str = "swiglu" # Kernels, workspace layouts and compiled functions are specific to the device architecture. @@ -93,7 +90,7 @@ def mxfp8(self) -> bool: @property def slot_rows(self) -> int: """Rows per ``signal[]`` entry: the expert alignment, at most one row tile.""" - return min(self.rows_alignment, ROWS_PER_TILE) + return min(self.token_alignment, ROWS_PER_TILE) @property def signal_capacity(self) -> int: @@ -101,12 +98,9 @@ def signal_capacity(self) -> int: return self.rows // self.slot_rows -def _tail_trigger(kernel_class) -> dict: - """PDL trigger of a forward kernel for its tail on the dispatch's SMs: at slots ready or at - entry, as the kernel class prefers.""" - if kernel_class.FC1_TAIL_AT_SLOTS_READY: - return {"launch_dependents_at_slots_ready": True} - return {"launch_dependents_at_entry": True} +def _tail_trigger() -> dict: + """PDL trigger of a forward kernel for its tail on the dispatch's SMs: at entry.""" + return {"launch_pdl_dependents_at_entry": True} def build_kernel(cfg: DispatchGemmConfig): @@ -118,19 +112,18 @@ def build_kernel(cfg: DispatchGemmConfig): # The TMA warp turns the received compact scales into the GEMM's layout per tile. common = { **blockscaled_kwargs(cfg.num_experts), - "signal_capacity": cfg.signal_capacity, + "streaming_signal_capacity": cfg.signal_capacity, "compact_sfa_sf_warp": True, "use_pdl": True, - **mxfp8_tail_tile_kwargs(cfg.rows_alignment), + **mxfp8_tail_tile_kwargs(cfg.token_alignment), } if cfg.backward and rubin: # 128-deep K tiles of one scale atom each: the TMA warp queues the compact scales ahead. module = import_gemm_modules("moe_blockscaled_grouped_gemm_dglu_rubin")[0] + # TODO(phuonguyen): fp8_k_tile / compact_sfa_queue are computed internally by cuDNN FE. return module.BlockScaledMoEGroupedGemmDgluKernel( discrete_col_sfd=True, act_func=backward_activation, - fp8_k_tile=128, - compact_sfa_queue=True, **common, ) if cfg.backward: @@ -138,6 +131,7 @@ def build_kernel(cfg: DispatchGemmConfig): return module.BlockScaledMoEGroupedGemmDgluDbiasKernel( discrete_col_sfd=True, act_func=backward_activation, + launch_pdl_dependents_at_entry=True, **common, ) if rubin: @@ -145,7 +139,8 @@ def build_kernel(cfg: DispatchGemmConfig): # through registers with the opt-in shared memory. module = import_gemm_modules("moe_blockscaled_grouped_gemm_glu_rubin")[0] kernel_class = module.BlockScaledMoEGroupedGemmGluKernel - scale_rows_tma = cfg.k % 1024 == 0 + # TODO(phuonguyen): smem_capacity / max_ab_stages / compact_sfa_rows are computed + # internally by cuDNN FE. return kernel_class( generate_sfd=True, discrete_col_sfd=False, @@ -153,22 +148,19 @@ def build_kernel(cfg: DispatchGemmConfig): enable_bias=False, generate_c=True, generate_sfd_col=False, - smem_capacity=None if scale_rows_tma else device_smem_optin(), device_layout=cfg.device_layout, - max_ab_stages=_RUBIN_FC1_AB_STAGES if scale_rows_tma else None, - compact_sfa_rows=scale_rows_tma, - **_tail_trigger(kernel_class), + **_tail_trigger(), **{**common, "vectorized_f32": True}, ) - module = import_gemm_modules("moe_blockscaled_grouped_gemm_quant_sm100")[0] - kernel_class = module.BlockScaledMoEGroupedGemmQuantKernel + module = import_gemm_modules("moe_blockscaled_grouped_gemm_glu_bias")[0] + kernel_class = module.BlockScaledMoEGroupedGemmGluBiasKernel return kernel_class( + act_func=cfg.activation, generate_sfd=True, discrete_col_sfd=False, enable_bias=False, - fuse_swiglu=True, device_layout=cfg.device_layout, - **_tail_trigger(kernel_class), + **_tail_trigger(), **common, ) common = { @@ -179,25 +171,26 @@ def build_kernel(cfg: DispatchGemmConfig): "vectorized_f32": False, "expert_cnt": cfg.num_experts, "use_dynamic_sched": True, - "signal_capacity": cfg.signal_capacity, + "streaming_signal_capacity": cfg.signal_capacity, "use_pdl": True, - **tail_tile_kwargs(cfg.rows_alignment, fused=not cfg.backward), + **tail_tile_kwargs(cfg.token_alignment, fused=not cfg.backward), } if cfg.backward: kernel_class, moe_utils = import_bf16_kernel("dispatch_bwd") return kernel_class( weight_mode=moe_utils.MoEWeightMode.DENSE, act_func=backward_activation, + launch_pdl_dependents_at_entry=True, **common, ) kernel_class, moe_utils = import_bf16_kernel("dispatch_fwd") return kernel_class( weight_mode=moe_utils.MoEWeightMode.DENSE, + act_func=cfg.activation, generate_c=True, enable_bias=False, device_layout=cfg.device_layout, - **({"max_ab_stages": _RUBIN_FC1_AB_STAGES} if rubin else {}), - **_tail_trigger(kernel_class), + **_tail_trigger(), **common, ) @@ -205,8 +198,8 @@ def build_kernel(cfg: DispatchGemmConfig): @functools.lru_cache(maxsize=None) def workspace_layout(cfg: DispatchGemmConfig): """Total bytes and byte offsets of the claim counter, ``signal[]`` and scheduler state.""" - helpers, _ = import_gemm_modules("moe_signal_helpers") - offsets = helpers.signal_workspace_offsets(build_kernel(cfg)) + helpers, _ = import_gemm_modules("moe_kernel_helpers") + offsets = helpers.streaming_signal_workspace_offsets(build_kernel(cfg)) return offsets["total_bytes"], offsets["counter"], offsets["signal"], offsets["state"] @@ -277,12 +270,11 @@ def _compile_forward_mxfp8(cfg: DispatchGemmConfig): @cute.jit def launch(a, b, sfb, sfa, c, d, sfd, expert_row_ends, alpha, norm_const, workspace, stream): weight = weight_view(b, n, k, experts, n_major=False) - d3 = rows_view(d, rows, d_cols) kernel( rows_view(a, rows, k), weight, sfb, cutlass.Int32(0), cutlass.Int32(0), - cutlass.Int64(0), OperandMajorMode.K, workspace.iterator, d3, d3, sfa, sfd, None, None, - norm_const, expert_row_ends, alpha, None, None, None, rows_view(c, rows, n), - num_clusters, stream, + cutlass.Int64(0), OperandMajorMode.K, workspace.iterator, rows_view(c, rows, n), + rows_view(d, rows, d_cols), None, sfa, sfd, None, None, norm_const, expert_row_ends, + alpha, None, None, num_clusters, stream, ) # fmt: skip @cute.jit @@ -320,8 +312,6 @@ def _compile_backward_mxfp8(cfg: DispatchGemmConfig): """MXFP8 FC2 data gradient with the columnwise forward weight [experts, k, n] read N-major, SwiGLU backward in the epilogue, and the forward activation recomputed columnwise.""" kernel, (rows, k, n, experts, num_clusters), tail = _prologue(cfg) - # The SM 10.7 kernel takes the GeGLU linear offset (unused by SwiGLU) ahead of the bias. - rubin = is_sm107() @cute.jit def launch( @@ -334,8 +324,8 @@ def launch( cutlass.Int64(0), OperandMajorMode.K, workspace.iterator, rows_view(c, rows, 2 * n), rows_view(d, rows, 2 * n), rows_view(d_col, rows, 2 * n), sfa, sfd_row, sfd_col, None, norm_const, expert_row_ends, alpha, alpha, prob_view(prob, rows), - prob_view(dprob, rows), *((cutlass.Float32(1.0),) if rubin else ()), None, - rows_view(h, rows, n), sfh_col, num_clusters, stream, + prob_view(dprob, rows), None, num_clusters, stream, + h_tensor=rows_view(h, rows, n), sfh_col_tensor=sfh_col, ) # fmt: skip row_ends, alpha, prob, workspace = tail @@ -369,32 +359,32 @@ def launch( } -def _config(rows, k, n, num_experts, num_clusters, backward, scaling_mode, rows_alignment, +def _config(rows, k, n, num_experts, num_clusters, backward, scaling_mode, token_alignment, device_layout): # fmt: skip """Build a DispatchGemmConfig from the entry-point arguments.""" return DispatchGemmConfig( - rows, k, n, num_experts, num_clusters, bool(backward), int(scaling_mode), rows_alignment, + rows, k, n, num_experts, num_clusters, bool(backward), int(scaling_mode), token_alignment, bool(device_layout), ) # fmt: skip def get_ep_dispatch_gemm_workspace_layout( rows, k, n, num_experts, num_clusters, backward, scaling_mode=DELAYED_TENSOR_SCALING, - rows_alignment=ROWS_PER_TILE, device_layout=False, + token_alignment=ROWS_PER_TILE, device_layout=False, ): # fmt: skip """[total bytes, counter, signal, state] byte offsets of the workspace of this configuration.""" return list(workspace_layout(_config( - rows, k, n, num_experts, num_clusters, backward, scaling_mode, rows_alignment, device_layout, + rows, k, n, num_experts, num_clusters, backward, scaling_mode, token_alignment, device_layout, ))) # fmt: skip def get_ep_dispatch_gemm_function( fn_name, rows, k, n, num_experts, num_clusters, backward, scaling_mode=DELAYED_TENSOR_SCALING, - rows_alignment=ROWS_PER_TILE, device_layout=False, + token_alignment=ROWS_PER_TILE, device_layout=False, ) -> bool: # fmt: skip """Compile and register the GEMM of this configuration as ``fn_name``; return whether it is.""" cfg = _config( - rows, k, n, num_experts, num_clusters, backward, scaling_mode, rows_alignment, device_layout, + rows, k, n, num_experts, num_clusters, backward, scaling_mode, token_alignment, device_layout, ) # fmt: skip compile_fn = _COMPILERS[cfg.backward, cfg.mxfp8] return register_function(fn_name, lambda: compile_fn(cfg), "EP dispatch grouped GEMM") diff --git a/transformer_engine/common/CuTeDSL/ep_gemm/wgrad_gemm.py b/transformer_engine/common/CuTeDSL/ep_gemm/wgrad_gemm.py index 151985b455d..7c92c687d77 100644 --- a/transformer_engine/common/CuTeDSL/ep_gemm/wgrad_gemm.py +++ b/transformer_engine/common/CuTeDSL/ep_gemm/wgrad_gemm.py @@ -7,15 +7,10 @@ ``weight_grad[e] = grad[rows of e]^T x[rows of e]`` per expert: ``grad`` [rows, m] and ``x`` [rows, n] BF16, or MXFP8 columnwise data with their GEMM-swizzled columnwise scales, ``weight_grad`` [experts, m, n] BF16 or FP32, written or added to. Operands: ``expert_row_ends`` -[experts] int32, ``workspace`` uint8, stream; ``signal`` [rows / slot rows] int32 with -``ready_slot_rows`` (BF16 only). - -Each launch is a persistent grid that claims output tiles from a counter in ``workspace``, so -launches sharing one workspace split the tiles. It is a programmatic dependent of the kernel -before it and lets the kernel behind it start early. MXFP8 launches of an added or FP32 weight -gradient, and on SM 10.7 of a written BF16 one with long experts, read per-expert descriptors -that a ``descriptors_only`` launch writes into ``workspace`` ahead of them; the others read global -descriptors. +[experts] int32, ``workspace`` uint8, stream. + +Each launch is a persistent grid that claims output tiles from an atomic counter in ``workspace``, +so launches sharing one workspace split the tiles across SMs. """ import functools @@ -51,12 +46,7 @@ class WgradConfig: num_clusters: int # persistent clusters fp32_out: bool = False # FP32 instead of BF16 weight gradient accumulate: bool = False # add to the weight gradient instead of writing it - wait_primary_at_start: bool = False # wait for the kernel before it ahead of any load - ready_slot_rows: int = 0 # wait until signal[] is set for every slot of these rows scaling_mode: int = DELAYED_TENSOR_SCALING # operand scaling (NVTEScalingMode) - descriptors_only: bool = False # MXFP8: write the per-expert descriptors, no GEMM - rows_alignment: int = 0 # rows per expert slab are a multiple of it - routed_rows: int = 0 # rows a rank receives on average # Kernels, workspace layouts and compiled functions are specific to the device architecture. capability: tuple = field(default_factory=device_compute_capability) @@ -66,132 +56,53 @@ def mxfp8(self) -> bool: return self.scaling_mode == MXFP8_1D_SCALING -def _mxfp8_kernels(): - """(per-expert descriptor, reuse, dense or None, moe_utils) MXFP8 kernel classes of the - device. SM 10.7 has no dense one.""" +def _mxfp8_kernel(): + """MXFP8 weight-gradient kernel class of the device and moe_utils.""" if is_sm107(): - stock, reuse, moe_utils = import_gemm_modules( - "moe_blockscaled_grouped_gemm_wgrad_rubin", - "moe_blockscaled_grouped_gemm_wgrad_reuse_rubin", - ) - return ( - stock.BlockScaledMoEGroupedGemmWgradRubinKernel, - reuse.BlockScaledMoEGroupedGemmWgradReuseRubinKernel, - None, - moe_utils, - ) - blockscaled, dense, reuse, moe_utils = import_gemm_modules( - "moe_blockscaled_grouped_gemm_wgrad", - "moe_blockscaled_grouped_gemm_wgrad_dense", - "moe_blockscaled_grouped_gemm_wgrad_reuse", - ) - return ( - blockscaled.BlockScaledMoEGroupedGemmWgradKernel, - reuse.BlockScaledMoEGroupedGemmWgradReuseKernel, - dense.BlockScaledMoEGroupedGemmWgradDenseKernel, - moe_utils, - ) - - -def _global_descriptor_kernel(cfg: WgradConfig): - """Class of an MXFP8 weight gradient written in BF16 that reads global descriptors: the one - keeping A across the N tiles of an expert when the experts are short on average, else the - dense one; None for the others.""" - if cfg.accumulate or cfg.fp32_out: - return None - _, reuse, dense, _ = _mxfp8_kernels() - # Each weight gradient picks for its own shape; EPCompOverlap keeps A only when both can, so - # with ffn 256, 1280 or 1792 it runs the first one dense too. - if reuse.can_implement(cfg.m, cfg.n, cfg.rows_alignment, cfg.routed_rows, cfg.num_experts): - return reuse - return dense + module, moe_utils = import_gemm_modules("moe_blockscaled_grouped_gemm_wgrad_rubin") + return module.BlockScaledMoEGroupedGemmWgradRubinKernel, moe_utils + module, moe_utils = import_gemm_modules("moe_blockscaled_grouped_gemm_wgrad") + return module.BlockScaledMoEGroupedGemmWgradKernel, moe_utils def reads_descriptors(cfg: WgradConfig) -> bool: - """Whether the launches of ``cfg`` read the per-expert descriptors of a ``descriptors_only`` + """Whether the launches of ``cfg`` read per-expert descriptors from a ``descriptors_only`` launch.""" - return cfg.mxfp8 and _global_descriptor_kernel(cfg) is None + del cfg + # TODO(phuonguyen): cuDNN FE has no descriptors-only / reuse wgrad kernels, so the single + # kernel reads its operands directly and no descriptor pre-launch is needed. + return False def build_kernel(cfg: WgradConfig): - """Kernel for ``cfg``: 256 x 512 output tiles where they divide a BF16 weight gradient that is - written, else 256 x 256 tiles. An MXFP8 weight gradient written in BF16 keeps A across the N - tiles of an expert when the experts are short on average, else reads A, B and the scales - through global descriptors (per-expert ones on SM 10.7).""" - if cfg.mxfp8: - stock, _, _, moe_utils = _mxfp8_kernels() - kernel = _global_descriptor_kernel(cfg) - if kernel is not None: - # The SM 10.7 reuse kernel sizes its A ring to the average padded expert. - padded_rows = cfg.routed_rows + cfg.num_experts * cfg.rows_alignment // 2 - a_stages = ( - {"a_stages": kernel.a_stages_for(padded_rows, cfg.num_experts)} - if is_sm107() - else {} - ) - return kernel( - sf_vec_size=SF_VEC_SIZE, - acc_dtype=cutlass.Float32, - use_2cta_instrs=True, - mma_tiler_mn=MMA_TILER_MN, - cluster_shape_mn=CLUSTER_MN, - expert_cnt=cfg.num_experts, - weight_mode=moe_utils.MoEWeightMode.DENSE, - input_order=moe_utils.WGradInputOrder.Tensor2D, - tile_claim=moe_utils.WgradTileClaim.COUNTER, - use_pdl=True, - wait_primary_at_start=cfg.wait_primary_at_start, - **a_stages, - ) - if is_sm107() and cfg.rows <= 256: - # The SM 10.7 kernel faults when the K extent is a single 256-row tile. - raise ValueError( - "The SM 10.7 MXFP8 weight gradient that is added, FP32 or of long experts needs " - "a receive capacity above 256 rows." - ) - return stock( - sf_vec_size=SF_VEC_SIZE, - acc_dtype=cutlass.Float32, - use_2cta_instrs=True, - mma_tiler_mn=MMA_TILER_MN, - cluster_shape_mn=CLUSTER_MN, - accumulate_on_output=cfg.accumulate, - expert_cnt=cfg.num_experts, - weight_mode=moe_utils.MoEWeightMode.DENSE, - input_order=moe_utils.WGradInputOrder.Tensor2D, - tile_claim=moe_utils.WgradTileClaim.COUNTER, - descriptors_only=cfg.descriptors_only, - descriptors_prebuilt=not cfg.descriptors_only, - use_pdl=not cfg.descriptors_only, - wait_primary_at_start=cfg.wait_primary_at_start, - ) - if is_sm107(): - # Both kernels, sized for the SM 10.7 shared memory. - names = ("moe_grouped_gemm_sm107",) * 2 - else: - names = ("moe_grouped_gemm_wgrad", "moe_grouped_gemm_wgrad_wide") - stock, wide, moe_utils = import_gemm_modules(*names) - options = { - "expert_cnt": cfg.num_experts, - "tile_claim": moe_utils.WgradTileClaim.COUNTER, - } - wide_kernel = wide.MoEGroupedGemmWgradWideBF16Kernel - if not (cfg.accumulate or cfg.fp32_out) and wide_kernel.can_implement(cfg.m, cfg.n): - return wide_kernel( - use_pdl=True, - wait_primary_at_start=cfg.wait_primary_at_start, - ready_slot_rows=cfg.ready_slot_rows, - **options, - ) - return stock.MoEGroupedGemmWgradBF16Kernel( + """Weight-gradient kernel for ``cfg``. Persistent clusters claim output tiles from an atomic + counter in the workspace, so launches sharing one workspace split the tiles across SMs.""" + # cuDNN FE splits the output tiles across SMs with atomic_counter_claim. Its finer overlap is + # performance-only and not upstreamed yet: use_pdl (WAR for PR #2898), wait_primary_at_start, + # signal_unit_tokens, the MXFP8 descriptor-reuse kernels and the 256 x 512 wide BF16 kernel. + # TODO(phuonguyen): restore them once cuDNN FE adds them; correctness holds without them. + common = dict( acc_dtype=cutlass.Float32, use_2cta_instrs=True, mma_tiler_mn=MMA_TILER_MN, cluster_shape_mn=CLUSTER_MN, accumulate_on_output=cfg.accumulate, + expert_cnt=cfg.num_experts, + atomic_counter_claim=True, + ) + if cfg.mxfp8: + kernel_class, moe_utils = _mxfp8_kernel() + return kernel_class( + sf_vec_size=SF_VEC_SIZE, + weight_mode=moe_utils.MoEWeightMode.DENSE, + input_order=moe_utils.WGradInputOrder.Tensor2D, + **common, + ) + module, moe_utils = import_gemm_modules("moe_grouped_gemm_wgrad") + return module.MoEGroupedGemmWgradBF16Kernel( weight_mode=moe_utils.MoEWeightMode.DENSE, input_order=moe_utils.WGradInputOrder.Tensor2D, - **options, + **common, ) @@ -223,13 +134,15 @@ def views(grad, x, weight_grad): tail = ( fake_tensor(cutlass.Int32, (experts,), (0,), 16), fake_tensor(cutlass.Uint8, (workspace_layout(cfg)[0],), (0,), 128), + # Shared tile counter: launches into one workspace split one tile list. + fake_tensor(cutlass.Int32, (1,), (0,), 16), ) if cfg.mxfp8: k_scales = rows // SF_VEC_SIZE @cute.jit def launch_mxfp8( - grad, x, grad_scales, x_scales, weight_grad, expert_row_ends, workspace, stream + grad, x, grad_scales, x_scales, weight_grad, expert_row_ends, workspace, counter, stream ): a, b, out = views(grad, x, weight_grad) # Columnwise scales as (columns, rows / 32) over the per-expert swizzled atoms. @@ -239,7 +152,10 @@ def launch_mxfp8( sfb = cute.make_tensor( x_scales.iterator, cute.make_layout((n, k_scales), stride=(k_scales, 1)) ) - kernel(a, b, sfa, sfb, out, expert_row_ends, workspace, num_clusters, stream) + kernel( + a, b, sfa, sfb, out, expert_row_ends, workspace, num_clusters, stream, + scheduler_counter=counter, + ) # fmt: skip return compile_launch( launch_mxfp8, @@ -257,80 +173,62 @@ def launch_mxfp8( out_fake, *tail, ) - if cfg.ready_slot_rows: - # Only the wide kernel waits on the signal. The stock kernel, chosen for FP32 or - # accumulated gradients and shapes the wide one cannot implement, is launched without PDL, - # so it starts after the signaling kernels complete and has no flags to wait for. - wait_on_signal = getattr(kernel, "ready_slot_rows", 0) > 0 - - @cute.jit - def launch_ready(grad, x, weight_grad, expert_row_ends, workspace, signal, stream): - a, b, out = views(grad, x, weight_grad) - if cutlass.const_expr(wait_on_signal): - kernel( - a, b, out, expert_row_ends, workspace, num_clusters, stream, None, - signal.iterator, - ) # fmt: skip - else: - kernel(a, b, out, expert_row_ends, workspace, num_clusters, stream) - - return compile_launch( - launch_ready, - *fakes, - fake_tensor(cutlass.Int32, (rows // cfg.ready_slot_rows,), (0,), 4), - ) @cute.jit - def launch(grad, x, weight_grad, expert_row_ends, workspace, stream): + def launch(grad, x, weight_grad, expert_row_ends, workspace, counter, stream): a, b, out = views(grad, x, weight_grad) - kernel(a, b, out, expert_row_ends, workspace, num_clusters, stream) + kernel( + a, b, out, expert_row_ends, workspace, num_clusters, stream, scheduler_counter=counter + ) return compile_launch(launch, *fakes) def _config( rows, m, n, num_experts, num_clusters, fp32_out, accumulate, wait_primary_at_start, - ready_slot_rows, scaling_mode, descriptors_only, rows_alignment, routed_rows, + signal_unit_tokens, scaling_mode, descriptors_only, token_alignment, routed_tokens, ): # fmt: skip - """Build a WgradConfig from the entry-point arguments.""" + """Build a WgradConfig from the entry-point arguments. The overlap-selection arguments + (wait_primary_at_start, signal_unit_tokens, descriptors_only, token_alignment, routed_tokens) select + cuDNN FE optimizations that are not upstreamed yet (see build_kernel); they are accepted for ABI + stability and currently ignored.""" + del wait_primary_at_start, signal_unit_tokens, descriptors_only, token_alignment, routed_tokens return WgradConfig( - rows, m, n, num_experts, num_clusters, bool(fp32_out), bool(accumulate), - bool(wait_primary_at_start), ready_slot_rows, int(scaling_mode), bool(descriptors_only), - rows_alignment, routed_rows, - ) # fmt: skip + rows, m, n, num_experts, num_clusters, bool(fp32_out), bool(accumulate), int(scaling_mode) + ) def get_ep_wgrad_workspace_layout( rows, m, n, num_experts, num_clusters, fp32_out, accumulate, wait_primary_at_start, - ready_slot_rows, scaling_mode, descriptors_only, rows_alignment, routed_rows, + signal_unit_tokens, scaling_mode, descriptors_only, token_alignment, routed_tokens, ): # fmt: skip """[total bytes, counter offset] of the workspace of this configuration.""" return list(workspace_layout(_config( rows, m, n, num_experts, num_clusters, fp32_out, accumulate, wait_primary_at_start, - ready_slot_rows, scaling_mode, descriptors_only, rows_alignment, routed_rows, + signal_unit_tokens, scaling_mode, descriptors_only, token_alignment, routed_tokens, ))) # fmt: skip def get_ep_wgrad_reads_descriptors( rows, m, n, num_experts, num_clusters, fp32_out, accumulate, wait_primary_at_start, - ready_slot_rows, scaling_mode, descriptors_only, rows_alignment, routed_rows, + signal_unit_tokens, scaling_mode, descriptors_only, token_alignment, routed_tokens, ) -> bool: # fmt: skip """Whether the launches of this configuration read the per-expert descriptors of a ``descriptors_only`` launch.""" return reads_descriptors(_config( rows, m, n, num_experts, num_clusters, fp32_out, accumulate, wait_primary_at_start, - ready_slot_rows, scaling_mode, descriptors_only, rows_alignment, routed_rows, + signal_unit_tokens, scaling_mode, descriptors_only, token_alignment, routed_tokens, )) # fmt: skip def get_ep_wgrad_function( fn_name, rows, m, n, num_experts, num_clusters, fp32_out, accumulate, wait_primary_at_start, - ready_slot_rows, scaling_mode, descriptors_only, rows_alignment, routed_rows, + signal_unit_tokens, scaling_mode, descriptors_only, token_alignment, routed_tokens, ) -> bool: # fmt: skip """Compile and register the weight gradient of this configuration as ``fn_name``; return whether it is.""" cfg = _config( rows, m, n, num_experts, num_clusters, fp32_out, accumulate, wait_primary_at_start, - ready_slot_rows, scaling_mode, descriptors_only, rows_alignment, routed_rows, + signal_unit_tokens, scaling_mode, descriptors_only, token_alignment, routed_tokens, ) # fmt: skip return register_function(fn_name, lambda: _compile(cfg), "EP weight-gradient grouped GEMM") diff --git a/transformer_engine/common/ep/ep_gemm_api.cpp b/transformer_engine/common/ep/ep_gemm_api.cpp index 6c71164482e..882425eb99e 100644 --- a/transformer_engine/common/ep/ep_gemm_api.cpp +++ b/transformer_engine/common/ep/ep_gemm_api.cpp @@ -142,7 +142,7 @@ struct EpGemmContext { size_t alignment() const { return layer_cfg.dispatch_output_per_expert_alignment; } // Rows per dispatch readiness flag: the alignment. A GEMM M tile (kRowsPerTile rows) is a whole // multiple of every allowed alignment, so each tile spans a whole number of readiness slots. - size_t ready_slot_rows() const { return alignment(); } + size_t signal_unit_tokens() const { return alignment(); } }; // comm_sms: the group's SM count of the NCCL EP call that the entry point overlaps; the GEMM runs @@ -213,8 +213,8 @@ void check_expert_token_offsets(const NVTETensor expert_token_offsets, size_t nu // Rows: the group capacity, or any multiple of the flag rows in eager mode. void check_rows(const EpGemmContext& ctx, size_t rows, const char* name) { - NVTE_CHECK(rows % ctx.ready_slot_rows() == 0, name, " rows (", rows, ") must be a multiple of ", - ctx.ready_slot_rows()); + NVTE_CHECK(rows % ctx.signal_unit_tokens() == 0, name, " rows (", rows, + ") must be a multiple of ", ctx.signal_unit_tokens()); NVTE_CHECK(ctx.eager || rows == static_cast(ctx.group.max_recv_tokens_per_rank), name, " has ", rows, " rows, max_recv_tokens_per_rank is ", ctx.group.max_recv_tokens_per_rank); @@ -442,13 +442,13 @@ std::optional make_wgrad(const EpGemmContext& ctx, NVTETensor grad, NVTET const NVTEDType out_type = nvte_tensor_type(weight_grad); NVTE_CHECK(out_type == kNVTEBFloat16 || out_type == kNVTEFloat32, "weight_grad must be bfloat16 or float32"); - const size_t routed_rows = + const size_t routed_tokens = static_cast(ctx.group.max_tokens_per_rank) * ctx.layer_cfg.top_k; Wgrad wgrad{grad, x, weight_grad, {rows, m, n, num_experts, 1, out_type == kNVTEFloat32, accumulate, false, 0, - scaling_mode, false, ctx.alignment(), routed_rows}, + scaling_mode, false, ctx.alignment(), routed_tokens}, {}}; const auto layout = wgrad.config.workspace_layout(); NVTE_CHECK(layout.has_value(), "cannot query the weight-gradient workspace layout"); @@ -465,11 +465,11 @@ bool needs_descriptors(const Wgrad& wgrad) { // One launch of a weight gradient on num_clusters clusters (none: no launch), a programmatic // dependent of the kernel before it. Launches sharing the call's workspace split the tiles. -// wait_primary_at_start: no load before that kernel completes. ready_slot_rows: no load before +// wait_primary_at_start: no load before that kernel completes. signal_unit_tokens: no load before // every dispatch flag of the expert rows is set. descriptors_only (MXFP8): a plain launch that // writes the per-expert descriptors the other launches read; it follows the scratch reset. void launch_wgrad(const Wgrad& wgrad, const GemmScratch& scratch, int num_clusters, - bool wait_primary_at_start, size_t ready_slot_rows, cudaStream_t stream, + bool wait_primary_at_start, size_t signal_unit_tokens, cudaStream_t stream, bool descriptors_only) { if (num_clusters <= 0) { return; @@ -477,33 +477,34 @@ void launch_wgrad(const Wgrad& wgrad, const GemmScratch& scratch, int num_cluste ep::EpWgradConfig config = wgrad.config; config.num_clusters = num_clusters; config.wait_primary_at_start = wait_primary_at_start; - config.ready_slot_rows = ready_slot_rows; + config.signal_unit_tokens = signal_unit_tokens; config.descriptors_only = descriptors_only; ep::WorkspaceLayout layout; const tvm::ffi::Function gemm = get_gemm(config, &layout); - // The call sized the scratch from its base configuration. + // The call sized the scratch from its base configuration. A base and tail must land on one + // workspace and the same tile-counter offset so they share one counter instead of each resetting + // and re-running the whole GEMM. NVTE_CHECK( layout.total_bytes <= wgrad.layout.total_bytes && layout.counter == wgrad.layout.counter, - "weight-gradient workspace layout differs between launches"); + "weight-gradient launches must share one workspace and tile counter"); auto out = wrap_rowwise(wgrad.weight_grad, false); auto row_ends = wrap_raw(scratch.row_ends, kNVTEInt32, config.num_experts); auto ws = wrap_raw(scratch.wgrad, kNVTEByte, layout.total_bytes); + // The tile counter the launches share: the caller zeroed it and the kernel does not reset it, so + // a base and tail into one workspace split one tile list instead of each draining it. + auto counter = wrap_raw(scratch.wgrad + layout.counter, kNVTEInt32, 1); if (config.is_mxfp8()) { auto grad = wrap_columnwise(wgrad.grad, true); auto x = wrap_columnwise(wgrad.x, true); auto grad_scales = wrap_scales(wgrad.grad, true, config.rows, config.m); auto x_scales = wrap_scales(wgrad.x, true, config.rows, config.n); - gemm(&grad, &x, &grad_scales, &x_scales, &out, &row_ends, &ws, static_cast(stream)); + gemm(&grad, &x, &grad_scales, &x_scales, &out, &row_ends, &ws, &counter, + static_cast(stream)); return; } auto grad = wrap_rowwise(wgrad.grad, true); auto x = wrap_rowwise(wgrad.x, true); - if (ready_slot_rows > 0) { - auto signal = wrap_raw(scratch.signal, kNVTEInt32, config.rows / ready_slot_rows); - gemm(&grad, &x, &out, &row_ends, &ws, &signal, static_cast(stream)); - return; - } - gemm(&grad, &x, &out, &row_ends, &ws, static_cast(stream)); + gemm(&grad, &x, &out, &row_ends, &ws, &counter, static_cast(stream)); } // The columnwise MXFP8 copy of t's received rows, requantized from its rowwise data and compact @@ -543,13 +544,13 @@ void launch_requant(NVTETensor t, const GemmScratch& scratch, size_t rows, size_ // [m, n], as make_wgrad sizes it; the max over the output precisions, which the query does not know. size_t wgrad_workspace_bytes(const EpGemmContext& ctx, size_t rows, size_t m, size_t n, size_t num_experts, NVTEScalingMode scaling_mode) { - const size_t routed_rows = + const size_t routed_tokens = static_cast(ctx.group.max_tokens_per_rank) * ctx.layer_cfg.top_k; size_t bytes = 0; for (const bool fp32_out : {false, true}) { - const ep::EpWgradConfig config{rows, m, n, num_experts, 1, fp32_out, - false, false, 0, scaling_mode, false, ctx.alignment(), - routed_rows}; + const ep::EpWgradConfig config{rows, m, n, num_experts, 1, fp32_out, + false, false, 0, scaling_mode, false, ctx.alignment(), + routed_tokens}; // The output precision is not known here, so size over both. A variant the device does not // support (e.g. the SM 10.7 FP32 MXFP8 weight gradient at or below 256 rows) throws while // building its kernel; skip it rather than failing the sizing of a supported call. @@ -695,7 +696,7 @@ void nvte_ep_dispatch_gemm_fwd(NVTETensor handle_mem, const NVTETensor topk_idx, } GemmScratch scratch = claim_scratch(ws_base, ws_bytes, layout.total_bytes, num_experts, rows, false, 0); - set_signal_words(scratch, layout, rows / ctx.ready_slot_rows()); + set_signal_words(scratch, layout, rows / ctx.signal_unit_tokens()); // The GEMM reads the expert row ends from the caller's [num_experts + 1] int32 // expert_token_offsets (expert 0's start, then the per-expert ends); the dispatch writes them in // capacity mode. @@ -706,7 +707,7 @@ void nvte_ep_dispatch_gemm_fwd(NVTETensor handle_mem, const NVTETensor topk_idx, TensorWrapper signal(scratch.signal, std::vector{static_cast(scratch.signal_capacity)}, DType::kInt32); - const ep::EpSignal dispatch_signal{signal.data(), ctx.ready_slot_rows()}; + const ep::EpSignal dispatch_signal{signal.data(), ctx.signal_unit_tokens()}; NVTECommWindow no_window{}; if (device_layout) { // Flags, scheduler state and unset layout words, before the dispatch that sets them. The fused @@ -761,6 +762,13 @@ void nvte_ep_dispatch_gemm_fwd(NVTETensor handle_mem, const NVTETensor topk_idx, gemm(&a, &b, &c, &d, &row_ends, &alpha, &prob, &ws, static_cast(stream)); } } + // The layout the dispatch wrote ends in the recv total; no row drops in this mode. It follows + // the GEMM launches so that it does not sit between the dispatch and its programmatic dependent. + if (device_layout && total_recv_tokens != nullptr) { + NVTE_CHECK_CUDA(cudaMemcpyAsync(nvte_tensor_data(total_recv_tokens), + scratch.row_ends + (num_experts - 1), sizeof(int32_t), + cudaMemcpyDefault, stream)); + } } void nvte_ep_combine_gemm_fwd(NVTETensor handle_mem, const NVTETensor gemm_in, @@ -897,7 +905,7 @@ void nvte_ep_combine_gemm_bwd( const tvm::ffi::Function gemm = get_gemm(config, &layout); GemmScratch scratch = claim_scratch(ws_base, ws_bytes, layout.total_bytes, num_experts, rows, false, wgrad ? wgrad->layout.total_bytes : 0); - set_signal_words(scratch, layout, rows / ctx.ready_slot_rows()); + set_signal_words(scratch, layout, rows / ctx.signal_unit_tokens()); if (wgrad) { scratch.reset.fill(scratch.wgrad + wgrad->layout.counter, 1, ep::kFillZero); } @@ -918,7 +926,7 @@ void nvte_ep_combine_gemm_bwd( TensorWrapper signal(scratch.signal, std::vector{static_cast(scratch.signal_capacity)}, DType::kInt32); - const ep::EpSignal dispatch_signal{signal.data(), ctx.ready_slot_rows()}; + const ep::EpSignal dispatch_signal{signal.data(), ctx.signal_unit_tokens()}; NVTECommWindow no_window{}; ctx.backend.combine_bwd(handle_mem, grad_result, grad_result_win, grad_expert_out, no_window, &dispatch_signal, &ctx.layer_cfg, stream); @@ -967,12 +975,11 @@ void nvte_ep_combine_gemm_bwd( } auto b = wrap_rowwise(weight, false); gemm(&a, &b, &c, &d, &dprob, &row_ends, &alpha, &prob, &ws, static_cast(stream)); - // The weight gradient once every row is received: its tail on the SMs the reverse dispatch - // frees, its base on those the GEMM frees. + // The weight gradient once the GEMM completes: its base waits for the GEMM, then lets its tail in. + // Both launches claim from one shared tile counter, so the split does not re-run the whole GEMM. if (wgrad) { - launch_wgrad(*wgrad, scratch, ctx.all_clusters - ctx.num_clusters, false, ctx.ready_slot_rows(), - stream, false); - launch_wgrad(*wgrad, scratch, ctx.num_clusters, false, ctx.ready_slot_rows(), stream, false); + launch_wgrad(*wgrad, scratch, ctx.num_clusters, true, 0, stream, false); + launch_wgrad(*wgrad, scratch, ctx.all_clusters - ctx.num_clusters, false, 0, stream, false); } } @@ -1089,7 +1096,7 @@ void nvte_ep_dispatch_gemm_bwd(NVTETensor handle_mem, const NVTETensor grad_gemm ctx.backend.dispatch_bwd(handle_mem, grad_recv_tokens, no_window, grad_recv_topk_weights, no_window, grad_tokens, grad_topk_weights, &combine_signal, &ctx.layer_cfg, stream); - // Its tail takes the tiles left on the communication SMs. + // Its tail takes the tiles the base left; both claim from one shared counter. if (wgrad) { launch_wgrad(*wgrad, scratch, ctx.all_clusters - ctx.num_clusters, false, 0, stream, false); } diff --git a/transformer_engine/common/ep/ep_gemm_config.h b/transformer_engine/common/ep/ep_gemm_config.h index 814d145addf..3e76e4fa850 100644 --- a/transformer_engine/common/ep/ep_gemm_config.h +++ b/transformer_engine/common/ep/ep_gemm_config.h @@ -159,7 +159,7 @@ struct EpDispatchGemmConfig { int num_clusters; // persistent clusters beside its NCCL EP call's SMs bool backward; // the second GEMM's data gradient and SwiGLU backward instead of the first GEMM NVTEScalingMode scaling_mode; // operand scaling: delayed for BF16, MXFP8 1D for MXFP8 - size_t rows_alignment; // rows per expert slab are a multiple of it + size_t token_alignment; // rows per expert slab are a multiple of it // Forward: the dispatch writes the expert offsets and the row total, the word before the row // ends and the row ends, after the caller set them to -1. bool device_layout = false; @@ -171,7 +171,7 @@ struct EpDispatchGemmConfig { return std::make_tuple(static_cast(rows), static_cast(k), static_cast(n), static_cast(num_experts), num_clusters, backward, static_cast(scaling_mode), - static_cast(rows_alignment), device_layout); + static_cast(token_alignment), device_layout); } std::string to_key() const { return config_key("ep_dispatch_gemm", args()); } @@ -199,7 +199,7 @@ struct EpCombineGemmConfig { bool dependents_at_entry; bool backward; // the data gradient of the first GEMM instead of the second GEMM NVTEScalingMode scaling_mode; // operand scaling: delayed for BF16, MXFP8 1D for MXFP8 - size_t rows_alignment; // rows per expert slab are a multiple of it + size_t token_alignment; // rows per expert slab are a multiple of it // Clusters launched, 0: num_clusters. Those past num_clusters stop after the first chunk. int grid_clusters = 0; @@ -210,8 +210,8 @@ struct EpCombineGemmConfig { return std::make_tuple(static_cast(rows), static_cast(k), static_cast(n), static_cast(num_experts), num_clusters, static_cast(n_chunk), dependents_at_entry, backward, - static_cast(scaling_mode), static_cast(rows_alignment), - grid_clusters); + static_cast(scaling_mode), + static_cast(token_alignment), grid_clusters); } std::string to_key() const { return config_key("ep_combine_gemm", args()); } @@ -241,25 +241,25 @@ struct EpWgradConfig { bool fp32_out; // FP32 instead of BF16 weight gradient bool accumulate; // add to the weight gradient instead of writing it bool wait_primary_at_start; // wait for the kernel before it ahead of any load - size_t ready_slot_rows; // wait for every dispatch flag of this many rows, 0: none + size_t signal_unit_tokens; // wait for every dispatch flag of this many rows, 0: none // Operand scaling: delayed for BF16, MXFP8 1D for MXFP8. With MXFP8 the GEMM launches of some // weight gradients (reads_descriptors) read the per-expert descriptors that one launch with // descriptors_only writes into the workspace first. NVTEScalingMode scaling_mode; bool descriptors_only; - size_t rows_alignment; // rows per expert slab are a multiple of it - size_t routed_rows; // rows a rank receives at capacity under uniform routing, unpadded + size_t token_alignment; // rows per expert slab are a multiple of it + size_t routed_tokens; // rows a rank receives at capacity under uniform routing, unpadded bool is_mxfp8() const { return scaling_mode == NVTE_MXFP8_1D_SCALING; } // In the parameter order of the get_ep_* function of CuTeDSL/ep_gemm/wgrad_gemm.py. auto args() const { - return std::make_tuple(static_cast(rows), static_cast(m), - static_cast(n), static_cast(num_experts), num_clusters, - fp32_out, accumulate, wait_primary_at_start, - static_cast(ready_slot_rows), - static_cast(scaling_mode), descriptors_only, - static_cast(rows_alignment), static_cast(routed_rows)); + return std::make_tuple( + static_cast(rows), static_cast(m), static_cast(n), + static_cast(num_experts), num_clusters, fp32_out, accumulate, + wait_primary_at_start, static_cast(signal_unit_tokens), + static_cast(scaling_mode), descriptors_only, static_cast(token_alignment), + static_cast(routed_tokens)); } std::string to_key() const { return config_key("ep_wgrad", args()); } diff --git a/transformer_engine/pytorch/ops/fused/moe_overlap.py b/transformer_engine/pytorch/ops/fused/moe_overlap.py index 202d27e8ce1..bbf633a05fc 100644 --- a/transformer_engine/pytorch/ops/fused/moe_overlap.py +++ b/transformer_engine/pytorch/ops/fused/moe_overlap.py @@ -77,8 +77,7 @@ class FusedMoE(FusedOperation): primary weights (``quantized_model_init``) under ``MXFP8BlockScaling``. - Contiguous forward inputs. - EP within one NVLink domain. - - ``EpConfig`` ``alignment`` of 256, 128 or (without a recipe) 64, with the receive capacity - a multiple of 256. + - ``EpConfig`` ``alignment`` of 256, with the receive capacity a multiple of 256. - Recipe of none or ``MXFP8BlockScaling``. Notes: @@ -225,6 +224,10 @@ def fuser_forward( buffer.alignment, buffer.total_recv_tokens_i32, **input_kwargs, **scales, **w1_kwargs, )[4] # fmt: skip + # Publish the public counters as the unfused prepare does: the kept tokens per expert and + # the recv total before any drop. + buffer.tokens_per_expert.copy_(tokens_per_expert) + buffer.total_recv_tokens.copy_(buffer.total_recv_tokens_i32) expert_out = torch.empty(rows, hidden, dtype=torch.bfloat16, device=device) result = torch.empty(buffer.num_local_tokens, hidden, dtype=torch.bfloat16, device=device) tex.ep_combine_gemm_fwd( @@ -263,9 +266,6 @@ def _save_for_backward(self, basic_op_ctxs, buffer, row_tensors, other_tensors, num_tokens = buffer.tokens_per_expert_i32.sum(0, keepdim=True, dtype=torch.int32) for tensor in saved_rows: tensor.grouped_tensor_num_tokens = num_tokens - # Publish the kept recv total to the buffer counter paged stashing reads; only needed - # when saving for backward, as stashing is. - buffer.total_recv_tokens.copy_(num_tokens) # CPU offload takes the activations, as the unfused ops do, not the routing weights. # The weight copies saved for backward stay on the GPU, as in TE modules. if is_cpu_offload_enabled(): @@ -447,6 +447,9 @@ def fp8_rows(cols): grad_expert_out, grad_expert_out_scale = fp8_rows(hidden) grad_expert_out_scale = grad_expert_out_scale.view(rows, hidden // _SF_VEC) grad_gemm, grad_gemm_scale = fp8_rows(2 * ffn) + # The columnwise grad_gemm_out feeds the FC1 weight gradient and act_out the FC2 one, so a + # frozen weight reads neither. TODO(phuonguyen): skip the unused one once the cuDNN FE dGLU + # kernel makes its columnwise D output optional (a generate_d_col flag like generate_h). grad_gemm_col, grad_gemm_col_scale = fp8_rows(2 * ffn) act_col, act_col_scale = fp8_rows(ffn) grad_recv_weights = torch.empty(rows, dtype=torch.float32, device=device) @@ -934,6 +937,9 @@ def _moe_overlap_unsupported_reason( if isinstance(recipe, MXFP8BlockScaling): # The SM 10.7 MXFP8 GEMMs have no tail tiles. alignments = (_TILE,) if torch.cuda.get_device_capability() == (10, 7) else (128, _TILE) + # TODO(phuonguyen): the cuDNN FE grouped GEMMs have no tail-tile kernels, so every expert must + # pad to a full 256-row tile. Delete this line to restore 64/128 alignment once tail-tiles land. + alignments = (_TILE,) if config.alignment not in alignments: return f"the EP alignment must be one of {alignments}" if config.zero_copy: @@ -1037,18 +1043,20 @@ def _unsupported_reason(dispatch, fc1, activation, fc2, combine, recipe=None) -> and config.recv_capacity_per_rank == _TILE ): # Some SM 10.7 MXFP8 weight gradients need more than one receive tile; one into - # main_grad counts as added. + # main_grad counts as added. Only a weight that gets a gradient runs such a kernel. from ....common.CuTeDSL.ep_gemm import ( # pylint: disable=import-outside-toplevel wgrad_gemm, ) for fc in (fc1, fc2): + if not (torch.is_grad_enabled() and fc.weight.requires_grad): + continue cfg = wgrad_gemm.WgradConfig( _TILE, fc.out_features, fc.in_features, config.num_local_experts, 1, accumulate=fc._accumulate_into_main_grad, scaling_mode=wgrad_gemm.MXFP8_1D_SCALING, - rows_alignment=config.alignment, - routed_rows=config.max_tokens_per_rank * config.top_k, + token_alignment=config.alignment, + routed_tokens=config.max_tokens_per_rank * config.top_k, ) # fmt: skip try: wgrad_gemm.build_kernel(cfg) From 31efb26951569bfd66c60d096fa523911b2be6fb Mon Sep 17 00:00:00 2001 From: Phuong Nguyen Date: Mon, 30 Nov 2026 20:19:27 -0800 Subject: [PATCH 09/67] Move the EP GEMM checks and wrappers into shared headers and name the tile and MXFP8 constants Signed-off-by: Phuong Nguyen --- transformer_engine/common/ep/ep_gemm_api.cpp | 155 ++++-------------- transformer_engine/common/ep/ep_gemm_config.h | 11 ++ transformer_engine/common/ep/ep_gemm_utils.h | 57 +++++++ transformer_engine/common/util/tensor_utils.h | 85 ++++++++++ 4 files changed, 185 insertions(+), 123 deletions(-) create mode 100644 transformer_engine/common/ep/ep_gemm_utils.h create mode 100644 transformer_engine/common/util/tensor_utils.h diff --git a/transformer_engine/common/ep/ep_gemm_api.cpp b/transformer_engine/common/ep/ep_gemm_api.cpp index 882425eb99e..6cd48bdbea1 100644 --- a/transformer_engine/common/ep/ep_gemm_api.cpp +++ b/transformer_engine/common/ep/ep_gemm_api.cpp @@ -22,8 +22,10 @@ #include "../cast/mxfp8/requantize_mxfp8_cutedsl.cuh" #include "../common.h" #include "../util/cuda_runtime.h" +#include "../util/tensor_utils.h" #include "ep_backend.h" #include "ep_gemm_config.h" +#include "ep_gemm_utils.h" #include "ep_overlap_workspace.h" namespace ep = transformer_engine::ep; @@ -31,89 +33,24 @@ namespace ep = transformer_engine::ep; namespace { constexpr size_t kWorkspaceAlign = 128; -// Rows per GEMM M tile (cluster tile M). Smaller expert alignments end an expert in a tail tile. -constexpr size_t kRowsPerTile = 256; -// GEMM CTA tile N; combine readiness flags cover a multiple of it. -constexpr size_t kTileN = 256; -constexpr size_t kClusterSize = 2; +using ep::check_ep_expert_token_offsets; +using ep::check_ep_mxfp8_dims; +using ep::ep_overlap_scaling_mode; +using ep::kClusterSize; +using ep::kRowsPerTile; +using ep::kTileN; +using transformer_engine::check_mxfp8; +using transformer_engine::check_vector; +using transformer_engine::is_mxfp8; +using transformer_engine::wrap_columnwise; +using transformer_engine::wrap_raw; +using transformer_engine::wrap_rowwise; +using transformer_engine::wrap_scales; size_t align_up(size_t value) { return (value + kWorkspaceAlign - 1) / kWorkspaceAlign * kWorkspaceAlign; } -using transformer_engine::tvm_ffi_bridge::DLTensorWrapper; - -// Operands live on the current device. -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)); -} - -// The operand scaling of a MoE overlap op: BF16 (the delayed default) or MXFP8; any other mode is -// unsupported for now. -NVTEScalingMode overlap_scaling_mode(NVTETensor t) { - const NVTEScalingMode mode = nvte_tensor_scaling_mode(t); - NVTE_CHECK(mode == NVTE_DELAYED_TENSOR_SCALING || mode == NVTE_MXFP8_1D_SCALING, - "the MoE overlap ops support BF16 or MXFP8 operands only, got scaling mode ", - static_cast(mode)); - return mode; -} - -// An MXFP8 operand: E4M3 data with compact or GEMM-swizzled scales. -void check_mxfp8(NVTETensor t, bool swizzled, const char* name) { - NVTE_CHECK(t != nullptr && is_mxfp8(t) && nvte_tensor_type(t) == kNVTEFloat8E4M3, name, - " must be MXFP8 E4M3"); - uint8_t with_swizzled = 0; - nvte_get_tensor_param_v2(t, kNVTEWithGEMMSwizzledScales, &with_swizzled, sizeof(with_swizzled), - nullptr); - NVTE_CHECK((with_swizzled != 0) == swizzled, name, - swizzled ? " needs GEMM-swizzled scales" : " needs compact scales"); -} - -// Shapes the MXFP8 GEMMs take: compact scale rows of whole 16-byte TMA boxes, SwiGLU tiles and -// expert slabs of whole 128-row scale tiles. -void check_mxfp8_dims(size_t hidden, size_t ffn, size_t alignment) { - NVTE_CHECK(hidden % 512 == 0 && ffn % 256 == 0, "MXFP8 needs hidden_dim (", hidden, - ") a multiple of 512 and ffn_dim (", ffn, ") a multiple of 256"); - NVTE_CHECK(alignment >= 128, "MXFP8 needs dispatch_output_per_expert_alignment 128 or ", - kRowsPerTile); -} - // Columns of one combine flag over the whole row: the row rounded up to whole NCCL EP push tiles // (1024 bfloat16 elements, or the row when shorter). NCCL EP takes a chunk past the row as one. size_t whole_row_chunk(size_t n) { @@ -183,34 +120,6 @@ EpGemmContext make_context(const NVTEEpLayerConfig* layer_cfg, int NVTEEpGroupCo return ctx; } -// A caller-owned [num_experts] int32 count tensor. -void check_counts(NVTETensor counts, size_t num_experts, const char* name) { - NVTE_CHECK(counts != nullptr, name, " must not be null"); - NVTE_CHECK(nvte_tensor_shape(counts).ndim == 1 && nvte_tensor_numel(counts) == num_experts && - nvte_tensor_type(counts) == kNVTEInt32, - name, " must be an int32 tensor of ", num_experts, " elements"); -} - -// A caller-owned float32 [rows] tensor. -void check_row_floats(NVTETensor t, size_t rows, const char* name) { - NVTE_CHECK(t != nullptr, name, " must not be null"); - NVTE_CHECK(nvte_tensor_shape(t).ndim == 1 && nvte_tensor_numel(t) == rows && - nvte_tensor_type(t) == kNVTEFloat32, - name, " must be a float32 tensor of recv_capacity (", rows, ") elements"); -} - -// The GEMM reads the per-expert row ends from expert_token_offsets[1:] and requires them 16-byte -// aligned; callers front-pad the [num_experts + 1] int32 layout by 3 elements to achieve that. -void check_expert_token_offsets(const NVTETensor expert_token_offsets, size_t num_experts) { - NVTE_CHECK(nvte_tensor_numel(expert_token_offsets) == num_experts + 1 && - nvte_tensor_type(expert_token_offsets) == kNVTEInt32, - "expert_token_offsets must be an int32 tensor of num_experts + 1 elements"); - const int32_t* row_ends = static_cast(nvte_tensor_data(expert_token_offsets)) + 1; - NVTE_CHECK(reinterpret_cast(row_ends) % 16 == 0, - "expert_token_offsets[1:] (the per-expert row ends) must start 16-byte aligned; " - "front-pad the num_experts + 1 int32 layout by 3 elements"); -} - // Rows: the group capacity, or any multiple of the flag rows in eager mode. void check_rows(const EpGemmContext& ctx, size_t rows, const char* name) { NVTE_CHECK(rows % ctx.signal_unit_tokens() == 0, name, " rows (", rows, @@ -660,12 +569,12 @@ void nvte_ep_dispatch_gemm_fwd(NVTETensor handle_mem, const NVTETensor topk_idx, ctx.group.num_experts / ctx.group.ep_size); NVTE_CHECK(nvte_tensor_shape(act_out).data[1] * 2 == n, "weight rows (", n, ") must be 2 * the act_out columns: SwiGLU"); - check_counts(recv_tokens_per_expert, num_experts, "recv_tokens_per_expert"); - check_row_floats(recv_topk_weights, rows, "recv_topk_weights"); + check_vector(recv_tokens_per_expert, num_experts, kNVTEInt32, "recv_tokens_per_expert"); + check_vector(recv_topk_weights, rows, kNVTEFloat32, "recv_topk_weights"); NVTE_CHECK(total_recv_tokens == nullptr || (nvte_tensor_numel(total_recv_tokens) == 1 && nvte_tensor_type(total_recv_tokens) == kNVTEInt32), "total_recv_tokens must be an int32 tensor of 1 element"); - const NVTEScalingMode scaling_mode = overlap_scaling_mode(tokens); + const NVTEScalingMode scaling_mode = ep_overlap_scaling_mode(tokens); const bool mxfp8 = scaling_mode == NVTE_MXFP8_1D_SCALING; if (mxfp8) { check_mxfp8(tokens, false, "tokens"); @@ -673,7 +582,7 @@ void nvte_ep_dispatch_gemm_fwd(NVTETensor handle_mem, const NVTETensor topk_idx, check_mxfp8(weight, true, "weight"); check_mxfp8(act_out, true, "act_out"); NVTE_CHECK(nvte_tensor_type(gemm_out) == kNVTEBFloat16, "gemm_out must be bfloat16"); - check_mxfp8_dims(hidden, n / 2, ctx.alignment()); + check_ep_mxfp8_dims(hidden, n / 2, ctx.alignment()); } else { NVTE_CHECK( nvte_tensor_type(tokens) == kNVTEBFloat16 && nvte_tensor_type(weight) == kNVTEBFloat16, @@ -700,7 +609,7 @@ void nvte_ep_dispatch_gemm_fwd(NVTETensor handle_mem, const NVTETensor topk_idx, // The GEMM reads the expert row ends from the caller's [num_experts + 1] int32 // expert_token_offsets (expert 0's start, then the per-expert ends); the dispatch writes them in // capacity mode. - check_expert_token_offsets(expert_token_offsets, num_experts); + check_ep_expert_token_offsets(expert_token_offsets, num_experts); scratch.row_ends = static_cast(nvte_tensor_data(expert_token_offsets)) + 1; // The dispatch publishes one flag per slot of rows; the GEMM behind it consumes ready tiles. @@ -788,18 +697,18 @@ void nvte_ep_combine_gemm_fwd(NVTETensor handle_mem, const NVTETensor gemm_in, const size_t n = nvte_tensor_shape(weight).data[1]; check_rows(ctx, rows, "gemm_in"); NVTE_CHECK(nvte_tensor_shape(weight).data[2] == k, "weight columns must equal gemm_in columns"); - const NVTEScalingMode scaling_mode = overlap_scaling_mode(gemm_in); + const NVTEScalingMode scaling_mode = ep_overlap_scaling_mode(gemm_in); const bool mxfp8 = scaling_mode == NVTE_MXFP8_1D_SCALING; if (mxfp8) { check_mxfp8(gemm_in, true, "gemm_in"); check_mxfp8(weight, true, "weight"); - check_mxfp8_dims(n, k, ctx.alignment()); + check_ep_mxfp8_dims(n, k, ctx.alignment()); } else { NVTE_CHECK( nvte_tensor_type(gemm_in) == kNVTEBFloat16 && nvte_tensor_type(weight) == kNVTEBFloat16, "gemm_in and weight must be bfloat16 or MXFP8"); } - check_expert_token_offsets(expert_token_offsets, num_experts); + check_ep_expert_token_offsets(expert_token_offsets, num_experts); const bool weighted = recv_topk_weights != nullptr; NVTE_CHECK(!weighted || (nvte_tensor_type(recv_topk_weights) == kNVTEFloat32 && nvte_tensor_numel(recv_topk_weights) == rows), @@ -870,7 +779,7 @@ void nvte_ep_combine_gemm_bwd( nvte_tensor_shape(grad_gemm_out).data[1] == 2 * ffn, "weight must be [experts, hidden, ffn] with 2 * ffn the gemm_out columns: SwiGLU"); NVTE_CHECK(nvte_tensor_type(gemm_out) == kNVTEBFloat16, "gemm_out must be bfloat16"); - const NVTEScalingMode scaling_mode = overlap_scaling_mode(grad_result); + const NVTEScalingMode scaling_mode = ep_overlap_scaling_mode(grad_result); const bool mxfp8 = scaling_mode == NVTE_MXFP8_1D_SCALING; if (mxfp8) { check_mxfp8(grad_result, false, "grad_result"); @@ -879,16 +788,16 @@ void nvte_ep_combine_gemm_bwd( check_mxfp8(grad_gemm_out, true, "grad_gemm_out"); check_mxfp8(act_out, true, "act_out"); NVTE_CHECK(nvte_tensor_shape(act_out).data[1] == ffn, "act_out must have ffn columns"); - check_mxfp8_dims(hidden, ffn, ctx.alignment()); + check_ep_mxfp8_dims(hidden, ffn, ctx.alignment()); } else { NVTE_CHECK( nvte_tensor_type(grad_result) == kNVTEBFloat16 && nvte_tensor_type(weight) == kNVTEBFloat16, "grad_result and weight must be bfloat16 or MXFP8"); NVTE_CHECK(act_out == nullptr, "act_out is written for MXFP8 only"); } - check_counts(recv_tokens_per_expert, num_experts, "recv_tokens_per_expert"); - check_row_floats(recv_topk_weights, rows, "recv_topk_weights"); - check_row_floats(grad_recv_topk_weights, rows, "grad_recv_topk_weights"); + check_vector(recv_tokens_per_expert, num_experts, kNVTEInt32, "recv_tokens_per_expert"); + check_vector(recv_topk_weights, rows, kNVTEFloat32, "recv_topk_weights"); + check_vector(grad_recv_topk_weights, rows, kNVTEFloat32, "grad_recv_topk_weights"); // The MXFP8 weight gradient reads the columnwise grad_expert_out that this call writes. const bool requant = @@ -1004,16 +913,16 @@ void nvte_ep_dispatch_gemm_bwd(NVTETensor handle_mem, const NVTETensor grad_gemm check_rows(ctx, rows, "grad_gemm_out"); NVTE_CHECK(nvte_tensor_shape(weight).data[1] == k && nvte_tensor_shape(weight).data[2] == hidden, "weight must be [experts, 2 * ffn, hidden]"); - check_counts(recv_tokens_per_expert, num_experts, "recv_tokens_per_expert"); - check_row_floats(grad_recv_topk_weights, rows, "grad_recv_topk_weights"); - const NVTEScalingMode scaling_mode = overlap_scaling_mode(grad_gemm_out); + check_vector(recv_tokens_per_expert, num_experts, kNVTEInt32, "recv_tokens_per_expert"); + check_vector(grad_recv_topk_weights, rows, kNVTEFloat32, "grad_recv_topk_weights"); + const NVTEScalingMode scaling_mode = ep_overlap_scaling_mode(grad_gemm_out); const bool mxfp8 = scaling_mode == NVTE_MXFP8_1D_SCALING; if (mxfp8) { check_mxfp8(grad_gemm_out, true, "grad_gemm_out"); check_mxfp8(weight, true, "weight"); NVTE_CHECK(nvte_tensor_type(grad_recv_tokens) == kNVTEBFloat16, "grad_recv_tokens must be bfloat16"); - check_mxfp8_dims(hidden, k / 2, ctx.alignment()); + check_ep_mxfp8_dims(hidden, k / 2, ctx.alignment()); } else { NVTE_CHECK(nvte_tensor_type(grad_gemm_out) == kNVTEBFloat16 && nvte_tensor_type(weight) == kNVTEBFloat16, diff --git a/transformer_engine/common/ep/ep_gemm_config.h b/transformer_engine/common/ep/ep_gemm_config.h index 3e76e4fa850..d839acfb76e 100644 --- a/transformer_engine/common/ep/ep_gemm_config.h +++ b/transformer_engine/common/ep/ep_gemm_config.h @@ -27,6 +27,17 @@ namespace transformer_engine { namespace ep { +// Rows per GEMM M tile (cluster tile M). Smaller expert alignments end an expert in a tail tile. +constexpr size_t kRowsPerTile = 256; +// GEMM CTA tile N; combine readiness flags cover a multiple of it. +constexpr size_t kTileN = 256; +constexpr size_t kClusterSize = 2; + +// MXFP8 GEMM shape requirements: hidden and ffn dims, and the smallest expert row alignment. +constexpr size_t kMxfp8HiddenMultiple = 512; +constexpr size_t kMxfp8FfnMultiple = 256; +constexpr size_t kMxfp8MinAlignment = 128; + // Signal-aware grouped GEMMs (CuTeDSL via TVM-FFI), keyed by configuration. The first // get_kernel of a configuration compiles: call it at warmup, outside graph capture. diff --git a/transformer_engine/common/ep/ep_gemm_utils.h b/transformer_engine/common/ep/ep_gemm_utils.h new file mode 100644 index 00000000000..af34b9591b2 --- /dev/null +++ b/transformer_engine/common/ep/ep_gemm_utils.h @@ -0,0 +1,57 @@ +/************************************************************************* + * Copyright (c) 2022-2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * + * See LICENSE for license information. + ************************************************************************/ + +#ifndef TRANSFORMER_ENGINE_COMMON_EP_EP_GEMM_UTILS_H_ +#define TRANSFORMER_ENGINE_COMMON_EP_EP_GEMM_UTILS_H_ + +#include + +#include +#include + +#include "../util/logging.h" +#include "ep_gemm_config.h" + +namespace transformer_engine { +namespace ep { + +// The operand scaling of a MoE overlap op: BF16 (the delayed default) or MXFP8; any other mode is +// unsupported for now. +inline NVTEScalingMode ep_overlap_scaling_mode(NVTETensor t) { + const NVTEScalingMode mode = nvte_tensor_scaling_mode(t); + NVTE_CHECK(mode == NVTE_DELAYED_TENSOR_SCALING || mode == NVTE_MXFP8_1D_SCALING, + "the MoE overlap ops support BF16 or MXFP8 operands only, got scaling mode ", + static_cast(mode)); + return mode; +} + +// Shapes the MXFP8 GEMMs take: compact scale rows of whole 16-byte TMA boxes, SwiGLU tiles and +// expert slabs of whole 128-row scale tiles. +inline void check_ep_mxfp8_dims(size_t hidden, size_t ffn, size_t alignment) { + NVTE_CHECK(hidden % kMxfp8HiddenMultiple == 0 && ffn % kMxfp8FfnMultiple == 0, + "MXFP8 needs hidden_dim (", hidden, ") a multiple of ", kMxfp8HiddenMultiple, + " and ffn_dim (", ffn, ") a multiple of ", kMxfp8FfnMultiple); + NVTE_CHECK(alignment >= kMxfp8MinAlignment, "MXFP8 needs dispatch_output_per_expert_alignment ", + kMxfp8MinAlignment, " or ", kRowsPerTile); +} + +// The GEMM reads the per-expert row ends from expert_token_offsets[1:] and requires them 16-byte +// aligned; callers front-pad the [num_experts + 1] int32 layout by 3 elements to achieve that. +inline void check_ep_expert_token_offsets(const NVTETensor expert_token_offsets, + size_t num_experts) { + NVTE_CHECK(nvte_tensor_numel(expert_token_offsets) == num_experts + 1 && + nvte_tensor_type(expert_token_offsets) == kNVTEInt32, + "expert_token_offsets must be an int32 tensor of num_experts + 1 elements"); + const int32_t *row_ends = static_cast(nvte_tensor_data(expert_token_offsets)) + 1; + NVTE_CHECK(reinterpret_cast(row_ends) % 16 == 0, + "expert_token_offsets[1:] (the per-expert row ends) must start 16-byte aligned; " + "front-pad the num_experts + 1 int32 layout by 3 elements"); +} + +} // namespace ep +} // namespace transformer_engine + +#endif // TRANSFORMER_ENGINE_COMMON_EP_EP_GEMM_UTILS_H_ diff --git a/transformer_engine/common/util/tensor_utils.h b/transformer_engine/common/util/tensor_utils.h new file mode 100644 index 00000000000..4ddec7e517e --- /dev/null +++ b/transformer_engine/common/util/tensor_utils.h @@ -0,0 +1,85 @@ +/************************************************************************* + * Copyright (c) 2022-2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * + * See LICENSE for license information. + ************************************************************************/ + +#ifndef TRANSFORMER_ENGINE_COMMON_UTIL_TENSOR_UTILS_H_ +#define TRANSFORMER_ENGINE_COMMON_UTIL_TENSOR_UTILS_H_ + +#include + +#include +#include + +#include "../common.h" +#include "../tvm_ffi_bridge.h" +#include "cuda_runtime.h" +#include "logging.h" + +namespace transformer_engine { + +using tvm_ffi_bridge::DLTensorWrapper; + +// Operands live on the current device. +inline DLTensorWrapper wrap_data(const NVTEBasicTensor &data, bool flatten_2d) { + return DLTensorWrapper(data, flatten_2d, cuda::current_device()); +} + +inline 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); +} + +inline 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. +inline 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. +inline 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); +} + +inline bool is_mxfp8(NVTETensor t) { return is_mxfp8_scaling(nvte_tensor_scaling_mode(t)); } + +// An MXFP8 operand: E4M3 data with compact or GEMM-swizzled scales. +inline void check_mxfp8(NVTETensor t, bool swizzled, const char *name) { + NVTE_CHECK(t != nullptr && is_mxfp8(t) && nvte_tensor_type(t) == kNVTEFloat8E4M3, name, + " must be MXFP8 E4M3"); + uint8_t with_swizzled = 0; + nvte_get_tensor_param_v2(t, kNVTEWithGEMMSwizzledScales, &with_swizzled, sizeof(with_swizzled), + nullptr); + NVTE_CHECK((with_swizzled != 0) == swizzled, name, + swizzled ? " needs GEMM-swizzled scales" : " needs compact scales"); +} + +// A caller-owned 1-D tensor of numel elements of the given dtype. +inline void check_vector(NVTETensor t, size_t numel, NVTEDType dtype, const char *name) { + NVTE_CHECK(t != nullptr, name, " must not be null"); + NVTE_CHECK(nvte_tensor_shape(t).ndim == 1 && nvte_tensor_numel(t) == numel && + nvte_tensor_type(t) == dtype, + name, " must be a 1-D ", to_string(static_cast(dtype)), " tensor of ", numel, + " elements"); +} + +} // namespace transformer_engine + +#endif // TRANSFORMER_ENGINE_COMMON_UTIL_TENSOR_UTILS_H_ From 7eeff64620af3716b2582a6a118b3bb3e96cd00f Mon Sep 17 00:00:00 2001 From: Phuong Nguyen Date: Mon, 30 Nov 2026 20:19:27 -0800 Subject: [PATCH 10/67] Pass MXFP8 tensors to the EP overlap GEMMs, require glu_interleave_size 32 and check runtime settings at execution Signed-off-by: Phuong Nguyen --- transformer_engine/common/__init__.py | 9 + .../pytorch/csrc/extensions/ep.cpp | 594 ++++++++-------- transformer_engine/pytorch/ep.py | 86 +-- .../pytorch/ops/fused/moe_overlap.py | 633 ++++++++---------- transformer_engine/pytorch/ops/fuser.py | 13 +- 5 files changed, 593 insertions(+), 742 deletions(-) diff --git a/transformer_engine/common/__init__.py b/transformer_engine/common/__init__.py index 1c55083f34b..9ac9c98e0b6 100644 --- a/transformer_engine/common/__init__.py +++ b/transformer_engine/common/__init__.py @@ -495,6 +495,15 @@ def _load_core_library(): return ctypes.CDLL(_get_shared_object_file("core"), mode=ctypes.RTLD_GLOBAL | os.RTLD_LAZY) +@functools.lru_cache(maxsize=None) +def cutedsl_backend_built() -> bool: + """Whether the core library was built with the CuTeDSL backend.""" + core = _load_core_library() + return hasattr(core, "nvte_is_cutedsl_backend_built") and bool( + core.nvte_is_cutedsl_backend_built() + ) + + if "NVTE_PROJECT_BUILDING" not in os.environ or bool(int(os.getenv("NVTE_RELEASE_BUILD", "0"))): sanity_checks_for_pypi_installation() diff --git a/transformer_engine/pytorch/csrc/extensions/ep.cpp b/transformer_engine/pytorch/csrc/extensions/ep.cpp index 51e93b873da..019f9c6d666 100644 --- a/transformer_engine/pytorch/csrc/extensions/ep.cpp +++ b/transformer_engine/pytorch/csrc/extensions/ep.cpp @@ -42,6 +42,7 @@ #include "../common.h" #include "../extensions.h" +#include "../pybind.h" #include "transformer_engine/gemm.h" namespace transformer_engine::pytorch { @@ -197,72 +198,88 @@ size_t check_mxfp8_scale_pair(const at::Tensor& send_scale, const at::Tensor& re return sc_cols; } -// MXFP8 TE tensor of E4M3 rowwise and/or columnwise data (undefined: absent) and E8M0 scales. -TensorWrapper make_mxfp8_tensor(const at::Tensor& rowwise, const at::Tensor& rowwise_scale_inv, - const at::Tensor& columnwise, - const at::Tensor& columnwise_scale_inv, bool swizzled) { - TensorWrapper t(NVTE_MXFP8_1D_SCALING); - for (const bool col : {false, true}) { - const at::Tensor& data = col ? columnwise : rowwise; - const at::Tensor& scale_inv = col ? columnwise_scale_inv : rowwise_scale_inv; - if (!data.defined()) { +// Whether an operand of the overlapped ops is an MXFP8 tensor; otherwise it is a torch tensor. +bool is_mxfp8_object(const py::object& obj) { return detail::IsMXFP8Tensor(obj.ptr()); } + +// Torch tensor of an MXFP8 tensor attribute, undefined when absent. +at::Tensor mxfp8_part(const py::object& obj, const char* name) { + py::object part = obj.attr(name); + return part.is_none() ? at::Tensor() : part.cast(); +} + +// Window of a symm-mem input: its data and, for an MXFP8 tensor, its scales. +NVTECommWindow make_input_window(const py::object& input) { + if (!is_mxfp8_object(input)) { + return make_input_window(input.cast(), std::nullopt); + } + return make_input_window(mxfp8_part(input, "_rowwise_data"), + mxfp8_part(input, "_rowwise_scale_inv")); +} + +// TE tensor of an operand; an MXFP8 operand carries its own data, scales and scale layout. +TensorWrapper operand_tensor(const py::object& obj) { + return makeTransformerEngineTensor(obj, py::none()); +} + +// TE tensor of a weight [num_experts, out_features, in_features]. An MXFP8 weight carries flat +// data, whose shape is set here from the experts and the input features. +TensorWrapper weight_operand(const py::object& weight, size_t num_experts, size_t in_features) { + TensorWrapper t = operand_tensor(weight); + if (!is_mxfp8_object(weight)) { + return t; + } + for (const bool columnwise : {false, true}) { + const NVTEBasicTensor data = + nvte_get_tensor_param(t.data(), columnwise ? kNVTEColumnwiseData : kNVTERowwiseData); + if (data.data_ptr == nullptr) { continue; } - NVTE_CHECK(data.scalar_type() == at::kFloat8_e4m3fn && data.is_contiguous() && - scale_inv.defined() && scale_inv.is_contiguous() && - scale_inv.element_size() == 1, - "MXFP8 operands need contiguous E4M3 data and contiguous one-byte E8M0 scales"); - if (col) { - t.set_columnwise_data(data.data_ptr(), DType::kFloat8E4M3, getTensorShape(data)); - t.set_columnwise_scale_inv(scale_inv.data_ptr(), DType::kFloat8E8M0, - getTensorShape(scale_inv)); + size_t numel = 1; + for (size_t i = 0; i < data.shape.ndim; ++i) { + numel *= data.shape.data[i]; + } + NVTE_CHECK(numel % (num_experts * in_features) == 0, "MXFP8 weight with ", numel, + " elements is not [", num_experts, ", out_features, ", in_features, "]"); + const std::vector shape = {num_experts, numel / (num_experts * in_features), + in_features}; + if (columnwise) { + t.set_columnwise_data(data.data_ptr, DType::kFloat8E4M3, shape); } else { - t.set_rowwise_data(data.data_ptr(), DType::kFloat8E4M3, getTensorShape(data)); - t.set_rowwise_scale_inv(scale_inv.data_ptr(), DType::kFloat8E8M0, getTensorShape(scale_inv)); + t.set_rowwise_data(data.data_ptr, DType::kFloat8E4M3, shape); } } - t.set_with_gemm_swizzled_scales(swizzled); return t; } -// Columnwise-only MXFP8 TE tensor with GEMM-swizzled scales. -TensorWrapper make_columnwise_mxfp8_tensor(const at::Tensor& data, const at::Tensor& scale_inv) { - return make_mxfp8_tensor(at::Tensor(), at::Tensor(), data, scale_inv, true); -} - -// Rowwise MXFP8 TE tensor when scale_inv is given, else the plain tensor. -TensorWrapper make_maybe_mxfp8_tensor(const at::Tensor& data, - const std::optional& scale_inv, bool swizzled) { - if (!scale_inv.has_value()) { - return makeTransformerEngineTensor(data); +// The EP backend reads the rowwise scales of an MXFP8 input as [rows, cols / 32], without the +// 128-row padding of the quantizer's scale tensor. +TensorWrapper compact_scales_operand(const py::object& obj) { + TensorWrapper t = operand_tensor(obj); + if (is_mxfp8_object(obj)) { + const NVTEShape shape = t.shape(); + size_t rows = 1; + for (size_t i = 0; i + 1 < shape.ndim; ++i) { + rows *= shape.data[i]; + } + const NVTEBasicTensor scales = nvte_get_tensor_param(t.data(), kNVTERowwiseScaleInv); + t.set_rowwise_scale_inv(scales.data_ptr, DType::kFloat8E8M0, + std::vector{rows, shape.data[shape.ndim - 1] / 32}); } - return make_mxfp8_tensor(data, *scale_inv, at::Tensor(), at::Tensor(), swizzled); + return t; } // Optional weight gradient of an overlapped backward GEMM and the activations it reads: plain, or -// columnwise MXFP8 data with its GEMM-swizzled scales. +// columnwise MXFP8 data with its GEMM-swizzled scales. An input that also holds rowwise data is the +// one the call requantizes into its columnwise copy. class WeightGradTensors { public: - // input_rowwise: the rowwise MXFP8 input the call requantizes into the columnwise input. - WeightGradTensors(const std::optional& input, - const std::optional& weight_grad, - const std::optional& input_scale_inv = std::nullopt, - const std::optional& input_rowwise = std::nullopt, - const std::optional& input_rowwise_scale_inv = std::nullopt) + WeightGradTensors(const std::optional& input, + const std::optional& weight_grad) : enabled_(weight_grad.has_value()) { NVTE_CHECK(input.has_value() == enabled_, "wgrad_input and weight_grad must be given together"); - NVTE_CHECK(enabled_ || !input_scale_inv.has_value(), "wgrad_input_scale_inv needs weight_grad"); - NVTE_CHECK(input_rowwise.has_value() == input_rowwise_scale_inv.has_value() && - (input_scale_inv.has_value() || !input_rowwise.has_value()), - "the rowwise wgrad_input needs its scales and a columnwise MXFP8 wgrad_input"); if (enabled_) { - NVTE_CHECK(input->is_contiguous() && weight_grad->is_contiguous(), - "wgrad_input and weight_grad must be contiguous"); - input_ = input_scale_inv.has_value() - ? make_mxfp8_tensor(input_rowwise.value_or(at::Tensor()), - input_rowwise_scale_inv.value_or(at::Tensor()), *input, - *input_scale_inv, true) - : makeTransformerEngineTensor(*input); + NVTE_CHECK(weight_grad->is_contiguous(), "weight_grad must be contiguous"); + input_ = operand_tensor(*input); output_ = makeTransformerEngineTensor(*weight_grad); } } @@ -298,6 +315,32 @@ void check_cuda_operands(std::initializer_list operands) { } } +// A torch tensor or the tensors of an MXFP8 tensor: contiguous on the current CUDA device. +void check_cuda_object(const char* name, const py::object& obj) { + std::vector parts; + if (is_mxfp8_object(obj)) { + for (const char* part : + {"_rowwise_data", "_rowwise_scale_inv", "_columnwise_data", "_columnwise_scale_inv"}) { + if (at::Tensor t = mxfp8_part(obj, part); t.defined()) { + parts.push_back(t); + } + } + } else { + parts.push_back(obj.cast()); + } + for (const at::Tensor& t : parts) { + NVTE_CHECK( + t.is_cuda() && t.device().index() == c10::cuda::current_device() && t.is_contiguous(), name, + " must be contiguous tensors on the current CUDA device"); + } +} + +void check_cuda_object(const char* name, const std::optional& obj) { + if (obj.has_value()) { + check_cuda_object(name, *obj); + } +} + } // namespace bool ep_get_zero_copy() { return g_zero_copy_enabled.load(std::memory_order_relaxed); } @@ -861,90 +904,57 @@ at::Tensor overlap_workspace(int64_t hidden_dim, int64_t ffn_dim, int64_t num_lo return at::empty({bytes}, like.options().dtype(at::kByte)); } -std::vector ep_dispatch_gemm_fwd( - at::Tensor handle_mem, at::Tensor topk_idx, at::Tensor tokens, at::Tensor topk_weights, - at::Tensor weight, std::optional recv_tokens_opt, - std::optional recv_topk_weights_opt, at::Tensor tokens_per_expert, - std::optional gemm_out_opt, std::optional act_out_opt, int64_t top_k, - int64_t dispatch_output_per_expert_alignment, std::optional total_recv_tokens, - int64_t eager_row_bucket, std::optional tokens_scale_inv, - std::optional recv_scale_inv, std::optional weight_scale_inv, - std::optional act_out_scale_inv, bool symm_input) { +// MXFP8 operands are MXFP8 tensors (their data, scales and scale layout travel with them), BF16 +// ones torch tensors; every operand of a call is of the one kind. The weights are +// [experts, out_features, in_features]. +at::Tensor ep_dispatch_gemm_fwd(at::Tensor handle_mem, at::Tensor topk_idx, py::object tokens, + at::Tensor topk_weights, py::object weight, py::object recv_tokens, + at::Tensor recv_topk_weights, at::Tensor tokens_per_expert, + at::Tensor gemm_out, py::object act_out, int64_t top_k, + int64_t dispatch_output_per_expert_alignment, + std::optional total_recv_tokens, bool symm_input) { check_cuda_operands({{"handle_mem", operand(handle_mem)}, {"topk_idx", operand(topk_idx)}, - {"tokens", operand(tokens)}, {"topk_weights", operand(topk_weights)}, - {"weight", operand(weight)}, - {"recv_tokens", operand(recv_tokens_opt)}, - {"recv_topk_weights", operand(recv_topk_weights_opt)}, + {"recv_topk_weights", operand(recv_topk_weights)}, {"tokens_per_expert", operand(tokens_per_expert)}, - {"gemm_out", operand(gemm_out_opt)}, - {"act_out", operand(act_out_opt)}, - {"tokens_scale_inv", operand(tokens_scale_inv)}, - {"recv_scale_inv", operand(recv_scale_inv)}, - {"weight_scale_inv", operand(weight_scale_inv)}, - {"act_out_scale_inv", operand(act_out_scale_inv)}}); + {"gemm_out", operand(gemm_out)}}); + check_cuda_object("tokens", tokens); + check_cuda_object("weight", weight); + check_cuda_object("recv_tokens", recv_tokens); + check_cuda_object("act_out", act_out); auto stream = at::cuda::getCurrentCUDAStream().stream(); - const bool eager = !recv_tokens_opt.has_value(); - NVTE_CHECK(recv_topk_weights_opt.has_value() != eager && gemm_out_opt.has_value() != eager && - act_out_opt.has_value() != eager, - "pass all of the recv and GEMM outputs, or none (eager)"); - const bool mxfp8 = tokens_scale_inv.has_value(); - NVTE_CHECK(weight_scale_inv.has_value() == mxfp8 && - recv_scale_inv.has_value() == (mxfp8 && !eager) && - act_out_scale_inv.has_value() == (mxfp8 && !eager), - "pass all of the MXFP8 scales, or none; eager allocates the output scales"); + const bool mxfp8 = is_mxfp8_object(tokens); + NVTE_CHECK(is_mxfp8_object(weight) == mxfp8 && is_mxfp8_object(recv_tokens) == mxfp8 && + is_mxfp8_object(act_out) == mxfp8, + "pass all of tokens, weight, recv_tokens and act_out as MXFP8 tensors, or none"); NVTE_CHECK(!total_recv_tokens.has_value() || total_recv_tokens->scalar_type() == at::kInt, "total_recv_tokens must be int32"); NVTE_CHECK(!total_recv_tokens.has_value() || total_recv_tokens->is_pinned() || (total_recv_tokens->is_cuda() && total_recv_tokens->device().index() == c10::cuda::current_device()), "total_recv_tokens must be pinned host memory or on the current CUDA device"); - at::Tensor recv_tokens, recv_topk_weights, gemm_out, act_out; - if (eager) { - // Prepare, read the recv total on the host and size the outputs to whole row buckets, all - // in this call; the fused entry then skips the prepare. - NVTE_CHECK(total_recv_tokens.has_value() && total_recv_tokens->is_pinned(), - "eager needs total_recv_tokens in pinned host memory"); - NVTE_CHECK(eager_row_bucket > 0, "eager needs eager_row_bucket > 0"); - ep_prepare(handle_mem, topk_idx, tokens_per_expert, top_k, dispatch_output_per_expert_alignment, - *total_recv_tokens); - NVTE_CHECK_CUDA(cudaStreamSynchronize(stream)); - const int64_t total = *total_recv_tokens->data_ptr(); - const int64_t buckets = std::max((total + eager_row_bucket - 1) / eager_row_bucket, 1); - const int64_t rows = buckets * eager_row_bucket; - const int64_t hidden = tokens.size(1); - const int64_t ffn = weight.size(1) / 2; - recv_tokens = at::empty({rows, hidden}, tokens.options()); - recv_topk_weights = at::empty({rows}, topk_weights.options()); - gemm_out = at::empty({rows, 2 * ffn}, tokens.options().dtype(at::kBFloat16)); - act_out = at::empty({rows, ffn}, tokens.options()); - if (mxfp8) { - const int64_t scale_cols = tokens_scale_inv->size(-1); - NVTE_CHECK(scale_cols > 0 && hidden % scale_cols == 0, "eager MXFP8 tokens_scale_inv cols (", - scale_cols, ") must be a non-zero divisor of hidden (", hidden, ")"); - const int64_t block = hidden / scale_cols; - recv_scale_inv = at::empty({rows, scale_cols}, tokens_scale_inv->options()); - act_out_scale_inv = at::empty({rows * ffn / block}, tokens_scale_inv->options()); - } - } else { - recv_tokens = *recv_tokens_opt; - recv_topk_weights = *recv_topk_weights_opt; - gemm_out = *gemm_out_opt; - act_out = *act_out_opt; - } - NVTE_CHECK(tokens.is_contiguous() && recv_tokens.is_contiguous() && weight.is_contiguous() && - gemm_out.is_contiguous() && act_out.is_contiguous(), - "operands must be contiguous"); - const int64_t recv_rows = recv_tokens.size(0); - NVTE_CHECK(tokens.dim() == 2 && weight.dim() == 3 && weight.size(1) % 2 == 0 && - weight.size(2) == tokens.size(1), + NVTE_CHECK(gemm_out.is_contiguous(), "gemm_out must be contiguous"); + auto tokens_te = compact_scales_operand(tokens); + auto weight_te = weight_operand(weight, tokens_per_expert.numel(), tokens_te.shape().data[1]); + auto recv_tokens_te = operand_tensor(recv_tokens); + auto act_out_te = operand_tensor(act_out); + const NVTEShape tokens_shape = tokens_te.shape(); + const NVTEShape weight_shape = weight_te.shape(); + const NVTEShape recv_shape = recv_tokens_te.shape(); + const NVTEShape act_shape = act_out_te.shape(); + const int64_t hidden = tokens_shape.ndim == 2 ? tokens_shape.data[1] : 0; + NVTE_CHECK(tokens_shape.ndim == 2 && weight_shape.ndim == 3 && weight_shape.data[1] % 2 == 0 && + weight_shape.data[2] == static_cast(hidden), "tokens must be [num_tokens, hidden] and weight [experts, 2 * ffn, hidden]"); - NVTE_CHECK(recv_tokens.dim() == 2 && recv_tokens.size(1) == tokens.size(1) && + const int64_t num_experts = weight_shape.data[0]; + const int64_t ffn = weight_shape.data[1] / 2; + const int64_t recv_rows = recv_shape.ndim == 2 ? recv_shape.data[0] : 0; + NVTE_CHECK(recv_shape.ndim == 2 && recv_shape.data[1] == static_cast(hidden) && recv_topk_weights.numel() == recv_rows && gemm_out.dim() == 2 && - gemm_out.size(0) == recv_rows && gemm_out.size(1) == weight.size(1) && - act_out.dim() == 2 && act_out.size(0) == recv_rows && - act_out.size(1) == weight.size(1) / 2, + gemm_out.size(0) == recv_rows && gemm_out.size(1) == 2 * ffn && + act_shape.ndim == 2 && act_shape.data[0] == static_cast(recv_rows) && + act_shape.data[1] == static_cast(ffn), "recv_tokens, recv_topk_weights, gemm_out and act_out must have the rows of the " "recv buffer and the hidden, 2 * ffn and ffn columns of the operands"); check_dense_cuda(tokens_per_expert, "tokens_per_expert"); @@ -953,188 +963,152 @@ std::vector ep_dispatch_gemm_fwd( // Front-pad by 3 so the row ends (expert_token_offsets[1:]) start 16-byte aligned, as the GEMM // needs. auto expert_token_offsets = - at::empty({weight.size(0) + 4}, tokens.options().dtype(at::kInt)).slice(0, 3); + at::empty({num_experts + 4}, tokens_per_expert.options().dtype(at::kInt)).slice(0, 3); auto handle_mem_te = makeTransformerEngineTensor(handle_mem); auto topk_idx_te = makeTransformerEngineTensor(topk_idx); - auto tokens_te = make_maybe_mxfp8_tensor(tokens, tokens_scale_inv, false); auto topk_weights_te = makeTransformerEngineTensor(topk_weights); - auto weight_te = make_maybe_mxfp8_tensor(weight, weight_scale_inv, true); - auto recv_tokens_te = make_maybe_mxfp8_tensor(recv_tokens, recv_scale_inv, false); auto recv_topk_weights_te = makeTransformerEngineTensor(recv_topk_weights); auto tokens_per_expert_te = makeTransformerEngineTensor(tokens_per_expert); auto gemm_out_te = makeTransformerEngineTensor(gemm_out); - auto act_out_te = make_maybe_mxfp8_tensor(act_out, act_out_scale_inv, true); auto expert_token_offsets_te = makeTransformerEngineTensor(expert_token_offsets); - // In eager mode the prepare above wrote the total. - const bool report_total = total_recv_tokens.has_value() && !eager; + // Eager: the prepare before this call wrote the total. TensorWrapper total_recv_tokens_te; - if (report_total) { + if (total_recv_tokens.has_value()) { total_recv_tokens_te = makeTransformerEngineTensor(*total_recv_tokens); } - const NVTECommWindow tokens_win = - symm_input ? make_input_window(tokens, tokens_scale_inv) : kNoWindow; + const NVTECommWindow tokens_win = symm_input ? make_input_window(tokens) : kNoWindow; auto layer_cfg = make_layer_cfg(top_k, dispatch_output_per_expert_alignment, get_contiguous_topk_idx_te_dtype(topk_idx)); - // Forward: no weight gradient. ffn is half the FC1 output rows (gate and up). - auto workspace_t = overlap_workspace(tokens.size(1), weight.size(1) / 2, weight.size(0), - recv_tokens.size(0), false, mxfp8, layer_cfg, tokens); + // Forward: no weight gradient. + auto workspace_t = overlap_workspace(hidden, ffn, num_experts, recv_rows, false, mxfp8, layer_cfg, + tokens_per_expert); auto workspace_te = makeTransformerEngineTensor(workspace_t); - nvte_ep_dispatch_gemm_fwd(handle_mem_te.data(), topk_idx_te.data(), tokens_te.data(), tokens_win, - topk_weights_te.data(), weight_te.data(), recv_tokens_te.data(), - recv_topk_weights_te.data(), gemm_out_te.data(), act_out_te.data(), - tokens_per_expert_te.data(), expert_token_offsets_te.data(), - report_total ? total_recv_tokens_te.data() : nullptr, - workspace_te.data(), NVTE_Activation_Type::SWIGLU, &layer_cfg, stream); - if (mxfp8) { - return {recv_tokens, recv_topk_weights, gemm_out, act_out, - expert_token_offsets, *recv_scale_inv, *act_out_scale_inv}; + { + py::gil_scoped_release release; + nvte_ep_dispatch_gemm_fwd( + handle_mem_te.data(), topk_idx_te.data(), tokens_te.data(), tokens_win, + topk_weights_te.data(), weight_te.data(), recv_tokens_te.data(), + recv_topk_weights_te.data(), gemm_out_te.data(), act_out_te.data(), + tokens_per_expert_te.data(), expert_token_offsets_te.data(), + total_recv_tokens.has_value() ? total_recv_tokens_te.data() : nullptr, workspace_te.data(), + NVTE_Activation_Type::SWIGLU, &layer_cfg, stream); } - return {recv_tokens, recv_topk_weights, gemm_out, act_out, expert_token_offsets}; + return expert_token_offsets; } -void ep_combine_gemm_fwd(at::Tensor handle_mem, at::Tensor gemm_in, at::Tensor expert_token_offsets, - at::Tensor weight, at::Tensor expert_out, at::Tensor result, int64_t top_k, +void ep_combine_gemm_fwd(at::Tensor handle_mem, py::object gemm_in, at::Tensor expert_token_offsets, + py::object weight, at::Tensor expert_out, at::Tensor result, int64_t top_k, int64_t dispatch_output_per_expert_alignment, - at::ScalarType topk_idx_dtype, std::optional recv_topk_weights, - std::optional gemm_in_scale_inv, - std::optional weight_scale_inv) { + at::ScalarType topk_idx_dtype, + std::optional recv_topk_weights) { check_cuda_operands({{"handle_mem", operand(handle_mem)}, - {"gemm_in", operand(gemm_in)}, {"expert_token_offsets", operand(expert_token_offsets)}, - {"weight", operand(weight)}, {"expert_out", operand(expert_out)}, {"result", operand(result)}, - {"recv_topk_weights", operand(recv_topk_weights)}, - {"gemm_in_scale_inv", operand(gemm_in_scale_inv)}, - {"weight_scale_inv", operand(weight_scale_inv)}}); + {"recv_topk_weights", operand(recv_topk_weights)}}); + check_cuda_object("gemm_in", gemm_in); + check_cuda_object("weight", weight); auto stream = at::cuda::getCurrentCUDAStream().stream(); - NVTE_CHECK(gemm_in.is_contiguous() && weight.is_contiguous() && expert_out.is_contiguous() && - result.is_contiguous(), - "operands must be contiguous"); - NVTE_CHECK(gemm_in.dim() == 2 && weight.dim() == 3 && weight.size(2) == gemm_in.size(1) && - expert_out.dim() == 2 && expert_out.size(0) == gemm_in.size(0) && - expert_out.size(1) == weight.size(1) && result.dim() == 2 && - result.size(1) == weight.size(1), + const bool mxfp8 = is_mxfp8_object(gemm_in); + NVTE_CHECK(is_mxfp8_object(weight) == mxfp8, + "pass gemm_in and weight as MXFP8 tensors, or both as torch tensors"); + NVTE_CHECK(expert_out.is_contiguous() && result.is_contiguous(), "operands must be contiguous"); + auto gemm_in_te = operand_tensor(gemm_in); + auto weight_te = + weight_operand(weight, expert_token_offsets.numel() - 1, gemm_in_te.shape().data[1]); + const NVTEShape gemm_in_shape = gemm_in_te.shape(); + const NVTEShape weight_shape = weight_te.shape(); + NVTE_CHECK(gemm_in_shape.ndim == 2 && weight_shape.ndim == 3 && + weight_shape.data[2] == gemm_in_shape.data[1] && expert_out.dim() == 2 && + expert_out.size(0) == static_cast(gemm_in_shape.data[0]) && + expert_out.size(1) == static_cast(weight_shape.data[1]) && + result.dim() == 2 && result.size(1) == static_cast(weight_shape.data[1]), "gemm_in must be [rows, ffn], weight [experts, hidden, ffn], expert_out [rows, " "hidden] and result [num_tokens, hidden]"); check_dense_cuda(expert_token_offsets, "expert_token_offsets"); - NVTE_CHECK(gemm_in_scale_inv.has_value() == weight_scale_inv.has_value(), - "pass both MXFP8 scales, or none"); auto handle_mem_te = makeTransformerEngineTensor(handle_mem); - auto gemm_in_te = make_maybe_mxfp8_tensor(gemm_in, gemm_in_scale_inv, true); TensorWrapper recv_topk_weights_te; if (recv_topk_weights.has_value()) { recv_topk_weights_te = makeTransformerEngineTensor(*recv_topk_weights); } auto expert_token_offsets_te = makeTransformerEngineTensor(expert_token_offsets); - auto weight_te = make_maybe_mxfp8_tensor(weight, weight_scale_inv, true); auto expert_out_te = makeTransformerEngineTensor(expert_out); auto result_te = makeTransformerEngineTensor(result); auto layer_cfg = make_layer_cfg(top_k, dispatch_output_per_expert_alignment, get_topk_idx_te_dtype(topk_idx_dtype)); // FC2 weight is [experts, hidden, ffn]; the combine GEMM has no weight gradient. - const bool mxfp8 = gemm_in_scale_inv.has_value(); - auto workspace_t = overlap_workspace(weight.size(1), weight.size(2), weight.size(0), - gemm_in.size(0), false, mxfp8, layer_cfg, gemm_in); + auto workspace_t = + overlap_workspace(weight_shape.data[1], weight_shape.data[2], weight_shape.data[0], + gemm_in_shape.data[0], false, mxfp8, layer_cfg, expert_token_offsets); auto workspace_te = makeTransformerEngineTensor(workspace_t); + py::gil_scoped_release release; nvte_ep_combine_gemm_fwd(handle_mem_te.data(), gemm_in_te.data(), recv_topk_weights.has_value() ? recv_topk_weights_te.data() : nullptr, expert_token_offsets_te.data(), weight_te.data(), expert_out_te.data(), result_te.data(), workspace_te.data(), &layer_cfg, stream); } -void ep_combine_gemm_bwd( - at::Tensor handle_mem, at::Tensor grad_result, at::Tensor gemm_out, - at::Tensor recv_topk_weights, at::Tensor tokens_per_expert, at::Tensor weight, - at::Tensor grad_expert_out, at::Tensor grad_gemm_out, at::Tensor grad_recv_topk_weights, - int64_t top_k, int64_t dispatch_output_per_expert_alignment, at::ScalarType topk_idx_dtype, - std::optional grad_result_scale_inv, - std::optional grad_expert_out_scale_inv, std::optional weight_scale_inv, - std::optional grad_gemm_out_scale_inv, - std::optional grad_gemm_out_columnwise, - std::optional grad_gemm_out_columnwise_scale_inv, std::optional act_out, - std::optional act_out_scale_inv, std::optional wgrad_input, - std::optional weight_grad, bool accumulate_weight_grad, - std::optional grad_expert_out_columnwise, - std::optional grad_expert_out_columnwise_scale_inv, - std::optional wgrad_input_scale_inv, bool symm_input) { - check_cuda_operands( - {{"handle_mem", operand(handle_mem)}, - {"grad_result", operand(grad_result)}, - {"gemm_out", operand(gemm_out)}, - {"recv_topk_weights", operand(recv_topk_weights)}, - {"tokens_per_expert", operand(tokens_per_expert)}, - {"weight", operand(weight)}, - {"grad_expert_out", operand(grad_expert_out)}, - {"grad_gemm_out", operand(grad_gemm_out)}, - {"grad_recv_topk_weights", operand(grad_recv_topk_weights)}, - {"grad_result_scale_inv", operand(grad_result_scale_inv)}, - {"grad_expert_out_scale_inv", operand(grad_expert_out_scale_inv)}, - {"weight_scale_inv", operand(weight_scale_inv)}, - {"grad_gemm_out_scale_inv", operand(grad_gemm_out_scale_inv)}, - {"grad_gemm_out_columnwise", operand(grad_gemm_out_columnwise)}, - {"grad_gemm_out_columnwise_scale_inv", operand(grad_gemm_out_columnwise_scale_inv)}, - {"act_out", operand(act_out)}, - {"act_out_scale_inv", operand(act_out_scale_inv)}, - {"wgrad_input", operand(wgrad_input)}, - {"weight_grad", operand(weight_grad)}, - {"grad_expert_out_columnwise", operand(grad_expert_out_columnwise)}, - {"grad_expert_out_columnwise_scale_inv", operand(grad_expert_out_columnwise_scale_inv)}, - {"wgrad_input_scale_inv", operand(wgrad_input_scale_inv)}}); +// MXFP8: the weight and act_out are columnwise with GEMM-swizzled scales; grad_result is rowwise +// with compact scales, grad_expert_out rowwise with compact scales and columnwise when the weight +// gradient is computed, and grad_gemm_out rowwise and columnwise with swizzled scales. +void ep_combine_gemm_bwd(at::Tensor handle_mem, py::object grad_result, at::Tensor gemm_out, + at::Tensor recv_topk_weights, at::Tensor tokens_per_expert, + py::object weight, py::object grad_expert_out, py::object grad_gemm_out, + at::Tensor grad_recv_topk_weights, int64_t top_k, + int64_t dispatch_output_per_expert_alignment, + at::ScalarType topk_idx_dtype, std::optional act_out, + std::optional wgrad_input, + std::optional weight_grad, bool accumulate_weight_grad, + bool symm_input) { + check_cuda_operands({{"handle_mem", operand(handle_mem)}, + {"gemm_out", operand(gemm_out)}, + {"recv_topk_weights", operand(recv_topk_weights)}, + {"tokens_per_expert", operand(tokens_per_expert)}, + {"grad_recv_topk_weights", operand(grad_recv_topk_weights)}, + {"weight_grad", operand(weight_grad)}}); + check_cuda_object("grad_result", grad_result); + check_cuda_object("weight", weight); + check_cuda_object("grad_expert_out", grad_expert_out); + check_cuda_object("grad_gemm_out", grad_gemm_out); + check_cuda_object("act_out", act_out); + check_cuda_object("wgrad_input", wgrad_input); auto stream = at::cuda::getCurrentCUDAStream().stream(); - NVTE_CHECK(grad_result.is_contiguous() && gemm_out.is_contiguous() && weight.is_contiguous() && - grad_expert_out.is_contiguous() && grad_gemm_out.is_contiguous(), - "operands must be contiguous"); + NVTE_CHECK(gemm_out.is_contiguous(), "gemm_out must be contiguous"); check_dense_cuda(tokens_per_expert, "tokens_per_expert"); check_dense_cuda(grad_recv_topk_weights, "grad_recv_topk_weights"); - const bool mxfp8 = grad_result_scale_inv.has_value(); - NVTE_CHECK(grad_expert_out_scale_inv.has_value() == mxfp8 && - weight_scale_inv.has_value() == mxfp8 && - grad_gemm_out_scale_inv.has_value() == mxfp8 && - grad_gemm_out_columnwise.has_value() == mxfp8 && - grad_gemm_out_columnwise_scale_inv.has_value() == mxfp8 && - act_out.has_value() == mxfp8 && act_out_scale_inv.has_value() == mxfp8, - "pass all of the MXFP8 operands, or none"); - // The columnwise grad_expert_out of the MXFP8 weight gradient, written by the call. - const bool grad_expert_out_columns = grad_expert_out_columnwise.has_value(); - NVTE_CHECK(grad_expert_out_columnwise_scale_inv.has_value() == grad_expert_out_columns && - (mxfp8 || !grad_expert_out_columns), - "pass the MXFP8 columnwise grad_expert_out with its scales, or neither"); + const bool mxfp8 = is_mxfp8_object(grad_result); + NVTE_CHECK(is_mxfp8_object(weight) == mxfp8 && is_mxfp8_object(grad_expert_out) == mxfp8 && + is_mxfp8_object(grad_gemm_out) == mxfp8 && act_out.has_value() == mxfp8 && + (!act_out.has_value() || is_mxfp8_object(*act_out)) && + (!wgrad_input.has_value() || is_mxfp8_object(*wgrad_input) == mxfp8), + "pass all of the operands as MXFP8 tensors, or all as torch tensors"); auto handle_mem_te = makeTransformerEngineTensor(handle_mem); - auto grad_result_te = make_maybe_mxfp8_tensor(grad_result, grad_result_scale_inv, false); + auto grad_result_te = compact_scales_operand(grad_result); auto gemm_out_te = makeTransformerEngineTensor(gemm_out); auto recv_topk_weights_te = makeTransformerEngineTensor(recv_topk_weights); auto tokens_per_expert_te = makeTransformerEngineTensor(tokens_per_expert); - // MXFP8 reads the forward weight columnwise. - auto weight_te = mxfp8 ? make_columnwise_mxfp8_tensor(weight, *weight_scale_inv) - : makeTransformerEngineTensor(weight); - auto grad_expert_out_te = - grad_expert_out_columns - ? make_mxfp8_tensor(grad_expert_out, *grad_expert_out_scale_inv, - *grad_expert_out_columnwise, *grad_expert_out_columnwise_scale_inv, - false) - : make_maybe_mxfp8_tensor(grad_expert_out, grad_expert_out_scale_inv, false); - auto grad_gemm_out_te = - mxfp8 ? make_mxfp8_tensor(grad_gemm_out, *grad_gemm_out_scale_inv, *grad_gemm_out_columnwise, - *grad_gemm_out_columnwise_scale_inv, true) - : makeTransformerEngineTensor(grad_gemm_out); + auto grad_expert_out_te = operand_tensor(grad_expert_out); + auto grad_gemm_out_te = operand_tensor(grad_gemm_out); auto grad_recv_topk_weights_te = makeTransformerEngineTensor(grad_recv_topk_weights); TensorWrapper act_out_te; if (mxfp8) { - act_out_te = make_columnwise_mxfp8_tensor(*act_out, *act_out_scale_inv); + act_out_te = operand_tensor(*act_out); } - NVTE_CHECK(mxfp8 || !wgrad_input_scale_inv.has_value(), - "wgrad_input_scale_inv is for MXFP8 only"); - WeightGradTensors wgrad(wgrad_input, weight_grad, wgrad_input_scale_inv); - const NVTECommWindow grad_result_win = - symm_input ? make_input_window(grad_result, grad_result_scale_inv) : kNoWindow; + // The weight is [experts, hidden, ffn], and act_out is [rows, ffn]. + auto weight_te = + weight_operand(weight, tokens_per_expert.numel(), mxfp8 ? act_out_te.shape().data[1] : 0); + WeightGradTensors wgrad(wgrad_input, weight_grad); + const NVTECommWindow grad_result_win = symm_input ? make_input_window(grad_result) : kNoWindow; auto layer_cfg = make_layer_cfg(top_k, dispatch_output_per_expert_alignment, get_topk_idx_te_dtype(topk_idx_dtype)); // FC2 weight is [experts, hidden, ffn]; size the wgrad region when a weight gradient is written. + const NVTEShape weight_shape = weight_te.shape(); auto workspace_t = - overlap_workspace(weight.size(1), weight.size(2), weight.size(0), grad_expert_out.size(0), - weight_grad.has_value(), mxfp8, layer_cfg, grad_result); + overlap_workspace(weight_shape.data[1], weight_shape.data[2], weight_shape.data[0], + grad_expert_out_te.shape().data[0], weight_grad.has_value(), mxfp8, + layer_cfg, tokens_per_expert); auto workspace_te = makeTransformerEngineTensor(workspace_t); + py::gil_scoped_release release; nvte_ep_combine_gemm_bwd( handle_mem_te.data(), grad_result_te.data(), grad_result_win, gemm_out_te.data(), recv_topk_weights_te.data(), tokens_per_expert_te.data(), weight_te.data(), wgrad.input(), @@ -1143,73 +1117,55 @@ void ep_combine_gemm_bwd( workspace_te.data(), NVTE_Activation_Type::SWIGLU, &layer_cfg, stream); } -void ep_dispatch_gemm_bwd( - at::Tensor handle_mem, at::Tensor grad_gemm_out, at::Tensor grad_recv_topk_weights, - at::Tensor tokens_per_expert, at::Tensor weight, at::Tensor grad_recv_tokens, - at::Tensor grad_tokens, at::Tensor grad_topk_weights, int64_t top_k, - int64_t dispatch_output_per_expert_alignment, at::ScalarType topk_idx_dtype, - std::optional grad_gemm_out_scale_inv, std::optional weight_scale_inv, - std::optional grad_gemm_out_columnwise, - std::optional grad_gemm_out_columnwise_scale_inv, - std::optional wgrad_input, std::optional wgrad_input_scale_inv, - std::optional weight_grad, bool accumulate_weight_grad, - std::optional wgrad_input_rowwise, - std::optional wgrad_input_rowwise_scale_inv) { - check_cuda_operands( - {{"handle_mem", operand(handle_mem)}, - {"grad_gemm_out", operand(grad_gemm_out)}, - {"grad_recv_topk_weights", operand(grad_recv_topk_weights)}, - {"tokens_per_expert", operand(tokens_per_expert)}, - {"weight", operand(weight)}, - {"grad_recv_tokens", operand(grad_recv_tokens)}, - {"grad_tokens", operand(grad_tokens)}, - {"grad_topk_weights", operand(grad_topk_weights)}, - {"grad_gemm_out_scale_inv", operand(grad_gemm_out_scale_inv)}, - {"weight_scale_inv", operand(weight_scale_inv)}, - {"grad_gemm_out_columnwise", operand(grad_gemm_out_columnwise)}, - {"grad_gemm_out_columnwise_scale_inv", operand(grad_gemm_out_columnwise_scale_inv)}, - {"wgrad_input", operand(wgrad_input)}, - {"wgrad_input_scale_inv", operand(wgrad_input_scale_inv)}, - {"weight_grad", operand(weight_grad)}, - {"wgrad_input_rowwise", operand(wgrad_input_rowwise)}, - {"wgrad_input_rowwise_scale_inv", operand(wgrad_input_rowwise_scale_inv)}}); +// MXFP8: the weight is columnwise with GEMM-swizzled scales, grad_gemm_out has swizzled scales and +// is columnwise as well when the weight gradient is computed. wgrad_input is the columnwise input +// of the weight gradient; when it also holds the rowwise data (compact scales), the call writes the +// columnwise data from there. +void ep_dispatch_gemm_bwd(at::Tensor handle_mem, py::object grad_gemm_out, + at::Tensor grad_recv_topk_weights, at::Tensor tokens_per_expert, + py::object weight, at::Tensor grad_recv_tokens, at::Tensor grad_tokens, + at::Tensor grad_topk_weights, int64_t top_k, + int64_t dispatch_output_per_expert_alignment, + at::ScalarType topk_idx_dtype, std::optional wgrad_input, + std::optional weight_grad, bool accumulate_weight_grad) { + check_cuda_operands({{"handle_mem", operand(handle_mem)}, + {"grad_recv_topk_weights", operand(grad_recv_topk_weights)}, + {"tokens_per_expert", operand(tokens_per_expert)}, + {"grad_recv_tokens", operand(grad_recv_tokens)}, + {"grad_tokens", operand(grad_tokens)}, + {"grad_topk_weights", operand(grad_topk_weights)}, + {"weight_grad", operand(weight_grad)}}); + check_cuda_object("grad_gemm_out", grad_gemm_out); + check_cuda_object("weight", weight); + check_cuda_object("wgrad_input", wgrad_input); auto stream = at::cuda::getCurrentCUDAStream().stream(); - NVTE_CHECK( - grad_gemm_out.is_contiguous() && weight.is_contiguous() && grad_recv_tokens.is_contiguous(), - "operands must be contiguous"); + NVTE_CHECK(grad_recv_tokens.is_contiguous(), "grad_recv_tokens must be contiguous"); check_dense_cuda(tokens_per_expert, "tokens_per_expert"); check_dense_cuda(grad_recv_topk_weights, "grad_recv_topk_weights"); - const bool mxfp8 = grad_gemm_out_scale_inv.has_value(); - NVTE_CHECK(weight_scale_inv.has_value() == mxfp8, "pass both MXFP8 scales, or none"); - // The MXFP8 weight gradient reads grad_gemm_out and wgrad_input columnwise. - const bool columnwise = grad_gemm_out_columnwise.has_value(); - NVTE_CHECK(grad_gemm_out_columnwise_scale_inv.has_value() == columnwise && - wgrad_input_scale_inv.has_value() == columnwise && (mxfp8 || !columnwise), - "pass the MXFP8 columnwise operands of the weight gradient together, or none"); + const bool mxfp8 = is_mxfp8_object(grad_gemm_out); + NVTE_CHECK(is_mxfp8_object(weight) == mxfp8 && + (!wgrad_input.has_value() || is_mxfp8_object(*wgrad_input) == mxfp8), + "pass all of the operands as MXFP8 tensors, or all as torch tensors"); auto handle_mem_te = makeTransformerEngineTensor(handle_mem); - auto grad_gemm_out_te = - columnwise - ? make_mxfp8_tensor(grad_gemm_out, *grad_gemm_out_scale_inv, *grad_gemm_out_columnwise, - *grad_gemm_out_columnwise_scale_inv, true) - : make_maybe_mxfp8_tensor(grad_gemm_out, grad_gemm_out_scale_inv, true); + auto grad_gemm_out_te = operand_tensor(grad_gemm_out); auto grad_recv_topk_weights_te = makeTransformerEngineTensor(grad_recv_topk_weights); auto tokens_per_expert_te = makeTransformerEngineTensor(tokens_per_expert); - // MXFP8 reads the forward weight columnwise. - auto weight_te = mxfp8 ? make_columnwise_mxfp8_tensor(weight, *weight_scale_inv) - : makeTransformerEngineTensor(weight); + auto weight_te = weight_operand(weight, tokens_per_expert.numel(), grad_recv_tokens.size(1)); auto grad_recv_tokens_te = makeTransformerEngineTensor(grad_recv_tokens); auto grad_tokens_te = makeTransformerEngineTensor(grad_tokens); auto grad_topk_weights_te = makeTransformerEngineTensor(grad_topk_weights); - WeightGradTensors wgrad(wgrad_input, weight_grad, wgrad_input_scale_inv, wgrad_input_rowwise, - wgrad_input_rowwise_scale_inv); + WeightGradTensors wgrad(wgrad_input, weight_grad); auto layer_cfg = make_layer_cfg(top_k, dispatch_output_per_expert_alignment, get_topk_idx_te_dtype(topk_idx_dtype)); // FC1 weight is [experts, 2 * ffn, hidden]; size the wgrad region when a weight gradient is // written. + const NVTEShape weight_shape = weight_te.shape(); auto workspace_t = - overlap_workspace(weight.size(2), weight.size(1) / 2, weight.size(0), grad_gemm_out.size(0), - weight_grad.has_value(), mxfp8, layer_cfg, grad_gemm_out); + overlap_workspace(weight_shape.data[2], weight_shape.data[1] / 2, weight_shape.data[0], + grad_gemm_out_te.shape().data[0], weight_grad.has_value(), mxfp8, layer_cfg, + tokens_per_expert); auto workspace_te = makeTransformerEngineTensor(workspace_t); + py::gil_scoped_release release; nvte_ep_dispatch_gemm_bwd(handle_mem_te.data(), grad_gemm_out_te.data(), grad_recv_topk_weights_te.data(), tokens_per_expert_te.data(), weight_te.data(), wgrad.input(), grad_recv_tokens_te.data(), @@ -1254,56 +1210,34 @@ void register_ep_bindings(pybind11::module_& m) { py::arg("result"), py::arg("top_k"), py::arg("dispatch_output_per_expert_alignment"), py::arg("topk_idx_dtype"), py::call_guard()); m.def("ep_dispatch_gemm_fwd", &ep_dispatch_gemm_fwd, - "EP dispatch overlapped with the first GEMM. Returns recv_tokens, recv_topk_weights, " - "gemm_out, act_out and expert_token_offsets, then the recv and act_out scales when " - "MXFP8; in eager mode omit them and they are sized and allocated here", + "EP dispatch overlapped with the first GEMM; returns expert_token_offsets", py::arg("handle_mem"), py::arg("topk_idx"), py::arg("tokens"), py::arg("topk_weights"), py::arg("weight"), py::arg("recv_tokens"), py::arg("recv_topk_weights"), py::arg("tokens_per_expert"), py::arg("gemm_out"), py::arg("act_out"), py::arg("top_k"), py::arg("dispatch_output_per_expert_alignment"), - py::arg("total_recv_tokens") = std::nullopt, py::arg("eager_row_bucket") = 0, - py::arg("tokens_scale_inv") = std::nullopt, py::arg("recv_scale_inv") = std::nullopt, - py::arg("weight_scale_inv") = std::nullopt, py::arg("act_out_scale_inv") = std::nullopt, - py::arg("symm_input") = false, py::call_guard()); + py::arg("total_recv_tokens") = std::nullopt, py::arg("symm_input") = false); m.def("ep_combine_gemm_fwd", &ep_combine_gemm_fwd, "EP second GEMM overlapped with the combine", py::arg("handle_mem"), py::arg("gemm_in"), py::arg("expert_token_offsets"), py::arg("weight"), py::arg("expert_out"), py::arg("result"), py::arg("top_k"), py::arg("dispatch_output_per_expert_alignment"), py::arg("topk_idx_dtype"), - py::arg("recv_topk_weights") = std::nullopt, py::arg("gemm_in_scale_inv") = std::nullopt, - py::arg("weight_scale_inv") = std::nullopt, py::call_guard()); + py::arg("recv_topk_weights") = std::nullopt); m.def("ep_combine_gemm_bwd", &ep_combine_gemm_bwd, "Backward of the second GEMM and the combine, with the activation backward", py::arg("handle_mem"), py::arg("grad_result"), py::arg("gemm_out"), py::arg("recv_topk_weights"), py::arg("tokens_per_expert"), py::arg("weight"), py::arg("grad_expert_out"), py::arg("grad_gemm_out"), py::arg("grad_recv_topk_weights"), py::arg("top_k"), py::arg("dispatch_output_per_expert_alignment"), - py::arg("topk_idx_dtype"), py::arg("grad_result_scale_inv") = std::nullopt, - py::arg("grad_expert_out_scale_inv") = std::nullopt, - py::arg("weight_scale_inv") = std::nullopt, - py::arg("grad_gemm_out_scale_inv") = std::nullopt, - py::arg("grad_gemm_out_columnwise") = std::nullopt, - py::arg("grad_gemm_out_columnwise_scale_inv") = std::nullopt, - py::arg("act_out") = std::nullopt, py::arg("act_out_scale_inv") = std::nullopt, + py::arg("topk_idx_dtype"), py::arg("act_out") = std::nullopt, py::arg("wgrad_input") = std::nullopt, py::arg("weight_grad") = std::nullopt, - py::arg("accumulate_weight_grad") = false, - py::arg("grad_expert_out_columnwise") = std::nullopt, - py::arg("grad_expert_out_columnwise_scale_inv") = std::nullopt, - py::arg("wgrad_input_scale_inv") = std::nullopt, py::arg("symm_input") = false, - py::call_guard()); - m.def( - "ep_dispatch_gemm_bwd", &ep_dispatch_gemm_bwd, "Backward of the first GEMM and the dispatch", - py::arg("handle_mem"), py::arg("grad_gemm_out"), py::arg("grad_recv_topk_weights"), - py::arg("tokens_per_expert"), py::arg("weight"), py::arg("grad_recv_tokens"), - py::arg("grad_tokens"), py::arg("grad_topk_weights"), py::arg("top_k"), - py::arg("dispatch_output_per_expert_alignment"), py::arg("topk_idx_dtype"), - py::arg("grad_gemm_out_scale_inv") = std::nullopt, py::arg("weight_scale_inv") = std::nullopt, - py::arg("grad_gemm_out_columnwise") = std::nullopt, - py::arg("grad_gemm_out_columnwise_scale_inv") = std::nullopt, - py::arg("wgrad_input") = std::nullopt, py::arg("wgrad_input_scale_inv") = std::nullopt, - py::arg("weight_grad") = std::nullopt, py::arg("accumulate_weight_grad") = false, - py::arg("wgrad_input_rowwise") = std::nullopt, - py::arg("wgrad_input_rowwise_scale_inv") = std::nullopt, - py::call_guard()); + py::arg("accumulate_weight_grad") = false, py::arg("symm_input") = false); + m.def("ep_dispatch_gemm_bwd", &ep_dispatch_gemm_bwd, + "Backward of the first GEMM and the dispatch", py::arg("handle_mem"), + py::arg("grad_gemm_out"), py::arg("grad_recv_topk_weights"), py::arg("tokens_per_expert"), + py::arg("weight"), py::arg("grad_recv_tokens"), py::arg("grad_tokens"), + py::arg("grad_topk_weights"), py::arg("top_k"), + py::arg("dispatch_output_per_expert_alignment"), py::arg("topk_idx_dtype"), + py::arg("wgrad_input") = std::nullopt, py::arg("weight_grad") = std::nullopt, + py::arg("accumulate_weight_grad") = false); m.def("ep_dispatch_bwd", &ep_dispatch_bwd, "EP dispatch backward", py::arg("handle_mem"), py::arg("grad"), py::arg("g_recv_topk_weights"), py::arg("grad_tokens"), py::arg("grad_topk_weights"), py::arg("top_k"), diff --git a/transformer_engine/pytorch/ep.py b/transformer_engine/pytorch/ep.py index 98dbc10310d..e6a6ceb472b 100644 --- a/transformer_engine/pytorch/ep.py +++ b/transformer_engine/pytorch/ep.py @@ -6,7 +6,6 @@ from __future__ import annotations import atexit -import functools import math import os import warnings @@ -18,13 +17,13 @@ import transformer_engine_torch as tex -from ..common import _load_core_library +from ..common import cutedsl_backend_built from .constants import DType from .cpu_offload import mark_not_offload from .distributed import symm_mem_alloc, release_symm_mem_pool from .quantized_tensor import QuantizedTensor, QuantizedTensorStorage from .tensor.storage.mxfp8_tensor_storage import MXFP8TensorStorage -from .utils import round_up_to_nearest_multiple +from .utils import get_device_compute_capability, round_up_to_nearest_multiple # Type-hint-only import; keeps the ``Recipe`` annotation without a runtime import of # common.recipe (the concrete recipe classes are imported lazily where used). @@ -97,7 +96,7 @@ def _check_nccl_runtime_version() -> None: _EAGER = False _BOOTSTRAP_SETTINGS: Optional[dict[str, object]] = None # Symm-mem data and scale buffers the overlapped MoE ops quantize their MXFP8 dispatch inputs into. -_DISPATCH_WINDOW: Optional[tuple[torch.Tensor, torch.Tensor]] = None +_SYM_DISPATCH_BUFFERS: Optional[MXFP8TensorStorage] = None @dataclass(frozen=True, slots=True) @@ -134,10 +133,10 @@ class EpConfig: def _atexit_finalize() -> None: """Best-effort teardown at interpreter shutdown; swallows errors.""" - global _BOOTSTRAPPED, _EP_GROUP, _EAGER, _BOOTSTRAP_SETTINGS, _DISPATCH_WINDOW + global _BOOTSTRAPPED, _EP_GROUP, _EAGER, _BOOTSTRAP_SETTINGS, _SYM_DISPATCH_BUFFERS if _BOOTSTRAPPED: try: - _DISPATCH_WINDOW = None + _SYM_DISPATCH_BUFFERS = None tex.ep_finalize() except Exception: # pylint: disable=broad-exception-caught import traceback @@ -285,25 +284,16 @@ def get_ep_drop_on_overflow() -> Optional[bool]: return bool(_BOOTSTRAP_SETTINGS["drop_on_overflow"]) -@functools.lru_cache(maxsize=None) -def _cutedsl_backend_built() -> bool: - """Whether the core library was built with the CuTeDSL backend.""" - core = _load_core_library() - return hasattr(core, "nvte_is_cutedsl_backend_built") and bool( - core.nvte_is_cutedsl_backend_built() - ) - - def _moe_overlap_available() -> bool: """Whether the overlapped MoE GEMMs can run: SM 10.0, 10.3 or 10.7 (tcgen05 kernels), the CuTeDSL backend built and on, and the GEMM path set.""" if not torch.cuda.is_available(): return False return ( - torch.cuda.get_device_capability() in ((10, 0), (10, 3), (10, 7)) + get_device_compute_capability() in ((10, 0), (10, 3), (10, 7)) and os.environ.get("NVTE_ENABLE_CUTEDSL_BACKEND", "0") != "0" and bool(os.environ.get("NVTE_MOE_OVERLAP")) - and _cutedsl_backend_built() + and cutedsl_backend_built() ) @@ -322,11 +312,11 @@ def ep_finalize() -> None: a caller that used ``symm_mem_alloc(use_pool=True)`` does not need a separate ``release_symm_mem_pool()`` before destroying the PG. """ - global _BOOTSTRAPPED, _EP_GROUP, _EAGER, _BOOTSTRAP_SETTINGS, _DISPATCH_WINDOW + global _BOOTSTRAPPED, _EP_GROUP, _EAGER, _BOOTSTRAP_SETTINGS, _SYM_DISPATCH_BUFFERS if not _BOOTSTRAPPED: return try: - _DISPATCH_WINDOW = None + _SYM_DISPATCH_BUFFERS = None # Deregister pooled symm-mem windows while the group's comm is still valid. release_symm_mem_pool() tex.ep_finalize() @@ -1151,12 +1141,18 @@ def _alloc_io(shape, dtype: torch.dtype, device, zero_copy: bool) -> torch.Tenso return torch.empty(*shape, dtype=dtype, device=device) -def _dispatch_window(device) -> Optional[tuple[torch.Tensor, torch.Tensor]]: - """Symm-mem data and scale buffers of one MXFP8 dispatch input, or None without symm-mem - support. Allocated collectively on first use and shared by every layer and direction, so the - EP calls of the group must share one stream.""" - global _DISPATCH_WINDOW - if _DISPATCH_WINDOW is None: +def _sym_dispatch_buffers(device, quantizer: "Quantizer") -> Optional[MXFP8TensorStorage]: + """Symm-mem rowwise storage of one dispatch input quantized by ``quantizer``, or None without + symm-mem support. Allocated collectively on first use and shared by every layer and + direction, so the EP calls of the group must share one stream.""" + global _SYM_DISPATCH_BUFFERS + if _SYM_DISPATCH_BUFFERS is None: + from .tensor.mxfp8_tensor import MXFP8Quantizer + + if not isinstance(quantizer, MXFP8Quantizer): + raise NotImplementedError( + "The EP dispatch buffers support only MXFP8; " f"got {type(quantizer).__name__}." + ) if not tex.ep_zero_copy_supported(): return None if torch.cuda.is_current_stream_capturing(): @@ -1164,22 +1160,26 @@ def _dispatch_window(device) -> Optional[tuple[torch.Tensor, torch.Tensor]]: "The EP dispatch window is allocated on first use; run a warmup step before " "CUDA graph capture." ) - from .tensor.mxfp8_tensor import MXFP8Quantizer 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) + scale_shape = quantizer.get_scale_shape(shape, False) window = symm_mem_alloc( (data_bytes + math.prod(scale_shape),), torch.uint8, _EP_GROUP, device=device ) mark_not_offload(window) - _DISPATCH_WINDOW = (window[:data_bytes], window[data_bytes:]) - return _DISPATCH_WINDOW + _SYM_DISPATCH_BUFFERS = _mxfp8_storage( + (window[:data_bytes], window[data_bytes:]), shape, quantizer + ) + return _SYM_DISPATCH_BUFFERS -def _mxfp8_storage(out, shape, quantizer: "MXFP8Quantizer", fake_dtype=None) -> MXFP8TensorStorage: - """Rowwise MXFP8 storage of ``shape`` at the start of the uint8 data and scale buffers ``out``.""" - data, scales = out +def _mxfp8_storage( + buffers, shape, quantizer: "MXFP8Quantizer", fake_dtype=None +) -> MXFP8TensorStorage: + """Rowwise MXFP8 storage of ``shape`` at the start of ``buffers``, a pair of uint8 data and + scale buffers.""" + data, scales = buffers for name, buf in (("data", data), ("scale", scales)): if buf.dtype != torch.uint8 or not buf.is_contiguous(): raise ValueError(f"MXFP8 {name} output buffer must be a contiguous uint8 tensor.") @@ -1201,17 +1201,21 @@ def _mxfp8_storage(out, shape, quantizer: "MXFP8Quantizer", fake_dtype=None) -> ) +def _buffers(storage: MXFP8TensorStorage) -> tuple[torch.Tensor, torch.Tensor]: + """The rowwise data and scale buffers of a storage.""" + return storage._rowwise_data, storage._rowwise_scale_inv + + def quantize_for_ep( input_: torch.Tensor | QuantizedTensorStorage, quantizer: Optional["Quantizer"], - out: Optional[tuple[torch.Tensor, torch.Tensor]] = None, + out: Optional[MXFP8TensorStorage] = None, ) -> tuple[MXFP8TensorStorage, torch.Tensor]: """Quantize an EP input with a supported quantizer. - ``out`` is a pair of contiguous uint8 tensors on the input's device, the data and the scales. - The data holds ``input_.numel()`` bytes and the scales the rowwise scale shape of the quantizer - (``get_scale_shape(shape, False)``, rows padded to 128). When given, the returned storage and - the compact scales it returns are views of them, so they alias ``out``. + ``out`` is a rowwise storage on the input's device that holds at least the input's rows. When + given, the returned storage and the compact scales it returns are views of its buffers, so + they alias ``out``. """ from .tensor.mxfp8_tensor import MXFP8Quantizer @@ -1228,7 +1232,7 @@ def quantize_for_ep( def _quantize_mxfp8( input_: torch.Tensor | QuantizedTensorStorage, quantizer: "MXFP8Quantizer", - out: Optional[tuple[torch.Tensor, torch.Tensor]] = None, + out: Optional[MXFP8TensorStorage] = None, ) -> tuple[MXFP8TensorStorage, torch.Tensor]: """Return E4M3 MXFP8 storage and compact rowwise scales for EP.""" from .constants import MXFP8_BLOCK_SCALING_SIZE @@ -1239,7 +1243,7 @@ def _quantize_mxfp8( input_device = ( input_._rowwise_data.device if isinstance(input_, MXFP8TensorStorage) else input_.device ) - if out[0].device != input_device: + if out._rowwise_data.device != input_device: raise ValueError(f"EP output buffers must be on the input's device {input_device}.") if isinstance(input_, MXFP8TensorStorage): quantized = input_ @@ -1252,7 +1256,7 @@ def _quantize_mxfp8( if out is None: quantized = quantizer(input_) else: - quantized = _mxfp8_storage(out, input_.shape, quantizer, input_.dtype) + quantized = _mxfp8_storage(_buffers(out), input_.shape, quantizer, input_.dtype) tex.quantize(input_, quantizer, quantized, None) if quantized._fp8_dtype != DType.kFloat8E4M3: @@ -1282,7 +1286,7 @@ def _quantize_mxfp8( raise ValueError("EP requires compact contiguous MXFP8 scales.") if out is not None and quantized is input_: # An MXFP8 input is copied into out, so the result is there whatever the input. - quantized = _mxfp8_storage(out, input_.shape, quantizer, fake_dtype=input_.dtype) + quantized = _mxfp8_storage(_buffers(out), input_.shape, quantizer, fake_dtype=input_.dtype) quantized._rowwise_data.copy_(data) quantized._rowwise_scale_inv[:t_flat, :scale_cols].copy_(scale_inv) scale_inv = quantized._rowwise_scale_inv[:t_flat, :scale_cols] diff --git a/transformer_engine/pytorch/ops/fused/moe_overlap.py b/transformer_engine/pytorch/ops/fused/moe_overlap.py index bbf633a05fc..8d3e6b0978d 100644 --- a/transformer_engine/pytorch/ops/fused/moe_overlap.py +++ b/transformer_engine/pytorch/ops/fused/moe_overlap.py @@ -14,7 +14,7 @@ import transformer_engine_torch as tex from ....common.recipe import Format, MXFP8BlockScaling -from ...constants import MXFP8_BLOCK_SCALING_SIZE +from ...constants import DType, MXFP8_BLOCK_SCALING_SIZE from ...cpu_offload import ( is_cpu_offload_enabled, mark_activation_offload, @@ -23,16 +23,17 @@ ) from ...ep import ( EpConfig, - _dispatch_window, - _make_grouped_mxfp8, _moe_overlap_available, + _sym_dispatch_buffers, quantize_for_ep, ) from ...distributed_weight import is_distributed_weight from ...quantization import Recipe from ...tensor.grouped_tensor import GroupedTensor from ...tensor.mxfp8_tensor import MXFP8Quantizer -from ...utils import clear_tensor_data, mark_grouped_tensor +from ...tensor.storage.grouped_tensor_storage import GroupedTensorStorage +from ...tensor.storage.mxfp8_tensor_storage import MXFP8TensorStorage +from ...utils import clear_tensor_data, get_device_compute_capability, mark_grouped_tensor from ..basic import ( GroupedLinear, MoeCombine, @@ -75,6 +76,8 @@ class FusedMoE(FusedOperation): Requirements: - Packed weights (``single_grouped_weight=True``) without bias: BF16 parameters, or MXFP8 primary weights (``quantized_model_init``) under ``MXFP8BlockScaling``. + - ``ScaledSwiGLU`` with ``glu_interleave_size=32``: the FC1 gate and up rows are in + alternating blocks of 32, the layout the GEMMs take. - Contiguous forward inputs. - EP within one NVLink domain. - ``EpConfig`` ``alignment`` of 256, with the receive capacity a multiple of 256. @@ -92,12 +95,7 @@ class FusedMoE(FusedOperation): ``MXFP8BlockScaling`` the GEMMs and the EP transport run in MXFP8 and the routing weights are applied to the second GEMM's output. Either way their gradient goes to the dispatch's ``topk_weights``. - - The weights are prepared for the GEMMs (quantized to MXFP8, or their FC1 rows reordered) at - each forward. - - The GEMMs take the FC1 gate and up rows in alternating blocks of 32 - (``glu_interleave_size=32``). With ``glu_interleave_size=None`` the FC1 weight rows are - reordered when the weights are prepared and the FC1 weight gradient is returned in the - parameter's own layout. + - The weights are prepared for the GEMMs (quantized to MXFP8) at each forward. """ @classmethod @@ -108,7 +106,7 @@ def is_supported(cls) -> bool: # check. if not _moe_overlap_available() or _gemm_interface_reason() is not None: return False - if torch.cuda.get_device_capability() != (10, 7): + if get_device_compute_capability() != (10, 7): return GroupedMLP_CuTeGEMMGLUBf16.is_supported() # SM 10.7 has no BF16 cuDNN GLU kernels; the EP GEMMs replace them, and this op takes only # the cuDNN wgrad kernel. @@ -135,11 +133,7 @@ def __init__( if reason is not None: raise RuntimeError(f"FusedMoE is not supported: {reason}.") self._mxfp8 = recipe is not None - # The GEMMs take FC1 gate and up rows in alternating blocks of _GLU_BLOCK. - # TODO(phuonguyen): cuDNN upstream supports glu_interleave_size=None; drop the reorder once - # the rebased cuDNN is upstreamed. - self._reorder_glu = activation.glu_interleave_size is None - self._operands = _Mxfp8Operands() if self._mxfp8 else _Bf16Operands(self._reorder_glu) + self._operands = _Mxfp8Operands() if self._mxfp8 else _Bf16Operands() # The dispatch and combine share one EpBuffer (see _unsupported_reason); FusedMoE reads it # from self.basic_ops[0].buffer at each forward. @@ -162,22 +156,12 @@ def fuser_forward( raise ValueError("FusedMoE allocates its outputs and gradients; it takes no buffers.") fc2_op = self.basic_ops[3] topk_idx, topk_weights = basic_op_extra_inputs[0] - # Splits and scales come from the dispatch inside this op. - for extra_inputs in basic_op_extra_inputs[1:-1]: - if any(t is not None for t in extra_inputs): - raise ValueError( - "FusedMoE takes the splits and routing scales from its dispatch; " - "do not pass them as extra inputs." - ) buffer = validate_ep_buffer("FusedMoE", self.basic_ops[0].config, self.basic_ops[0].buffer) input_shape = _validate_dispatch_input(input_, buffer) _validate_routing_inputs(topk_idx, topk_weights, device=buffer.device) if topk_idx.dtype not in (torch.int32, torch.int64): raise TypeError(f"topk_idx must be int32 or int64, got {topk_idx.dtype}.") - # TODO(phuonguyen): revisit once non-BF16 compute dtypes are supported. - if torch.is_autocast_enabled() and torch.get_autocast_dtype("cuda") != torch.bfloat16: - raise RuntimeError("FusedMoE computes in BF16; keep the autocast dtype BF16.") if not buffer.eager and buffer.recv_capacity_per_rank % _TILE != 0: raise ValueError( f"FusedMoE needs the recv rows ({buffer.recv_capacity_per_rank}) to be a" @@ -191,39 +175,40 @@ def fuser_forward( hidden = buffer.hidden_dim ffn = fc2_op.in_features backward = any(ctx.requires_grad for ctx in basic_op_ctxs) - w1, w2 = (self._weight_operands(idx, backward) for idx in (1, 3)) - w1_data, w1_kwargs = operands.weight(w1) - w2_data, w2_kwargs = operands.weight(w2) - tokens, input_kwargs = operands.dispatch_input(_require_contiguous(input_, "input"), device) + self._check_runtime_support(backward) topk_idx = _require_contiguous(topk_idx, "topk_idx") topk_weights = _require_contiguous(topk_weights, "topk_weights") - tokens_per_expert = buffer.tokens_per_expert_i32 if buffer.eager: - # The binding runs the prepare, reads the recv total on the host and allocates the - # recv rows in whole buckets, so the number of compiled GEMMs stays bounded. - recv_tokens, recv_weights, gemm_out, act_out, expert_token_offsets, *scale_list = ( - tex.ep_dispatch_gemm_fwd( - buffer.handle_mem, topk_idx, tokens, topk_weights, w1_data, None, None, - tokens_per_expert, None, None, buffer.top_k, buffer.alignment, - buffer.total_recv_tokens_i32, _EAGER_ROW_BUCKET, **input_kwargs, **w1_kwargs, - ) + # The prepare writes the recv total to pinned host memory. Launch it first and mark its + # completion with an event, so the weight and input preparation below overlaps it; + # only the total read waits. + tex.ep_prepare( + buffer.handle_mem, topk_idx, tokens_per_expert, buffer.top_k, buffer.alignment, + buffer.total_recv_tokens_i32, ) # fmt: skip - scales = dict(zip(operands.scale_names, scale_list)) - rows = recv_tokens.shape[0] + prepared = torch.cuda.Event() + prepared.record() + w1, w2 = (self._weight_operands(idx, backward) for idx in (1, 3)) + tokens, symm_input = operands.dispatch_input(_require_contiguous(input_, "input"), device) + + if buffer.eager: + # Size the recv rows in whole buckets, so the number of compiled GEMMs stays bounded. + prepared.synchronize() + total = int(buffer.total_recv_tokens_i32.item()) + rows = max(-(-total // _EAGER_ROW_BUCKET), 1) * _EAGER_ROW_BUCKET + total_recv_tokens = None else: rows = buffer.recv_capacity_per_rank - recv_tokens, gemm_out, act_out, scales = operands.recv_buffers( - rows, hidden, ffn, device - ) - recv_weights = torch.empty(rows, dtype=torch.float32, device=device) - # The dispatch writes the expert layout the GEMMs read. - expert_token_offsets = tex.ep_dispatch_gemm_fwd( - buffer.handle_mem, topk_idx, tokens, topk_weights, w1_data, recv_tokens, - recv_weights, tokens_per_expert, gemm_out, act_out, buffer.top_k, - buffer.alignment, buffer.total_recv_tokens_i32, **input_kwargs, **scales, - **w1_kwargs, - )[4] # fmt: skip + total_recv_tokens = buffer.total_recv_tokens_i32 + recv_tokens, gemm_out, act_out = operands.recv_buffers(rows, hidden, ffn, device) + recv_weights = torch.empty(rows, dtype=torch.float32, device=device) + # The dispatch writes the expert layout the GEMMs read. + expert_token_offsets = tex.ep_dispatch_gemm_fwd( + buffer.handle_mem, topk_idx, tokens, topk_weights, operands.forward_weight(w1), + recv_tokens, recv_weights, tokens_per_expert, gemm_out, act_out, buffer.top_k, + buffer.alignment, total_recv_tokens, symm_input=symm_input, + ) # fmt: skip # Publish the public counters as the unfused prepare does: the kept tokens per expert and # the recv total before any drop. buffer.tokens_per_expert.copy_(tokens_per_expert) @@ -231,17 +216,52 @@ def fuser_forward( expert_out = torch.empty(rows, hidden, dtype=torch.bfloat16, device=device) result = torch.empty(buffer.num_local_tokens, hidden, dtype=torch.bfloat16, device=device) tex.ep_combine_gemm_fwd( - buffer.handle_mem, act_out, expert_token_offsets, w2_data, expert_out, result, - buffer.top_k, buffer.alignment, buffer.topk_idx_dtype, - **operands.combine_kwargs(recv_weights, scales), **w2_kwargs, + buffer.handle_mem, act_out, expert_token_offsets, operands.forward_weight(w2), + expert_out, result, buffer.top_k, buffer.alignment, buffer.topk_idx_dtype, + operands.combine_recv_weights(recv_weights), ) # fmt: skip row_tensors, other_tensors = operands.saved_tensors( - recv_tokens, recv_weights, gemm_out, act_out, scales, w1, w2, backward + recv_tokens, recv_weights, gemm_out, act_out, w1, w2, backward ) self._save_for_backward(basic_op_ctxs, buffer, row_tensors, other_tensors, topk_weights) return result, [(tokens_per_expert, recv_weights), (), (), (), ()] + def _check_runtime_support(self, backward: bool) -> None: + """Raise for a setting that can change between calls and the GEMMs do not support.""" + # TODO(phuonguyen): drop the deterministic gate once the routing-weight gradient is + # reworked to avoid the atomic reduction, which makes it reproducible. + if _deterministic_algorithms_required(): + raise RuntimeError( + "FusedMoE does not support deterministic execution: the routing-weight gradient is" + " reduced with atomics." + ) + # TODO(phuonguyen): revisit once non-BF16 compute dtypes are supported. + if torch.is_autocast_enabled() and torch.get_autocast_dtype("cuda") != torch.bfloat16: + raise RuntimeError("FusedMoE computes in BF16; keep the autocast dtype BF16.") + _, fc1_op, _, fc2_op, _ = self.basic_ops + if fc1_op.need_backward_dw() or fc2_op.need_backward_dw(): + raise RuntimeError( + "FusedMoE does not support delayed weight gradient computation (delay_wgrad_compute)." + ) + config = self.basic_ops[0].config + if ( + backward + and self._mxfp8 + and get_device_compute_capability() == (10, 7) + and config.recv_capacity_per_rank == _TILE + ): + # Some SM 10.7 MXFP8 weight gradients need more than one receive tile; one into + # main_grad counts as added. Only a weight that gets a gradient runs such a kernel. + for fc in (fc1_op, fc2_op): + if fc.weight.requires_grad: + reason = _mxfp8_wgrad_unsupported_reason( + fc.out_features, fc.in_features, config.num_local_experts, + fc._accumulate_into_main_grad, + ) # fmt: skip + if reason is not None: + raise RuntimeError(f"FusedMoE is not supported: {reason}.") + def _save_for_backward(self, basic_op_ctxs, buffer, row_tensors, other_tensors, topk_weights): """Save the tensors the backward reads, when any output needs a gradient. The operands of the weight gradient of a frozen weight are not saved.""" @@ -281,17 +301,12 @@ def _save_for_backward(self, basic_op_ctxs, buffer, row_tensors, other_tensors, fc1_ctx.topk_weights_shape = topk_weights.shape def _weight_operands(self, idx, columnwise): - """GEMM operands of the weight of the GroupedLinear at ``idx``: its ``_MxFp8Weight``, or - the BF16 weight. Prepared fresh at each forward.""" + """GEMM operands of the weight of the GroupedLinear at ``idx``, as ``_MxFp8WeightOperands`` + or the BF16 weight. Prepared fresh at each forward.""" fc_op = self.basic_ops[idx] - # TODO(phuonguyen): drop the FC1 reorder, here and in the backward, once cuDNN upstream - # supports glu_interleave_size=None. - reorder = self._reorder_glu and idx == 1 - if not (self._mxfp8 or reorder): - return _bf16_weight(fc_op, fc_op.num_groups) if self._mxfp8: - return _mxfp8_weight(fc_op, fc_op.num_groups, columnwise, reorder_glu=reorder) - return _interleave_glu_rows(_bf16_weight(fc_op, fc_op.num_groups)) + return _mxfp8_weight_operands(fc_op, fc_op.num_groups, columnwise) + return _bf16_weight(fc_op, fc_op.num_groups) def fuser_backward( self, @@ -308,7 +323,7 @@ def fuser_backward( return self._backward_mxfp8(basic_op_ctxs, grad_output, grad_recv_weights_extra) _, fc1_op, _, fc2_op, _ = self.basic_ops dispatch_ctx, fc1_ctx, _, fc2_ctx, _ = basic_op_ctxs - recv_tokens, gemm_out, act_out, recv_weights, *w1 = fc1_ctx.saved_tensors + recv_tokens, gemm_out, act_out, recv_weights = fc1_ctx.saved_tensors buffer = fc1_ctx.buffer device = buffer.device num_groups = fc1_op.num_groups @@ -316,7 +331,7 @@ def fuser_backward( ffn = fc2_op.in_features rows = gemm_out.shape[0] tokens_per_expert = buffer.tokens_per_expert_i32 - w1 = w1[0] if w1 else _bf16_weight(fc1_op, num_groups) + w1 = _bf16_weight(fc1_op, num_groups) w2 = _bf16_weight(fc2_op, num_groups) grad_result = _bf16_grad_output(grad_output) num_tokens = grad_result.shape[0] @@ -330,7 +345,7 @@ def fuser_backward( fc2_grads = None fc2_wgrad = _CallWgrad() if fc2_ctx.weight_requires_grad: - fc2_grads = grad_params(fc2_op, fc2_ctx, act_out, grad_expert_out, "FC2", fc2_wgrad) + fc2_grads = grad_params(fc2_op, fc2_ctx, act_out, None, "FC2", fc2_wgrad) tex.ep_combine_gemm_bwd( buffer.handle_mem, grad_result, gemm_out, recv_weights, tokens_per_expert, w2, grad_expert_out, grad_gemm, grad_recv_weights, buffer.top_k, buffer.alignment, @@ -345,9 +360,8 @@ def fuser_backward( if grad_recv_weights_extra is not None: grad_recv_weights.add_(grad_recv_weights_extra.to(torch.float32)) fc1_wgrad = _CallWgrad() - # The weight gradient of reordered FC1 rows is computed after the reorder back. - if not self._reorder_glu and fc1_ctx.weight_requires_grad: - fc1_grads = grad_params(fc1_op, fc1_ctx, recv_tokens, grad_gemm, "FC1", fc1_wgrad) + if fc1_ctx.weight_requires_grad: + fc1_grads = grad_params(fc1_op, fc1_ctx, recv_tokens, None, "FC1", fc1_wgrad) grad_recv = torch.empty(rows, hidden, dtype=torch.bfloat16, device=device) grad_tokens = torch.empty(num_tokens, hidden, dtype=torch.bfloat16, device=device) grad_topk = torch.empty(fc1_ctx.topk_weights_shape, dtype=torch.float32, device=device) @@ -358,8 +372,6 @@ def fuser_backward( ) # fmt: skip if fc1_grads is None: - if fc1_ctx.weight_requires_grad and self._reorder_glu: - grad_gemm = _deinterleave_glu_columns(grad_gemm) fc1_grads = grad_params(fc1_op, fc1_ctx, recv_tokens, grad_gemm, "FC1") clear_tensor_data(recv_tokens, act_out) @@ -370,9 +382,9 @@ def _grad_params( tokens_per_expert, ): # fmt: skip """Parameter gradients of ``fc_op``, in registration order. With ``wgrad_args`` the weight - gradient is computed by the backward call from the operands recorded there; otherwise it - is computed here from ``grouped_x`` and ``grouped_dy``, which a frozen weight does not - read.""" + gradient is computed by the backward call, and ``grouped_x`` is its input, recorded there; + otherwise it is computed here from ``grouped_x`` and ``grouped_dy``. A frozen weight reads + neither.""" num_groups = fc_op.num_groups shape = (fc_op.out_features, fc_op.in_features) mxfp8 = self._mxfp8 @@ -417,16 +429,14 @@ def _backward_mxfp8(self, basic_op_ctxs, grad_output, grad_recv_weights_extra=No """Backward with MXFP8 GEMMs and EP transport.""" _, fc1_op, _, fc2_op, _ = self.basic_ops dispatch_ctx, fc1_ctx, _, fc2_ctx, _ = basic_op_ctxs + operands = self._operands ( - recv_tokens, - recv_scale, - gemm_out, - recv_weights, - w1_col, - w1_col_scale, - w2_col, + recv_data, recv_scale, gemm_out, recv_weights, w1_col, w1_col_scale, w2_col, w2_col_scale, - ) = fc1_ctx.saved_tensors + ) = fc1_ctx.saved_tensors # fmt: skip + recv_tokens = _make_mxfp8_storage(recv_data, recv_scale) + w1 = _make_mxfp8_storage(columnwise=(w1_col, w1_col_scale), swizzled=True) + w2 = _make_mxfp8_storage(columnwise=(w2_col, w2_col_scale), swizzled=True) buffer = fc1_ctx.buffer device = buffer.device num_groups = fc1_op.num_groups @@ -434,93 +444,73 @@ def _backward_mxfp8(self, basic_op_ctxs, grad_output, grad_recv_weights_extra=No ffn = fc2_op.in_features rows = gemm_out.shape[0] tokens_per_expert = buffer.tokens_per_expert_i32 - # GroupedTensor group sizes are int64. + # Grouped tensor group sizes are int64. first_dims = tokens_per_expert.long() grad_result = _bf16_grad_output(grad_output) num_tokens = grad_result.shape[0] - grad_result, grad_result_scale, symm_input = _quantize_for_dispatch(grad_result, device) + grad_result, symm_input = operands.dispatch_input(grad_result, device) - def fp8_rows(cols): - data = torch.empty(rows, cols, dtype=torch.float8_e4m3fn, device=device) - return data, torch.empty(rows * cols // _SF_VEC, dtype=torch.uint8, device=device) + def empty(quantizer, cols): + return quantizer.make_empty((rows, cols), dtype=torch.bfloat16, device=device) - grad_expert_out, grad_expert_out_scale = fp8_rows(hidden) - grad_expert_out_scale = grad_expert_out_scale.view(rows, hidden // _SF_VEC) - grad_gemm, grad_gemm_scale = fp8_rows(2 * ffn) + # The call writes the columnwise grad_expert_out for the FC2 weight gradient. + grad_expert_out = empty( + operands.transport_columnwise if fc2_ctx.weight_requires_grad else operands.transport, + hidden, + ) + grad_gemm = empty(operands.gemm_both, 2 * ffn) # The columnwise grad_gemm_out feeds the FC1 weight gradient and act_out the FC2 one, so a # frozen weight reads neither. TODO(phuonguyen): skip the unused one once the cuDNN FE dGLU # kernel makes its columnwise D output optional (a generate_d_col flag like generate_h). - grad_gemm_col, grad_gemm_col_scale = fp8_rows(2 * ffn) - act_col, act_col_scale = fp8_rows(ffn) + act_col = empty(operands.gemm_columnwise, ffn) grad_recv_weights = torch.empty(rows, dtype=torch.float32, device=device) grad_params = functools.partial( self._grad_params, device=device, tokens_per_expert=tokens_per_expert ) - def grouped(cols, data, scale, col_data, col_scale, in_call): - # Expert slabs of a row-sized MXFP8 tensor with GEMM-swizzled scales. A weight - # gradient in a backward call reads no tensor offsets. - return GroupedTensor( + def grouped(cols, data, scale, col_data, col_scale): + # Expert slabs of a row-sized MXFP8 tensor with GEMM-swizzled scales. + return GroupedTensorStorage( shape=(rows, cols), dtype=torch.bfloat16, num_tensors=num_groups, - quantizer=_ep_quantizer(), data=data, columnwise_data=col_data.view(-1), + quantizer=operands.transport, data=data, columnwise_data=col_data.view(-1), scale_inv=scale, columnwise_scale_inv=col_scale, first_dims=first_dims, - tensor_offsets=None if in_call else tex.splits_to_offsets(first_dims, cols), + tensor_offsets=tex.splits_to_offsets(first_dims, cols), with_gemm_swizzled_scales=True, ) # fmt: skip def fc1_grad_params(wgrad_args=None): if not fc1_ctx.weight_requires_grad: return grad_params(fc1_op, fc1_ctx, None, None, "FC1") - in_call = wgrad_args is not None - if in_call: + if wgrad_args is not None: # The call writes the columnwise received rows from their rowwise copy. - x_col, x_col_scale = fp8_rows(hidden) - grouped_x = grouped(hidden, None, None, x_col, x_col_scale, True) - wgrad_args.update( - wgrad_input_rowwise=recv_tokens, wgrad_input_rowwise_scale_inv=recv_scale + x_col = empty(operands.gemm_columnwise, hidden) + # Its rowwise half keeps compact scales although the storage is marked swizzled. + wgrad_input = _make_mxfp8_storage( + recv_data, + recv_scale, + columnwise=(x_col._columnwise_data, x_col._columnwise_scale_inv), + swizzled=True, ) - else: - grouped_x = _columnwise_rows(recv_tokens, recv_scale, first_dims) - grad_gemm_cols = ( - grouped(2 * ffn, None, None, _deinterleave_glu_columns(grad_gemm_col), - _deinterleave_glu_col_scales(grad_gemm_col_scale, tokens_per_expert, - 2 * ffn), in_call) - if self._reorder_glu - else grouped(2 * ffn, grad_gemm.view(-1), grad_gemm_scale, grad_gemm_col, - grad_gemm_col_scale, in_call) + return grad_params(fc1_op, fc1_ctx, wgrad_input, None, "FC1", wgrad_args) + grad_gemm_cols = grouped( + 2 * ffn, grad_gemm._rowwise_data.view(-1), grad_gemm._rowwise_scale_inv.view(-1), + grad_gemm._columnwise_data, grad_gemm._columnwise_scale_inv.view(-1), ) # fmt: skip return grad_params( - fc1_op, fc1_ctx, grouped_x, grad_gemm_cols, "FC1", wgrad_args + fc1_op, fc1_ctx, _with_columnwise_data(recv_tokens, first_dims, operands), + grad_gemm_cols, "FC1", ) # fmt: skip - # The call computes the FC2 weight gradient too, and writes the received rows columnwise - # for it. fc2_wgrad = _CallWgrad() - grad_expert_out_cols = {} if fc2_ctx.weight_requires_grad: - grad_expert_out_col, grad_expert_out_col_scale = fp8_rows(hidden) - grad_expert_out_cols = { - "grad_expert_out_columnwise": grad_expert_out_col, - "grad_expert_out_columnwise_scale_inv": grad_expert_out_col_scale, - } - fc2_grads = grad_params( - fc2_op, fc2_ctx, grouped(ffn, None, None, act_col, act_col_scale, True), - grouped(hidden, None, None, grad_expert_out_col, grad_expert_out_col_scale, True), - "FC2", fc2_wgrad, - ) # fmt: skip + fc2_grads = grad_params(fc2_op, fc2_ctx, act_col, None, "FC2", fc2_wgrad) else: fc2_grads = grad_params(fc2_op, fc2_ctx, None, None, "FC2") tex.ep_combine_gemm_bwd( - buffer.handle_mem, grad_result, gemm_out, - recv_weights, tokens_per_expert, w2_col, grad_expert_out, grad_gemm, - grad_recv_weights, buffer.top_k, buffer.alignment, buffer.topk_idx_dtype, - grad_result_scale_inv=grad_result_scale, - grad_expert_out_scale_inv=grad_expert_out_scale, weight_scale_inv=w2_col_scale, - grad_gemm_out_scale_inv=grad_gemm_scale, grad_gemm_out_columnwise=grad_gemm_col, - grad_gemm_out_columnwise_scale_inv=grad_gemm_col_scale, act_out=act_col, - act_out_scale_inv=act_col_scale, **grad_expert_out_cols, **fc2_wgrad, - symm_input=symm_input, + buffer.handle_mem, grad_result, gemm_out, recv_weights, tokens_per_expert, w2, + grad_expert_out, grad_gemm, grad_recv_weights, buffer.top_k, buffer.alignment, + buffer.topk_idx_dtype, act_out=act_col, symm_input=symm_input, **fc2_wgrad, ) # fmt: skip grad_tokens = grad_topk = fc1_grads = None @@ -528,131 +518,125 @@ def fc1_grad_params(wgrad_args=None): if grad_recv_weights_extra is not None: grad_recv_weights.add_(grad_recv_weights_extra.to(torch.float32)) fc1_wgrad = _CallWgrad() - # The weight gradient of reordered FC1 rows is computed after the reorder back. - if not self._reorder_glu and fc1_ctx.weight_requires_grad: - fc1_wgrad.update( - grad_gemm_out_columnwise=grad_gemm_col, - grad_gemm_out_columnwise_scale_inv=grad_gemm_col_scale, - ) + if fc1_ctx.weight_requires_grad: fc1_grads = fc1_grad_params(fc1_wgrad) grad_recv = torch.empty(rows, hidden, dtype=torch.bfloat16, device=device) grad_tokens = torch.empty(num_tokens, hidden, dtype=torch.bfloat16, device=device) grad_topk = torch.empty(fc1_ctx.topk_weights_shape, dtype=torch.float32, device=device) + # The columnwise grad_gemm_out is read only by the in-call weight gradient. tex.ep_dispatch_gemm_bwd( - buffer.handle_mem, grad_gemm, grad_recv_weights, tokens_per_expert, w1_col, - grad_recv, grad_tokens, grad_topk, buffer.top_k, buffer.alignment, - buffer.topk_idx_dtype, grad_gemm_out_scale_inv=grad_gemm_scale, - weight_scale_inv=w1_col_scale, **fc1_wgrad, + buffer.handle_mem, grad_gemm if fc1_wgrad else _rowwise_only(grad_gemm), + grad_recv_weights, tokens_per_expert, w1, grad_recv, grad_tokens, grad_topk, + buffer.top_k, buffer.alignment, buffer.topk_idx_dtype, **fc1_wgrad, ) # fmt: skip if fc1_grads is None: fc1_grads = fc1_grad_params() - clear_tensor_data(recv_tokens, recv_scale) + clear_tensor_data(recv_data, recv_scale) return self._finish_backward(grad_tokens, grad_topk, fc1_grads, fc2_grads) class _Bf16Operands: """Operands of the forward GEMM calls with BF16 GEMMs and EP transport.""" - scale_names = () # Positions in the saved row tensors: the inputs of the FC1 and FC2 weight gradients, which a # frozen weight does not need, and the activations CPU offload takes. fc1_wgrad_inputs = (0,) fc2_wgrad_inputs = (2,) offload_slots = (0, 1, 2) - def __init__(self, reorder_glu: bool) -> None: - self.reorder_glu = reorder_glu - @staticmethod def dispatch_input(input_, device): - """Dispatch input and the keyword arguments it adds to the dispatch GEMM call.""" + """Dispatch input and whether the dispatch reads it in place from a symm-mem window.""" del device - return input_, {} + return input_, False @staticmethod - def weight(weight): - """GEMM operand of a weight and the keyword arguments it adds to the call.""" - return weight, {} + def forward_weight(weight): + """GEMM operand of a weight.""" + return weight @staticmethod def recv_buffers(rows, hidden, ffn, device): - """Receive buffers of a fixed capacity: recv tokens, GEMM output, activation output and - a dict of scale buffers named as the dispatch GEMM call's keyword arguments.""" + """Receive buffers of a fixed capacity: recv tokens, GEMM output and activation output.""" return ( torch.empty(rows, hidden, dtype=torch.bfloat16, device=device), torch.empty(rows, 2 * ffn, dtype=torch.bfloat16, device=device), torch.empty(rows, ffn, dtype=torch.bfloat16, device=device), - {}, ) @staticmethod - def combine_kwargs(recv_weights, scales): - """Keyword arguments the combine GEMM call adds.""" - del recv_weights, scales - return {} + def combine_recv_weights(recv_weights): + """Routing weights the combine GEMM call scales its output rows with: none, as the + activation applies them.""" + del recv_weights - def saved_tensors(self, recv_tokens, recv_weights, gemm_out, act_out, scales, w1, w2, backward): + @staticmethod + def saved_tensors(recv_tokens, recv_weights, gemm_out, act_out, w1, w2, backward): """Row-sized tensors and the other tensors saved for the backward.""" - del scales, w2, backward + del w1, w2, backward # The BF16 SwiGLU backward GEMM cannot write the SwiGLU output, so the FC2 wgrad reads it. - return (recv_tokens, gemm_out, act_out, recv_weights), (w1,) if self.reorder_glu else () + return (recv_tokens, gemm_out, act_out, recv_weights), () class _Mxfp8Operands: """Operands of the forward GEMM calls with MXFP8 GEMMs and EP transport.""" - scale_names = ("recv_scale_inv", "act_out_scale_inv") fc1_wgrad_inputs = (0, 1) fc2_wgrad_inputs = () offload_slots = (0, 1, 2) - @staticmethod - def dispatch_input(input_, device): - """Dispatch input quantized to MXFP8, with its scales.""" - tokens, tokens_scale, symm_input = _quantize_for_dispatch(input_, device) - return tokens, {"tokens_scale_inv": tokens_scale, "symm_input": symm_input} + def __init__(self) -> None: + # Transport tensors have compact scales, GEMM operands GEMM-swizzled ones. + self.transport = _mxfp8_quantizer(rowwise=True, columnwise=False, swizzled=False) + self.transport_columnwise = _mxfp8_quantizer(rowwise=True, columnwise=True, swizzled=False) + self.gemm_rowwise = _mxfp8_quantizer(rowwise=True, columnwise=False, swizzled=True) + self.gemm_both = _mxfp8_quantizer(rowwise=True, columnwise=True, swizzled=True) + self.gemm_columnwise = _mxfp8_quantizer(rowwise=False, columnwise=True, swizzled=True) + + def dispatch_input(self, input_, device): + """Dispatch input quantized to MXFP8, and whether the dispatch reads it in place from a + symm-mem window: the quantized rows are in the window whenever it exists, alike on every + rank.""" + window = _sym_dispatch_buffers(device, self.transport) + quantized, _ = quantize_for_ep(input_, self.transport, window) + return quantized, window is not None @staticmethod - def weight(weight): - """MXFP8 data of a weight and its scales.""" - return weight.data, {"weight_scale_inv": weight.scale_inv} + def forward_weight(weight): + """Rowwise MXFP8 operand of a weight.""" + return weight.rowwise - @staticmethod - def recv_buffers(rows, hidden, ffn, device): - """MXFP8 recv tokens and activation output, with their scale buffers.""" - fp8 = torch.float8_e4m3fn + def recv_buffers(self, rows, hidden, ffn, device): + """MXFP8 recv tokens, BF16 GEMM output and MXFP8 activation output.""" return ( - torch.empty(rows, hidden, dtype=fp8, device=device), + self.transport.make_empty((rows, hidden), dtype=torch.bfloat16, device=device), torch.empty(rows, 2 * ffn, dtype=torch.bfloat16, device=device), - torch.empty(rows, ffn, dtype=fp8, device=device), - { - "recv_scale_inv": torch.empty( - rows, hidden // _SF_VEC, dtype=torch.uint8, device=device - ), - "act_out_scale_inv": torch.empty( - rows * ffn // _SF_VEC, dtype=torch.uint8, device=device - ), - }, + self.gemm_rowwise.make_empty((rows, ffn), dtype=torch.bfloat16, device=device), ) @staticmethod - def combine_kwargs(recv_weights, scales): + def combine_recv_weights(recv_weights): """The routing weights scale the second GEMM's output rows.""" - return {"recv_topk_weights": recv_weights, "gemm_in_scale_inv": scales["act_out_scale_inv"]} + return recv_weights @staticmethod - def saved_tensors(recv_tokens, recv_weights, gemm_out, act_out, scales, w1, w2, backward): + def saved_tensors(recv_tokens, recv_weights, gemm_out, act_out, w1, w2, backward): """Tensors saved for the backward; the FC2 dgrad recomputes the SwiGLU output for the FC2 wgrad, so it is not saved.""" del act_out - return (recv_tokens, scales["recv_scale_inv"], gemm_out, recv_weights), ( + return ( + recv_tokens._rowwise_data, + recv_tokens._rowwise_scale_inv, + gemm_out, + recv_weights, + ), ( ( - w1.columnwise_data, - w1.columnwise_scale_inv, - w2.columnwise_data, - w2.columnwise_scale_inv, + w1.columnwise._columnwise_data, + w1.columnwise._columnwise_scale_inv, + w2.columnwise._columnwise_data, + w2.columnwise._columnwise_scale_inv, ) if backward else () @@ -675,25 +659,17 @@ def _bf16_grad_output(grad_output) -> torch.Tensor: class _CallWgrad(dict): """Keyword arguments of a weight gradient computed inside a backward call, passed as - ``**wgrad``. Its wgrad factory only records the operands; the call runs the kernel later, so - distributed weights, which FusedMoE rejects, do not fit.""" + ``**wgrad``. Its wgrad factory only records the input and the output; the call runs the kernel + later, so distributed weights, which FusedMoE rejects, do not fit.""" def gemm_fn_factory(self, num_groups: int, weight_shape) -> Callable: """Wgrad factory that records the operands of a weight of shape ``weight_shape``.""" def factory(accumulate: bool) -> Callable: - def gemm_fn(grouped_x, grouped_dy, wgrad_output): + def gemm_fn(wgrad_input, grouped_dy, wgrad_output): del grouped_dy - if isinstance(grouped_x, GroupedTensor): - self.update( - wgrad_input=grouped_x.columnwise_data.view(torch.float8_e4m3fn).view( - -1, weight_shape[1] - ), - wgrad_input_scale_inv=grouped_x.columnwise_scale_inv, - ) - else: - self.update(wgrad_input=grouped_x) self.update( + wgrad_input=wgrad_input, weight_grad=wgrad_output.rowwise_data.view(num_groups, *weight_shape), accumulate_weight_grad=accumulate, ) @@ -708,13 +684,12 @@ def require_recorded(self) -> None: raise RuntimeError("FusedMoE: the weight-gradient GEMM function was not called.") -class _MxFp8Weight(NamedTuple): - """MXFP8 operands of a weight: data and scales, rowwise and, when prepared, columnwise.""" +class _MxFp8WeightOperands(NamedTuple): + """MXFP8 operands of a weight [num_groups, out_features, in_features]: rowwise and, when + prepared for the backward, columnwise.""" - data: torch.Tensor - scale_inv: torch.Tensor - columnwise_data: Optional[torch.Tensor] = None - columnwise_scale_inv: Optional[torch.Tensor] = None + rowwise: MXFP8TensorStorage + columnwise: Optional[MXFP8TensorStorage] = None def _gemm_interface_reason(mxfp8: bool = False) -> Optional[str]: @@ -728,85 +703,91 @@ def _gemm_interface_reason(mxfp8: bool = False) -> Optional[str]: return gemm_interface_reason(mxfp8) -def _ep_quantizer() -> MXFP8Quantizer: - """Rowwise E4M3 quantizer of the MXFP8 EP transport.""" - quantizer = MXFP8Quantizer(tex.DType.kFloat8E4M3, rowwise=True, columnwise=False) +def _mxfp8_quantizer(*, rowwise: bool, columnwise: bool, swizzled: bool) -> MXFP8Quantizer: + """E4M3 quantizer of the MXFP8 EP transport and GEMM operands; it makes internal storages.""" + quantizer = MXFP8Quantizer(DType.kFloat8E4M3, rowwise=rowwise, columnwise=columnwise) quantizer.internal = True + quantizer.optimize_for_gemm = swizzled return quantizer -def _quantize_for_dispatch(input_, device): - """MXFP8 data and compact scales of a dispatch input, and whether the dispatch reads them in - place: they are in the EP dispatch window whenever it exists, alike on every rank.""" - window = _dispatch_window(device) - quantized, scale = quantize_for_ep(input_, _ep_quantizer(), window) - return quantized._rowwise_data.view(torch.float8_e4m3fn), scale, window is not None +def _make_mxfp8_storage( + rowwise: Optional[torch.Tensor] = None, + rowwise_scale_inv: Optional[torch.Tensor] = None, + *, + columnwise: Optional[tuple[torch.Tensor, torch.Tensor]] = None, + swizzled: bool = False, +) -> MXFP8TensorStorage: + """MXFP8 storage of rowwise data and scales and, as a (data, scales) pair, columnwise ones.""" + col_data, col_scale = columnwise if columnwise is not None else (None, None) + return MXFP8TensorStorage( + rowwise, rowwise_scale_inv, col_data, col_scale, DType.kFloat8E4M3, None, swizzled, + fake_dtype=torch.bfloat16, + ) # fmt: skip -def _columnwise_rows(data, scale, tokens_per_expert): - """Expert slabs of received MXFP8 rows with compact scales, given columnwise data for the - weight gradient.""" - grouped = _make_grouped_mxfp8( - data, scale, tokens_per_expert, tex.DType.kFloat8E4M3, torch.bfloat16 - ) - quantizer = _ep_quantizer() - quantizer.set_usage(rowwise=True, columnwise=True) - quantizer.optimize_for_gemm = True +def _rowwise_only(tensor: MXFP8TensorStorage) -> MXFP8TensorStorage: + """The rowwise part of an MXFP8 storage.""" + return MXFP8TensorStorage( + tensor._rowwise_data, tensor._rowwise_scale_inv, None, None, tensor._fp8_dtype, None, + tensor._with_gemm_swizzled_scales, fake_dtype=torch.bfloat16, + ) # fmt: skip + + +def _with_columnwise_data(recv_tokens, first_dims, operands): + """Expert slabs of received MXFP8 rows with compact scales, given the columnwise data and + GEMM-swizzled scales of the weight gradient.""" + rows, hidden = recv_tokens._rowwise_data.shape + grouped = GroupedTensorStorage( + shape=(rows, hidden), dtype=torch.bfloat16, num_tensors=first_dims.numel(), + quantizer=operands.transport, data=recv_tokens._rowwise_data.view(-1), + scale_inv=recv_tokens._rowwise_scale_inv.view(-1), first_dims=first_dims, + tensor_offsets=tex.splits_to_offsets(first_dims, hidden), + ) # fmt: skip tex.group_requantize_inplace( - grouped, quantizer, tokens_per_expert.numel(), tokens_per_expert, tex.DType.kBFloat16, + grouped, operands.gemm_both, first_dims.numel(), first_dims, DType.kBFloat16, tensor_offsets=grouped.tensor_offsets, ) # fmt: skip return grouped -def _mxfp8_weight( - fc_op: GroupedLinear, num_groups: int, columnwise: bool, reorder_glu: bool = False -) -> _MxFp8Weight: +def _mxfp8_weight_operands( + fc_op: GroupedLinear, num_groups: int, columnwise: bool +) -> _MxFp8WeightOperands: """GEMM operands of the weight quantized to MXFP8, with the columnwise ones when asked; data - is [num_groups, out_features, in_features]. + is flat; the bindings shape it as [num_groups, out_features, in_features]. BF16 weights are quantized with GEMM-swizzled scales; the scales of MXFP8 weight parameters - are swizzled into a copy. Each direction is swizzled along its own scaling axis. - ``reorder_glu`` reorders FC1 rows as ``_interleave_glu_rows`` does, data and scales alike.""" + are swizzled into a copy. Each direction is swizzled along its own scaling axis.""" weight = fc_op.weight - shape = (num_groups, fc_op.out_features, fc_op.in_features) if weight.quantizer is not None: # Only add usages, never drop: later weight updates keep what this op needs. weight.quantizer.set_usage(rowwise=True, columnwise=True if columnwise else None) if columnwise and weight.columnwise_data is None: raise RuntimeError("FusedMoE needs columnwise data in the MXFP8 weight parameters.") weight = weight.copy() - if reorder_glu: - # Rowwise scales follow the rows; a columnwise scale row covers one block of rows. - rows, cols = shape[1:] - weight.rowwise_data = _interleave_glu_rows(weight.rowwise_data.view(shape)).view(-1) - weight.scale_inv = _interleave_glu_rows( - weight.scale_inv.view(num_groups, rows, -1) - ).view(-1) - if weight.columnwise_data is not None: - weight.columnwise_data = _interleave_glu_rows( - weight.columnwise_data.view(shape) - ).view(-1) - weight.columnwise_scale_inv = _interleave_glu_rows( - weight.columnwise_scale_inv.view(num_groups, rows // _SF_VEC, cols), - block=_GLU_BLOCK // _SF_VEC, - ).view(-1) tex.grouped_swizzle_for_gemm(weight, rowwise=True, columnwise=columnwise) else: quantizer = fc_op.get_quantizer("forward", 1).copy() quantizer.set_usage(rowwise=True, columnwise=columnwise) quantizer.optimize_for_gemm = True - data = weight.rowwise_data.view(shape) - if reorder_glu: - data = _interleave_glu_rows(data) - weight = tex.group_quantize(data.view(weight.logical_shape), quantizer, num_groups, None) - fp8 = torch.float8_e4m3fn - operands = _MxFp8Weight(weight.rowwise_data.view(fp8).view(shape), weight.scale_inv.reshape(-1)) - if columnwise: - operands = operands._replace( - columnwise_data=weight.columnwise_data.view(fp8).view(shape), - columnwise_scale_inv=weight.columnwise_scale_inv.reshape(-1), + weight = tex.group_quantize( + weight.rowwise_data.view(weight.logical_shape), quantizer, num_groups, None ) - return operands + uint8 = torch.uint8 + return _MxFp8WeightOperands( + _make_mxfp8_storage(weight.rowwise_data.view(uint8), weight.scale_inv, swizzled=True), + ( + _make_mxfp8_storage( + columnwise=( + weight.columnwise_data.view(uint8), + weight.columnwise_scale_inv, + ), + swizzled=True, + ) + if columnwise + else None + ), + ) def _bf16_weight(fc_op: GroupedLinear, num_groups: int) -> torch.Tensor: @@ -815,51 +796,6 @@ def _bf16_weight(fc_op: GroupedLinear, num_groups: int) -> torch.Tensor: return _bf16_packed_weight(fc_op, num_groups).to(torch.bfloat16) -# TODO(phuonguyen): the cuDNN GEMMs require the interleaved GLU layout, so FC1 weights are reordered -# here. Drop this reorder and pass the non-interleaved layout through once cuDNN supports it. -def _interleave_glu_rows(t: torch.Tensor, block: int = _GLU_BLOCK) -> torch.Tensor: - """Copy of per-expert rows [experts, 2 * n, ...], gate rows then up rows, with gate and up - alternating in blocks of ``block`` rows, the GLU layout of ``glu_interleave_size=32``.""" - experts, rows = t.shape[:2] - blocks = t.reshape(experts, 2, rows // (2 * block), block, *t.shape[2:]) - return blocks.transpose(1, 2).reshape(t.shape) - - -def _deinterleave_glu_columns(t: torch.Tensor) -> torch.Tensor: - """Copy of [rows, 2 * n] with gate and up in alternating column blocks, gate columns first.""" - rows, cols = t.shape - # Moved in 16-byte words (complex128); a column block spans whole words. - words = t.view(torch.complex128) - blocks = words.reshape(rows, cols // (2 * _GLU_BLOCK), 2, _GLU_BLOCK * t.element_size() // 16) - return blocks.transpose(1, 2).reshape(rows, -1).view(t.dtype) - - -def _deinterleave_glu_col_scales(scale, tokens_per_expert, cols): - """Columnwise MXFP8 scales, swizzled per expert, of a tensor reordered by - ``_deinterleave_glu_columns``.""" - tiles = cols // 128 - blocks = scale.view(torch.int32).view(-1, 128) - units = blocks.shape[0] // tiles # 128-row units - device = scale.device - # First unit and unit count of each unit's expert; the rows after the experts form a last group. - ends = tokens_per_expert.cumsum(0) // 128 - starts = torch.nn.functional.pad(ends, (1, 0)) - stops = torch.nn.functional.pad(ends, (0, 1), value=units) - unit = torch.arange(units, device=device) - group = torch.searchsorted(stops, unit, right=True) - first = starts[group] - count = stops[group] - first - # Block of each (tile, unit) in the slabs. - tile = torch.arange(tiles, device=device)[:, None] - index = (torch.add(unit, first, alpha=tiles - 1) + tile * count).view(-1) - # Tile 2 * i + h holds column blocks 8 * i + 4 * h + 2 * j + g, of gate (g = 0) or up (g = 1), - # which go to tile g * tiles / 2 + i at slot 2 * h + j. - src = blocks[index].view(tiles // 2, 2, units, 32, 2, 2) - out = torch.empty_like(blocks) - out[index] = src.permute(5, 0, 2, 3, 1, 4).reshape(-1, 128) - return out.view(torch.uint8).view(scale.shape) - - def _routing_extras_internal(dispatch, fc1, activation, fc2) -> bool: """Whether tokens_per_expert and the routing weights flow from the dispatch to the MLP.""" channels = dispatch._extra_output_channels @@ -888,9 +824,8 @@ def _moe_overlap_unsupported_reason( """Why a ``Sequential`` of ``MoeDispatch``, ``GroupedLinear``, ``ScaledSwiGLU``, ``GroupedLinear`` and ``MoeCombine`` built with these settings does not run as one ``FusedMoE``, or ``None`` when it does. The reason names an unsupported setting or the - grouped GEMM backend failing to load on this device. It only queries the device; - deterministic execution and an autocast dtype other than BF16 are unsupported, and the answer - follows the settings in effect at the call. + grouped GEMM backend failing to load on this device. It only queries the device and the + static settings; those that can change between calls are checked when the op runs. Parameters ---------- @@ -903,7 +838,7 @@ def _moe_overlap_unsupported_reason( activation : str, default = "swiglu" Activation between the GroupedLinear ops. glu_interleave_size : int, optional - ``glu_interleave_size`` of the ``ScaledSwiGLU``, ``None`` or 32. + ``glu_interleave_size`` of the ``ScaledSwiGLU``; must be 32. bias : bool, default = ``False`` Whether the GroupedLinear ops have biases. single_grouped_weight : bool, default = ``False`` @@ -922,21 +857,12 @@ def _moe_overlap_unsupported_reason( ) mismatch = _gemm_interface_reason() if _moe_overlap_available() else None return f"{reason}: {mismatch}" if mismatch else reason - # TODO(phuonguyen): drop this gate once the routing-weight gradient is reworked to avoid the - # atomic reduction, which makes it reproducible under deterministic execution. - if _deterministic_algorithms_required(): - return ( - "deterministic execution was requested, and the routing-weight gradient is reduced" - " with atomics" - ) - if torch.is_autocast_enabled() and torch.get_autocast_dtype("cuda") != torch.bfloat16: - return "needs a BF16 autocast dtype" if config.payload_dtype is not torch.bfloat16: return "needs a BF16 payload" alignments = (64, 128, _TILE) if isinstance(recipe, MXFP8BlockScaling): # The SM 10.7 MXFP8 GEMMs have no tail tiles. - alignments = (_TILE,) if torch.cuda.get_device_capability() == (10, 7) else (128, _TILE) + alignments = (_TILE,) if get_device_compute_capability() == (10, 7) else (128, _TILE) # TODO(phuonguyen): the cuDNN FE grouped GEMMs have no tail-tile kernels, so every expert must # pad to a full 256-row tile. Delete this line to restore 64/128 alignment once tail-tiles land. alignments = (_TILE,) @@ -979,8 +905,8 @@ def _moe_overlap_unsupported_reason( return "ffn_hidden_size must be a multiple of 64" if activation != "swiglu": return "needs the SwiGLU activation" - if glu_interleave_size not in (None, _GLU_BLOCK): - return f"needs glu_interleave_size None or {_GLU_BLOCK}" + if glu_interleave_size != _GLU_BLOCK: + return f"needs glu_interleave_size {_GLU_BLOCK}" if not single_grouped_weight: return "needs single_grouped_weight=True" if bias: @@ -992,6 +918,24 @@ def _moe_overlap_unsupported_reason( return None +@functools.lru_cache(maxsize=None) +def _mxfp8_wgrad_unsupported_reason( + out_features: int, in_features: int, num_local_experts: int, accumulate: bool +) -> Optional[str]: + """Why the MXFP8 weight-gradient kernel of one receive tile does not build, or ``None``.""" + from ....common.CuTeDSL.ep_gemm import wgrad_gemm # pylint: disable=import-outside-toplevel + + cfg = wgrad_gemm.WgradConfig( + _TILE, out_features, in_features, num_local_experts, 1, + accumulate=accumulate, scaling_mode=wgrad_gemm.MXFP8_1D_SCALING, + ) # fmt: skip + try: + wgrad_gemm.build_kernel(cfg) + except ValueError as err: + return str(err) + return None + + def _unsupported_reason(dispatch, fc1, activation, fc2, combine, recipe=None) -> Optional[str]: """Why a window cannot use the overlapped ops, or ``None`` when it can.""" config = dispatch.config @@ -1026,10 +970,6 @@ def _unsupported_reason(dispatch, fc1, activation, fc2, combine, recipe=None) -> return "the dispatch extra outputs must feed the grouped MLP and not the caller" if any(is_distributed_weight(fc.weight) for fc in (fc1, fc2)): return "distributed (sharded) weights are not supported" - if any( - fc.wgrad_store is not None and fc.wgrad_store.delay_wgrad_compute() for fc in (fc1, fc2) - ): - return "delayed weight gradient computation (delay_wgrad_compute) is not supported" try: # The GLU layout is checked above. validate_grouped_mlp_dims(fc1, ScaledSwiGLU(glu_interleave_size=_GLU_BLOCK), fc2) @@ -1037,31 +977,6 @@ def _unsupported_reason(dispatch, fc1, activation, fc2, combine, recipe=None) -> return str(err) if fc1.in_features != config.hidden_dim or fc2.out_features != config.hidden_dim: return "the GroupedLinear sizes do not match the EP hidden_dim" - if ( - recipe is not None - and torch.cuda.get_device_capability() == (10, 7) - and config.recv_capacity_per_rank == _TILE - ): - # Some SM 10.7 MXFP8 weight gradients need more than one receive tile; one into - # main_grad counts as added. Only a weight that gets a gradient runs such a kernel. - from ....common.CuTeDSL.ep_gemm import ( # pylint: disable=import-outside-toplevel - wgrad_gemm, - ) - - for fc in (fc1, fc2): - if not (torch.is_grad_enabled() and fc.weight.requires_grad): - continue - cfg = wgrad_gemm.WgradConfig( - _TILE, fc.out_features, fc.in_features, config.num_local_experts, 1, - accumulate=fc._accumulate_into_main_grad, - scaling_mode=wgrad_gemm.MXFP8_1D_SCALING, - token_alignment=config.alignment, - routed_tokens=config.max_tokens_per_rank * config.top_k, - ) # fmt: skip - try: - wgrad_gemm.build_kernel(cfg) - except ValueError as err: - return str(err) return None diff --git a/transformer_engine/pytorch/ops/fuser.py b/transformer_engine/pytorch/ops/fuser.py index f6a2f93e4ea..6d13ba43942 100644 --- a/transformer_engine/pytorch/ops/fuser.py +++ b/transformer_engine/pytorch/ops/fuser.py @@ -8,7 +8,6 @@ from collections.abc import Callable, Iterable, Sequence import copy import itertools -import os from typing import Any, Optional, TypeAlias import torch @@ -52,7 +51,7 @@ def _is_graph_capturing() -> bool: "Callable[tuple[list[FusibleOperation], ...], list[FusibleOperation]]" ) _FusedOpList: TypeAlias = list[tuple[FusibleOperation, list[int]]] -_FusionParams: TypeAlias = tuple[str, int, tuple] +_FusionParams: TypeAlias = tuple[str, int] class _OperationFuserAutogradFunction(torch.autograd.Function): @@ -702,19 +701,9 @@ def maybe_fuse_ops( # backward boundary in the key, but pay construction cost only once for # each configuration. Full recompute therefore builds at most one # no-grad plan and one grad-enabled plan for a stable recipe. - # Runtime settings that fusions may fall back on are part of the key. - runtime_policy = ( - torch.are_deterministic_algorithms_enabled(), - os.getenv("NVTE_ALLOW_NONDETERMINISTIC_ALGO", "1"), - torch.get_autocast_dtype("cuda") if torch.is_autocast_enabled() else None, - tuple( - op.need_backward_dw() for op in self._basic_ops if hasattr(op, "need_backward_dw") - ), - ) fusion_params: _FusionParams = ( str(recipe) if recipe is not None else "", first_op_requiring_backward, - runtime_policy, ) cached_ops = self._fused_ops_cache.get(fusion_params) if cached_ops is not None: From 6da7b77e67188a598e91885411458c91a90c2ce2 Mon Sep 17 00:00:00 2001 From: Phuong Nguyen Date: Mon, 30 Nov 2026 20:19:28 -0800 Subject: [PATCH 11/67] Move the MoE overlap tests into TestMoeEpSequential and drop the glu_interleave_size None cases Signed-off-by: Phuong Nguyen --- tests/pytorch/distributed/run_ep.py | 3404 ++++++++++++++------------- 1 file changed, 1705 insertions(+), 1699 deletions(-) diff --git a/tests/pytorch/distributed/run_ep.py b/tests/pytorch/distributed/run_ep.py index c4e545a890b..d18543e30fa 100644 --- a/tests/pytorch/distributed/run_ep.py +++ b/tests/pytorch/distributed/run_ep.py @@ -173,12 +173,6 @@ def _build_ep_group(): return dist.new_group(ranks=ranks, backend="nccl") -def _gate_up_rows(t): - """Per-expert FC1 rows [experts, 2 * ffn, ...] of the 32-wide interleaved GLU layout in the - gate-then-up layout (glu_interleave_size=None).""" - return t.reshape(t.shape[0], -1, 2, 32, *t.shape[2:]).transpose(1, 2).reshape(t.shape) - - def _assert_close_in_norm(actual, expected, rtol): """``actual`` is within ``rtol`` of ``expected`` in norm, per expert of a grouped weight.""" rows = expected.shape[0] if expected.dim() == 3 else 1 @@ -426,6 +420,23 @@ def _require_mxfp8_shapes(self): if OVERLAP and OVERLAP_ALIGNMENT < _mxfp8_overlap_min_alignment(): self.skipTest("FusedMoE runs MXFP8 with alignment 128 or 256 (256 on SM 10.7)") + def _capture(self, step): + """Warm up ``step`` on a side stream then capture it into a CUDA graph. Returns + the graph; the caller replays it. With NVTE_EP_FUSED_PREPARE_DISPATCH set, dispatch + under capture takes the fused count-mode path that derives the counts from the + dispatch scan.""" + s = torch.cuda.Stream() + s.wait_stream(torch.cuda.current_stream()) + with torch.cuda.stream(s): + for _ in range(3): + step() + torch.cuda.current_stream().wait_stream(s) + torch.cuda.synchronize() + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph): + step() + return graph + class TestEP(_EpTestCase): """NCCL EP tests inherited from nvidia_origin/main.""" @@ -468,52 +479,6 @@ def _weighted(recv_tokens, recv_w): mask = (recv_w != 0).to(torch.float32).unsqueeze(-1) return (recv_tokens.float() * recv_w.unsqueeze(-1).float() * mask).to(recv_tokens.dtype) - def _moe_ops( - self, - config, - buffer, - glu_interleave_size=32, - accumulate_into_main_grad=False, - *, - ffn=HIDDEN_DIM, - activation=None, - fc_kwargs=({}, {}), - **linear_kwargs, - ): - """MoeDispatch, GroupedLinear, ``activation`` (default ScaledSwiGLU), GroupedLinear and - MoeCombine over ``buffer``, with the routing channels connected and fixed weights (BF16 - unless ``linear_kwargs`` change the GroupedLinear settings; ``fc_kwargs`` adds settings - of the first and of the second GroupedLinear).""" - device = self.cfg.device - gen = torch.Generator(device=device).manual_seed(5) - linear_kwargs = { - "bias": False, - "dtype": torch.bfloat16, - "single_grouped_weight": True, - "split_alignment": OVERLAP_ALIGNMENT, - "accumulate_into_main_grad": accumulate_into_main_grad, - **linear_kwargs, - } - dispatch = te_ops.MoeDispatch(config, buffer) - fc1 = te_ops.GroupedLinear( - NUM_LOCAL_EXPERTS, HIDDEN_DIM, 2 * ffn, device=device, **linear_kwargs, **fc_kwargs[0] - ) - fc2 = te_ops.GroupedLinear( - NUM_LOCAL_EXPERTS, ffn, HIDDEN_DIM, device=device, **linear_kwargs, **fc_kwargs[1] - ) - act = activation or te_ops.ScaledSwiGLU(glu_interleave_size=glu_interleave_size) - combine = te_ops.MoeCombine(config, buffer) - with torch.no_grad(): - for fc in (fc1, fc2): - for w in fc.parameters(): - w.copy_((torch.rand(w.shape, device=device, generator=gen) - 0.5) * 0.1) - dispatch.set_extra_output_channel(0, "tokens_per_expert", output_to_caller=False) - dispatch.set_extra_output_channel(1, "routing_weights", output_to_caller=False) - fc1.set_extra_input_channel(0, "tokens_per_expert") - act.set_extra_input_channel(0, "routing_weights") - fc2.set_extra_input_channel(0, "tokens_per_expert") - return dispatch, fc1, act, fc2, combine - def _moe_step(self, buffer, topk_idx, tokens, w): recv_t, recv_w_out, _tc = ep_dispatch(buffer, tokens, topk_idx, w) expert_out = self._weighted(recv_t, recv_w_out) @@ -630,1841 +595,1882 @@ def test_primitive_dispatch_combine_identity(self): # Overlapped MoE + @_zero_copy_test_include + def test_dispatch_autograd(self): + """0.5*||recv_tokens||^2 ; grad_tokens equals TOP_K * tokens. Covers the + EpBuffer-owned recv tokens (symm-mem under zero-copy) and, in normal + mode, a caller-supplied recv_tokens buffer.""" + if ZERO_COPY: + cases = [("buffer_owned", None)] + else: + rt_buf, _rw_buf, _ = self._make_raw_recv() + cases = [ + ("default_alloc", None), + ("caller_recv", rt_buf), + ] + for label, recv_tokens in cases: + with self.subTest(case=label): + buf = self._make_buffer() + topk_idx, tokens, w = _make_identity_inputs(self.cfg.rank, self.cfg.ep_size) + tokens_p = tokens.detach().clone().requires_grad_(True) + rt, rw, _tc = ep_dispatch(buf, tokens_p, topk_idx, w, recv_tokens=recv_tokens) + if recv_tokens is not None: # caller-supplied recv_tokens must be used in place + self.assertEqual(rt.data_ptr(), recv_tokens.data_ptr()) + rt = self._stage_grad_symm(rt) + rw = self._stage_grad_symm(rw) + (0.5 * (rt.float() ** 2).sum() + 0.0 * rw.float().sum()).backward() + torch.cuda.synchronize() + torch.testing.assert_close( + tokens_p.grad.float(), tokens.float() * float(TOP_K), atol=5e-2, rtol=5e-2 + ) + + # MXFP8 dispatch + + def _mxfp8_quantizer(self): + from transformer_engine.pytorch.tensor.mxfp8_tensor import MXFP8Quantizer + + return MXFP8Quantizer(fp8_dtype=tex.DType.kFloat8E4M3, rowwise=True, columnwise=False) + + def _assert_mxfp8_matches_bf16(self, recv_mx, tokens, topk_idx, w, tc): + """Dequantized MXFP8 recv matches a bf16 dispatch of the same tokens, per expert. Row + order within an expert's block can differ between the two dispatch kernels, so compare + by sorted row sums (order-tolerant) instead of position.""" + ref_tokens = self._mxfp8_quantizer().quantize(tokens).dequantize() + ref_recv, _rw, _tc = ep_dispatch(self._make_buffer(alignment=256), ref_tokens, topk_idx, w) + torch.cuda.synchronize() + got = _degroup_mxfp8(recv_mx).float() + cum = [0] + tc.cumsum(0).tolist() + for lo, hi in zip(cum[:-1], cum[1:]): + torch.testing.assert_close( + got[lo:hi].sum(dim=1).sort().values, + ref_recv[lo:hi].float().sum(dim=1).sort().values, + atol=1e-1, + rtol=1e-1, + ) + @_eager_test_include - @_overflow_test_include + @_zero_copy_test_include @_mxfp8_align_test - @_overlap_test - def test_moe_overlap_op(self): - """The fused MoE op matches the same ops run unfused: output and every - gradient, also when tokens overflow the capacity and are dropped. Skipped where the - overlapped GEMMs cannot run.""" - self._check_moe_overlap_op(None) + def test_dispatch_mxfp8(self): + """MXFP8 dispatch quantizes bf16 tokens internally; recv (a per-expert GroupedTensor) + dequantized matches a bf16 dispatch of the same tokens. Under zero-copy the recv data and + scales are symm-mem backed.""" + self._require_mxfp8_shapes() + topk_idx, tokens, w = _make_identity_inputs(self.cfg.rank, self.cfg.ep_size) + buf = self._make_buffer(dispatch_fwd_quant_recipe=MXFP8BlockScaling(), alignment=256) + recv_mx, _rw, tc = ep_dispatch(buf, tokens, topk_idx, w) + if ZERO_COPY: + self.assertTrue(is_symm_backed(recv_mx.rowwise_data)) + self.assertTrue(is_symm_backed(recv_mx.scale_inv)) + self._assert_mxfp8_matches_bf16(recv_mx, tokens, topk_idx, w, tc) @_eager_test_include - @_overflow_test_include @_mxfp8_align_test - @_overlap_test - def test_moe_overlap_op_mxfp8(self): - """Under MXFP8 with MXFP8 EP transport the fused op matches the unfused ops, with weight - scales that differ across blocks in both directions. The fused op dispatches x and dY in - place from the EP dispatch window. An unset config transport runs MXFP8.""" + def test_dispatch_mxfp8_autograd(self): + """MXFP8 dispatch fwd+bwd. Seeding the recv grad with ones scatters TOP_K back to each token + under identity routing, so grad_tokens equals TOP_K through the dispatch backward and the + input quantizer STE. Exercises the fused eager MXFP8 dispatch backward.""" self._require_mxfp8_shapes() - recipe = MXFP8BlockScaling() - with mock.patch.object( - tex, "ep_dispatch_gemm_fwd", wraps=tex.ep_dispatch_gemm_fwd - ) as fwd, mock.patch.object( - tex, "ep_combine_gemm_bwd", wraps=tex.ep_combine_gemm_bwd - ) as bwd: - self._check_moe_overlap_op(recipe, recipe) - for call in fwd.call_args_list + bwd.call_args_list: - self.assertEqual(call.kwargs["symm_input"], tex.ep_zero_copy_supported()) - # MXFP8 FusedMoE quantizes the EP transport itself, so an unset config transport fuses. - config = self._overlap_config() - model = te_ops.Sequential(*self._moe_ops(config, self._make_buffer_from_config(config))) topk_idx, tokens, w = _make_identity_inputs(self.cfg.rank, self.cfg.ep_size) - with te.autocast(recipe=recipe): - model(tokens, topk_idx, w, topk_idx) - self.assertTrue(self._moe_overlap_selected(model)) + tokens_p = tokens.detach().clone().requires_grad_(True) + buf = self._make_buffer(dispatch_fwd_quant_recipe=MXFP8BlockScaling(), alignment=256) + recv_mx, _rw, _tc = ep_dispatch(buf, tokens_p, topk_idx, w) + g_recv = torch.ones(recv_mx.shape, dtype=torch.bfloat16, device=self.cfg.device) + torch.autograd.backward(recv_mx, grad_tensors=g_recv) + torch.cuda.synchronize() + torch.testing.assert_close( + tokens_p.grad.float(), + torch.full_like(tokens_p, float(TOP_K)).float(), + atol=5e-2, + rtol=5e-2, + ) - @_eager_test_include - @_overflow_test_include + @_zero_copy_test_include @_mxfp8_align_test - @_overlap_test - def test_moe_overlap_op_variants(self): - """The fused op matches the unfused ops, in BF16 and, where the overlap tests run MXFP8, in - MXFP8, also: without input and routing-weight gradients (no dispatch backward), with - MXFP8 weight parameters, with accumulate_into_main_grad and both GLU layouts, with an FFN - size other than the hidden size, and with FP32 weight parameters cast by - ``Module.to(torch.bfloat16)``.""" - # (recipe, _check_moe_overlap_op settings) - cases = [ - (None, {"input_grad": False}), - # ffn != hidden, so a transposed weight layout cannot pass. - (None, {"ffn": HIDDEN_DIM // 2}), - (None, {"main_grad": True, "glu_interleave_size": None}), - (None, {"params_to_bf16": True}), - (None, {"params_to_bf16": True, "glu_interleave_size": None}), - (None, {"params_to_bf16": True, "main_grad": True}), - (None, {"frozen": (1,)}), - (None, {"frozen": (3,)}), - (None, {"frozen": (1, 3), "main_grad": True}), - ] - if _mxfp8_overlap(): - recipe = MXFP8BlockScaling() - cases += [ - (recipe, {"input_grad": False}), - (recipe, {"params_to_bf16": True}), - (recipe, {"quantized_weights": True}), - (recipe, {"frozen": (1,)}), - (recipe, {"frozen": (3,)}), - (recipe, {"frozen": (1, 3), "glu_interleave_size": None}), - ] - cases += [ - (recipe, {"quantized_weights": q, "glu_interleave_size": glu, "main_grad": True}) - for q, glu in itertools.product((False, True), (32, None)) - ] - for recipe, settings in cases: - with self.subTest(recipe=recipe, **settings): - self._check_moe_overlap_op(recipe, recipe, **settings) + def test_caller_provides_dispatch_recv_mxfp8(self): + """One caller-supplied buffer holds the recv data followed by the e8m0 scales; ep_dispatch + slices it and the returned GroupedTensor views the data and scale regions of that buffer.""" + self._require_mxfp8_shapes() + from transformer_engine.pytorch.constants import MXFP8_BLOCK_SCALING_SIZE - def _assert_glu_none_matches(self, got, want, got_grads, want_grads): - """The outputs and FC1, FC2 weight gradients of the fused op with glu_interleave_size=None - match those of the 32-wide layer, the FC1 rows mapped between the layouts.""" - for g, w in zip(got[:2], want[:2]): - self.assertTrue(torch.equal(g, w)) - if OVERLAP_ALIGNMENT >= 256 and HIDDEN_DIM <= 512: - self.assertTrue(torch.equal(got[2], want[2])) + rc = self.cfg.recv_capacity_per_rank + cols = HIDDEN_DIM // MXFP8_BLOCK_SCALING_SIZE + nbytes = rc * (HIDDEN_DIM + cols) # fp8 data + e8m0 scales, one byte per element + if ZERO_COPY: + recv_buf = symm_mem_alloc((nbytes,), torch.uint8, self.ep_group) else: - # The routing-weight gradient adds more than two column tiles, or tail tiles, in - # arrival order, which changes the FP32 sums by up to about 1e-6 of the largest one. - torch.testing.assert_close( - got[2], want[2], rtol=1.3e-6, atol=1e-6 * float(want[2].abs().amax()) - ) - fc1_shape = (NUM_LOCAL_EXPERTS, -1, HIDDEN_DIM) - # The rows of an expert may arrive in another order, which changes the FP32 wgrad sums by - # up to about 1e-6 of the expert's largest one, then by a BF16 rounding. - for g, w in ( - (got_grads[0].reshape(fc1_shape), _gate_up_rows(want_grads[0].reshape(fc1_shape))), - (got_grads[1], want_grads[1]), - ): - for ge, we in zip(g.reshape(NUM_LOCAL_EXPERTS, -1), w.reshape(NUM_LOCAL_EXPERTS, -1)): - torch.testing.assert_close(ge, we, rtol=1e-2, atol=1e-6 * float(we.abs().amax())) + recv_buf = torch.empty(nbytes, dtype=torch.uint8, device=self.cfg.device) + buf = self._make_buffer(dispatch_fwd_quant_recipe=MXFP8BlockScaling(), alignment=256) + topk_idx, tokens, w = _make_identity_inputs(self.cfg.rank, self.cfg.ep_size) + recv_mx, _rw, tc = ep_dispatch(buf, tokens, topk_idx, w, recv_tokens=recv_buf) + # the returned GroupedTensor views the caller buffer's data then scale regions + self.assertEqual(recv_mx.rowwise_data.data_ptr(), recv_buf.data_ptr()) + self.assertEqual(recv_mx.scale_inv.data_ptr(), recv_buf.data_ptr() + rc * HIDDEN_DIM) + self._assert_mxfp8_matches_bf16(recv_mx, tokens, topk_idx, w, tc) - def _check_moe_overlap_op( - self, recipe, transport=None, quantized_weights=False, glu_interleave_size=32, - main_grad=False, input_grad=True, params_to_bf16=False, ffn=HIDDEN_DIM, frozen=(), - ): # fmt: skip - from transformer_engine.pytorch.ops.fused import moe_overlap + @_zero_copy_test_include + def test_caller_provides_dispatch_recv_tokens(self): + """Caller-supplied recv_tokens (symm-mem-backed in zero-copy): ep_dispatch + writes into it and returns a view of the caller's buffer.""" + if ZERO_COPY: + rc = self.cfg.recv_capacity_per_rank + rt_buf = symm_mem_alloc((rc, HIDDEN_DIM), torch.bfloat16, self.ep_group) + else: + rt_buf, _rw_buf, _ = self._make_raw_recv() + buf = self._make_buffer() + topk_idx, tokens, w = _make_identity_inputs(self.cfg.rank, self.cfg.ep_size) + tokens_p = tokens.detach().clone().requires_grad_(True) + rt, rw, _ = ep_dispatch(buf, tokens_p, topk_idx, w, recv_tokens=rt_buf) + self.assertEqual(rt.data_ptr(), rt_buf.data_ptr()) + rt = self._stage_grad_symm(rt) + rw = self._stage_grad_symm(rw) + (0.5 * (rt.float() ** 2).sum() + 0.0 * rw.float().sum()).backward() + torch.cuda.synchronize() + torch.testing.assert_close( + tokens_p.grad.float(), tokens.float() * float(TOP_K), atol=5e-2, rtol=5e-2 + ) - device = self.cfg.device - config = self._overlap_config(transport) - # Where FusedMoE cannot run, the overlap raises, so there is nothing to compare. - if not moe_overlap.FusedMoE.is_supported() or ( - recipe is not None - and not (moe_overlap.GroupedMLP_CuTeGEMMGLU.is_supported() and transport is not None) - ): - self.skipTest("FusedMoE is not supported here") - # SM 10.7 runs the MXFP8 weight gradients into main_grad only above 256 receive rows. - if ( - main_grad - and recipe is not None - and torch.cuda.get_device_capability() == (10, 7) - and config.recv_capacity_per_rank == 256 - ): - self.skipTest( - "SM 10.7 MXFP8 main_grad weight gradients need more than 256 receive rows" - ) - with te.quantized_model_init(enabled=quantized_weights, recipe=recipe): - buffer = self._make_buffer_from_config(config) - ops = self._moe_ops( - config, - buffer, - glu_interleave_size, - main_grad, - ffn=ffn, - dtype=torch.float32 if params_to_bf16 else torch.bfloat16, - ) - gen = torch.Generator(device=device).manual_seed(6) - if recipe is not None: - # Power-of-two factors per row and column give every scale block its own exponent. - with torch.no_grad(): - for fc in (ops[1], ops[3]): - for w in fc.parameters(): - rows = torch.randint( - -3, 4, (*w.shape[:-1], 1), device=device, generator=gen - ) - cols = torch.randint(-3, 4, w.shape[-1:], device=device, generator=gen) - values = torch.rand(w.shape, device=device, generator=gen) - 0.5 - w.copy_(values * 0.1 * torch.exp2((rows + cols).float())) - if glu_interleave_size is None: - # The layer of glu_interleave_size=32 with its FC1 rows mapped to gate then up. - with torch.no_grad(): - ops[1].weight.copy_(_gate_up_rows(ops[1].weight * 1)) - if params_to_bf16: - for op in ops: - op.to(torch.bfloat16) - # The weights of the GroupedLinear ops at these positions (1: FC1, 3: FC2) are frozen. - for idx in frozen: - ops[idx].weight.requires_grad_(False) + @_zero_copy_test_include + def test_caller_provides_grad_expert_out(self): + """Caller-supplied grad_out (symm-mem-backed in zero-copy): ep_combine's + backward scatters the expert-out grad into it.""" + rc = self.cfg.recv_capacity_per_rank + if ZERO_COPY: + gbuf = symm_mem_alloc((rc, HIDDEN_DIM), torch.bfloat16, self.ep_group) + else: + gbuf = torch.empty(rc, HIDDEN_DIM, dtype=torch.bfloat16, device=self.cfg.device) + gbuf.zero_() + buf = self._make_buffer() topk_idx, tokens, w = _make_identity_inputs(self.cfg.rank, self.cfg.ep_size) - grad_out = torch.randn(tokens.shape, device=device, generator=gen).to(torch.bfloat16) - - def run(fused): - if not fused and params_to_bf16: - # The BF16 grouped MLP fusion reads the weight data as stored, so this reference - # runs the GroupedLinear ops, which cast it, and not FusedMoE. - ctx = contextlib.ExitStack() - ctx.enter_context( - mock.patch.object( - moe_overlap.GroupedMLP_CuTeGEMMGLUBf16, "is_supported", return_value=False - ) - ) - ctx.enter_context(self._moe_fusion(False)) - elif not fused: - ctx = self._moe_fusion(False) - elif input_grad: - ctx = contextlib.nullcontext() - else: - ctx = mock.patch.object( - moe_overlap.tex, "ep_dispatch_gemm_bwd", side_effect=AssertionError("called") - ) - if fused: - # The fused op uses its own counts and recv total, not the reference's. - buffer.tokens_per_expert_i32.fill_(-1) - buffer.total_recv_tokens_i32.fill_(-1) - buffer.total_recv_tokens.fill_(-1) - # Paged stashing pages the tensors that carry a token count. - stashable = [] - num_tokens = [] - - def pack(tensor): - if hasattr(tensor, "grouped_tensor_num_tokens"): - stashable.append((tensor.dtype, tensor.shape, tensor.nbytes)) - n = tensor.grouped_tensor_num_tokens - num_tokens.append(n.clone() if torch.is_tensor(n) else n) - return tensor + tokens_p = tokens.detach().clone().requires_grad_(True) + recv_t, recv_w, _ = ep_dispatch(buf, tokens_p, topk_idx, w) + recv_t = self._stage_grad_symm(recv_t) + recv_w = self._stage_grad_symm(recv_w) + expert_out = self._expert_out(self._weighted(recv_t, recv_w)) + out = ep_combine(buf, expert_out, grad_out=gbuf) + (0.5 * (out.float() ** 2).sum()).backward() + torch.cuda.synchronize() + torch.testing.assert_close(out.float(), tokens.float(), atol=5e-2, rtol=5e-2) + torch.testing.assert_close(tokens_p.grad.float(), tokens.float(), atol=5e-2, rtol=5e-2) + # the caller-owned buffer was used as the combine-bwd scatter target + self.assertGreater(gbuf.abs().sum().item(), 0.0) - with ctx, te.autocast( - enabled=recipe is not None, recipe=recipe - ), torch.autograd.graph.saved_tensors_hooks(pack, lambda tensor: tensor): - model = te_ops.Sequential(*ops) - x = tokens.clone().requires_grad_(input_grad) - topk_w = w.clone().requires_grad_(input_grad) - for p in model.parameters(): - p.grad = None - if main_grad: - p.main_grad = torch.full(p.shape, 0.5, dtype=torch.float32, device=device) - p.grad_added_to_main_grad = False - y = model(x, topk_idx, topk_w, topk_idx) - y.backward(grad_out) - torch.cuda.synchronize() - fused_ops = self._moe_overlap_selected(model) - trained = [p for p in model.parameters() if p.requires_grad] - if main_grad: - self.assertTrue(all(p.grad_added_to_main_grad for p in trained)) - grads = [(p.main_grad if main_grad else p.grad).clone() for p in trained] - counts = [int(n) for n in num_tokens] - return y.detach(), x.grad, topk_w.grad, grads, bool(fused_ops), stashable, counts + @_zero_copy_test_include + @_mxfp8_align_test + def test_combine_bwd_mxfp8_caller_grad_out(self): + """MXFP8 combine backward into a single caller buffer sliced into data + e8m0 scales: the + returned per-expert GroupedTensor views those regions and, dequantized, matches a bf16 + combine backward reference on the same routing. Under zero-copy the caller buffer and combine + input are symm-mem backed.""" + self._require_mxfp8_shapes() + from transformer_engine.pytorch.constants import MXFP8_BLOCK_SCALING_SIZE - ref = run(False) - out = run(True) - self.assertFalse(ref[4]) - self.assertTrue(out[4], "fusion selection") - # The launcher requires this line from every rank of an overlap pass. - print(f"OVERLAP_EXECUTED rank={self.cfg.rank}", flush=True) - reason = _moe_overlap_unsupported_reason( - config, ffn, params_dtype=torch.bfloat16, - glu_interleave_size=glu_interleave_size, single_grouped_weight=True, recipe=recipe, - primary_weights_in_fp8=quantized_weights, - ) # fmt: skip - self.assertIsNone(reason, "the fuser selects FusedMoE but the support check rejects it") - # Row tensors saved: recv tokens (and their scales), the FC1 output and the routing - # weights, plus the SwiGLU output in BF16. A frozen weight leaves out the input of its - # weight gradient: the recv tokens and scales for FC1, the SwiGLU output (BF16) for FC2. - fc1_inputs, fc2_inputs = (2, 0) if recipe is not None else (1, 1) - stashed = 4 - (fc1_inputs if 1 in frozen else 0) - (fc2_inputs if 3 in frozen else 0) - self.assertEqual(len(out[5]), stashed, "the fused op saves the stashable tensors") - # Their token count is the number of received rows kept. - kept = int(buffer.tokens_per_expert_i32.sum()) - self.assertEqual(out[6], [kept] * stashed, "stashed token counts") - # The fused op publishes that kept total to the buffer counter paged stashing reads. - self.assertEqual(int(buffer.total_recv_tokens.item()), kept, "published recv total") - if recipe is not None: - # The FC2 dgrad recomputes the SwiGLU output, so no [rows, ffn] tensor is saved: - # the recv tokens and scales, the FC1 output and the recv routing weights. - rows = next(shape[0] for dtype, shape, _ in out[5] if dtype == torch.float32) - saved = sum(nbytes for _, _, nbytes in out[5]) - ffn = ops[3].in_features - recv_bytes = 0 if 1 in frozen else HIDDEN_DIM + HIDDEN_DIM // 32 - self.assertEqual(saved, rows * (recv_bytes + 2 * ffn * 2 + 4), "saved bytes") - # Where the unfused ops compute the SwiGLU output in their own kernel, single elements may - # round to another value, so those results are compared in norm. The unfused MXFP8 ops also - # round the FC2 dgrad and the SwiGLU backward output to BF16 before quantizing them, so - # outputs and weight gradients may differ by up to the E4M3 epsilon. - norm_rtol = 2e-2 if recipe is None else 1 / 32 - unfused_reference = glu_interleave_size is None or ( - UNFUSED_BF16_MLP_REFERENCE if recipe is None else UNFUSED_MLP_REFERENCE + rc = self.cfg.recv_capacity_per_rank + cols = HIDDEN_DIM // MXFP8_BLOCK_SCALING_SIZE + topk_idx, tokens, w = _make_identity_inputs(self.cfg.rank, self.cfg.ep_size) + eo_vals = ( + torch.linspace(-0.5, 0.5, rc * HIDDEN_DIM, device=self.cfg.device) + .reshape(rc, HIDDEN_DIM) + .to(torch.bfloat16) + ) + # MXFP8 combine backward writes into one caller buffer (data then e8m0 scales) + buf_mx = self._make_buffer(combine_bwd_quant_recipe=MXFP8BlockScaling(), alignment=256) + _recv, _rw, tc = ep_dispatch(buf_mx, tokens, topk_idx, w) # seeds the routing + nbytes = rc * (HIDDEN_DIM + cols) + if ZERO_COPY: + grad_buf = symm_mem_alloc((nbytes,), torch.uint8, self.ep_group) + else: + grad_buf = torch.empty(nbytes, dtype=torch.uint8, device=self.cfg.device) + src_mx = eo_vals.detach().clone().requires_grad_(True) + out_mx = ep_combine(buf_mx, self._expert_out(src_mx), grad_out=grad_buf) + (0.5 * (out_mx.float() ** 2).sum()).backward() + g_mx = src_mx.grad # per-expert GroupedTensor viewing grad_buf + self.assertEqual(g_mx.rowwise_data.data_ptr(), grad_buf.data_ptr()) + self.assertEqual(g_mx.scale_inv.data_ptr(), grad_buf.data_ptr() + rc * HIDDEN_DIM) + # bf16 reference combine backward on the same routing + buf_bf = self._make_buffer(alignment=256) + ep_dispatch(buf_bf, tokens, topk_idx, w) + src_bf = eo_vals.detach().clone().requires_grad_(True) + out_bf = ep_combine(buf_bf, self._expert_out(src_bf)) + (0.5 * (out_bf.float() ** 2).sum()).backward() + torch.cuda.synchronize() + n = int(tc.sum()) + torch.testing.assert_close( + _degroup_mxfp8(g_mx).float(), src_bf.grad.float()[:n], atol=5e-2, rtol=5e-2 ) - outputs_in_norm = unfused_reference or params_to_bf16 - outputs_rtol = 1 / 16 if recipe is not None and unfused_reference else norm_rtol - if not input_grad: - self.assertTrue(all(g is None for g in out[1:3] + ref[1:3])) - for got, want in zip(out[: 3 if input_grad else 1], ref[:3]): - if outputs_in_norm: - _assert_close_in_norm(got, want, rtol=outputs_rtol) - else: - torch.testing.assert_close(got, want, rtol=2e-2, atol=2e-2) - for g, g_ref in zip(out[3], ref[3]): - if ( - recipe is None - and glu_interleave_size is not None - and not (UNFUSED_BF16_MLP_REFERENCE or params_to_bf16) - ): - torch.testing.assert_close(g, g_ref, rtol=2e-2, atol=2e-2) - else: - _assert_close_in_norm(g, g_ref, rtol=outputs_rtol) @_eager_test_include + @_zero_copy_test_include @_mxfp8_align_test - @_overlap_test - def test_moe_overlap_cpu_offload(self): - """Under CPU offload the tensors the fused op saves come back bitwise, and its output and - gradients match those without offload.""" - from transformer_engine.pytorch import cpu_offload - - self._require_moe_overlap() - tokens, topk_idx, w, grad_out = self._moe_calls(1)[0] - for recipe in [None] + ([MXFP8BlockScaling()] if _mxfp8_overlap() else []): - config = self._overlap_config(recipe) - ops = self._moe_ops(config, self._make_buffer_from_config(config)) - results = [] - for offload in (False, True): - saved = [] - for p in ops[1].parameters(): - p.grad = None - for p in ops[3].parameters(): - p.grad = None - with te.autocast(enabled=recipe is not None, recipe=recipe): - model = te_ops.Sequential(*ops) - x = tokens.clone().requires_grad_(True) - topk_w = w.clone().requires_grad_(True) - if offload: - ctx, sync, controller = cpu_offload.get_cpu_offload_context( - enabled=True, model_layers=1, manual_synchronization=True - ) - sync_state = ctx.offload_synchronizer - push, pop = sync_state.push_tensor, sync_state.pop_tensor - - def push_tensor(tensor, push=push): - saved.append([tensor.detach().reshape(-1).view(torch.uint8).cpu()]) - return len(saved) - 1, push(tensor) - - def pop_tensor(packed, pop=pop): - tensor = pop(packed[1]) - saved[packed[0]].append(tensor.detach().reshape(-1).view(torch.uint8)) - return tensor - - with mock.patch.object( - sync_state, "push_tensor", push_tensor - ), mock.patch.object(sync_state, "pop_tensor", pop_tensor): - with ctx: - y = model(x, topk_idx, topk_w, topk_idx) - y = sync(y) - controller.start_offload_layer(0) - controller.release_activation_forward_gpu_memory(0) - controller.start_reload_layer(0) - else: - y = model(x, topk_idx, topk_w, topk_idx) - y.backward(grad_out) - torch.cuda.synchronize() - self.assertTrue(self._moe_overlap_selected(model)) - self.assertEqual(bool(saved), offload, "offloaded tensors") - for before, after in saved: - self.assertTrue(torch.equal(before, after.cpu()), "a saved tensor changed") - grads = [p.grad.clone() for p in model.parameters()] - results.append([y.detach(), x.grad, topk_w.grad, *grads]) - with self.subTest(recipe=recipe): - for i, (got, want) in enumerate(zip(*results)): - if recipe is not None and i >= 3: - _assert_close_in_norm(got, want, rtol=1 / 32) - else: - torch.testing.assert_close(got, want, rtol=2e-2, atol=2e-2) - - def _require_moe_overlap(self): - from transformer_engine.pytorch.ops.fused import moe_overlap - - if not moe_overlap.FusedMoE.is_supported(): - self.skipTest( - "FusedMoE needs SM 10.0, 10.3 or 10.7, NVTE_ENABLE_CUTEDSL_BACKEND=1," - " NVTE_MOE_OVERLAP and the BF16 cuDNN grouped GEMM kernels" - ) - - @staticmethod - def _moe_fusion(fused): - """Context in which the fuser may select FusedMoE, or keeps the MoE ops unfused.""" - from transformer_engine.pytorch.ops.fused import moe_overlap - - if fused: - return contextlib.nullcontext() - return mock.patch.object(moe_overlap, "_moe_overlap_available", return_value=False) - - @staticmethod - def _moe_overlap_selected(model): - """The FusedMoE ops of the plan ``model`` ran last.""" - from transformer_engine.pytorch.ops.fused import moe_overlap - - return [ - op - for group in model._module_groups - for op, _ in getattr(group, "_forward_ops", []) - if isinstance(op, moe_overlap.FusedMoE) - ] - - def _moe_calls(self, num_calls): - """(tokens, topk_idx, topk_weights, grad_output) of calls that each route differently.""" - gen = torch.Generator(device=self.cfg.device).manual_seed(8) + def test_combine_bwd_mxfp8(self): + """MXFP8 combine backward with an internally allocated grad target: the returned per-expert + GroupedTensor, dequantized, matches a bf16 combine backward reference on the same routing. + Under zero-copy the combine input is symm-mem backed. + """ + self._require_mxfp8_shapes() topk_idx, tokens, w = _make_identity_inputs(self.cfg.rank, self.cfg.ep_size) - return [ - ( - tokens.roll(i, 0), - (topk_idx + i) % self.cfg.num_experts, - w, - torch.randn(tokens.shape, device=self.cfg.device, generator=gen).to(torch.bfloat16), - ) - for i in range(num_calls) - ] - - @staticmethod - def _moe_call(model, tokens, topk_idx, w, grad, *, tokens_grad=True, weights_grad=True): - """Forward, then backward when ``grad`` is given: (output, tokens grad, topk_weights - grad). Parameter gradients accumulate on the parameters.""" - x = tokens.clone().requires_grad_(tokens_grad) - topk_w = w.clone().requires_grad_(weights_grad) - y = model(x, topk_idx, topk_w, topk_idx) - if grad is not None: - y.backward(grad) - return y.detach(), x.grad, topk_w.grad - - @staticmethod - def _param_grads(model): - return [None if p.grad is None else p.grad.clone() for p in model.parameters()] + buf_mx = self._make_buffer(combine_bwd_quant_recipe=MXFP8BlockScaling(), alignment=256) + _recv, _rw, tc = ep_dispatch(buf_mx, tokens, topk_idx, w) # seeds the routing + # Combine input rows match the recv total (per-step in eager, capacity otherwise). + rows = int(buf_mx.total_recv_tokens.item()) if EAGER else self.cfg.recv_capacity_per_rank + eo_vals = ( + torch.linspace(-0.5, 0.5, rows * HIDDEN_DIM, device=self.cfg.device) + .reshape(rows, HIDDEN_DIM) + .to(torch.bfloat16) + ) + src_mx = eo_vals.detach().clone().requires_grad_(True) + out_mx = ep_combine(buf_mx, self._expert_out(src_mx)) + (0.5 * (out_mx.float() ** 2).sum()).backward() + g_mx = src_mx.grad # per-expert GroupedTensor + # bf16 reference combine backward on the same routing + buf_bf = self._make_buffer(alignment=256) + ep_dispatch(buf_bf, tokens, topk_idx, w) + src_bf = eo_vals.detach().clone().requires_grad_(True) + out_bf = ep_combine(buf_bf, self._expert_out(src_bf)) + (0.5 * (out_bf.float() ** 2).sum()).backward() + torch.cuda.synchronize() + n = int(tc.sum()) + torch.testing.assert_close( + _degroup_mxfp8(g_mx).float(), src_bf.grad.float()[:n], atol=5e-2, rtol=5e-2 + ) - def _assert_moe_close( - self, got, ref, in_norm=UNFUSED_BF16_MLP_REFERENCE, outputs_in_norm=True, rtol=2e-2 - ): - """Fused and unfused MoE results, nested in lists, agree within ``rtol``; with in_norm the - grouped weight gradients in norm, and with outputs_in_norm as well the outputs and input - gradients.""" - if isinstance(ref, (list, tuple)): - self.assertEqual(len(got), len(ref)) - for g, r in zip(got, ref): - self._assert_moe_close(g, r, in_norm, outputs_in_norm, rtol) - elif ref is None: - self.assertIsNone(got) - elif in_norm and (outputs_in_norm or ref.dim() == 3): - _assert_close_in_norm(got, ref, rtol=rtol) - else: - torch.testing.assert_close(got, ref, rtol=rtol, atol=rtol) + @_zero_copy_test_include + def test_zero_copy_pool_auto_alloc(self): + """Zero-copy with recv/grad left None: ep_dispatch/ep_combine allocate their IO + tensors from the symm-mem pool (is_symm_backed). This is the primary mcore + path — mcore hands no caller buffers, TE pools them on the fly.""" + if not ZERO_COPY: + self.skipTest("zero-copy pool auto-alloc only") + buf = self._make_buffer() + topk_idx, tokens, w = _make_identity_inputs(self.cfg.rank, self.cfg.ep_size) + tokens_p = tokens.detach().clone().requires_grad_(True) + recv_t, recv_w, _ = ep_dispatch(buf, tokens_p, topk_idx, w) # recv_tokens=None -> pool + self.assertTrue(is_symm_backed(recv_t)) # dispatch recv came from the symm-mem pool + recv_t = self._stage_grad_symm(recv_t) + recv_w = self._stage_grad_symm(recv_w) + expert_out = self._expert_out(self._weighted(recv_t, recv_w)) + out = ep_combine(buf, expert_out) # grad_out=None -> bwd allocs the grad from the pool + (0.5 * (out.float() ** 2).sum()).backward() + torch.cuda.synchronize() + torch.testing.assert_close(out.float(), tokens.float(), atol=5e-2, rtol=5e-2) + torch.testing.assert_close(tokens_p.grad.float(), tokens.float(), atol=5e-2, rtol=5e-2) - @_mxfp8_align_test - @_overlap_test - def test_moe_overlap_wgrad(self): - """With accumulate_into_main_grad, the fused op writes the weight gradients of two calls - into an FP32 or BF16 main_grad, accumulated or overwritten, as the unfused ops do.""" - self._require_moe_overlap() - config = self._overlap_config() - calls = self._moe_calls(2) - ops = self._moe_ops( - config, self._make_buffer_from_config(config), accumulate_into_main_grad=True - ) - weights = (ops[1].weight, ops[3].weight) - for dtype, overwrite in itertools.product((torch.float32, torch.bfloat16), (False, True)): - results = [] - for fused in (False, True): - for p in weights: - p.grad = None - p.main_grad = torch.full(p.size(), 0.5, dtype=dtype, device=self.cfg.device) - p.overwrite_main_grad = overwrite - p.grad_added_to_main_grad = False - with self._moe_fusion(fused): - model = te_ops.Sequential(*ops) - outs = [self._moe_call(model, *call) for call in calls] - torch.cuda.synchronize() - self.assertEqual(bool(self._moe_overlap_selected(model)), fused) - for p in weights: - self.assertTrue(p.grad_added_to_main_grad) - results.append((outs, [p.main_grad.clone() for p in weights])) - with self.subTest(dtype=dtype, overwrite=overwrite): - self._assert_moe_close(results[1], results[0]) + # Multi-iter stability @_eager_test_include - @_mxfp8_align_test - @_overlap_test - def test_moe_overlap_rank_without_tokens(self): - """Every token picks the first expert of ranks 0 and 1, so the other ranks and the other - experts of ranks 0 and 1 receive no tokens. The fused op matches the unfused ops, and - the weight gradients of the experts without tokens are zero. The fused op with - glu_interleave_size=None and the FC1 rows mapped matches it.""" - self._require_moe_overlap() - if self.cfg.ep_size < 3: - self.skipTest("needs a rank that receives no tokens") - config = self._overlap_config() - ops = self._moe_ops(config, self._make_buffer_from_config(config)) - tokens, _, w, grad = self._moe_calls(1)[0] - topk_idx = torch.tensor([0, NUM_LOCAL_EXPERTS], device=self.cfg.device).repeat( - TOKENS_PER_RANK, 1 - ) - results = [] - for fused in (False, True): - for p in ops[1].parameters(): - p.grad = None - for p in ops[3].parameters(): - p.grad = None - with self._moe_fusion(fused): - model = te_ops.Sequential(*ops) - out = self._moe_call(model, tokens, topk_idx, w, grad) - torch.cuda.synchronize() - self.assertEqual(bool(self._moe_overlap_selected(model)), fused) - results.append((out, self._param_grads(model))) - self._assert_moe_close(results[1], results[0]) - has_tokens = self.cfg.rank < 2 - for g in results[1][1]: - per_expert = g.view(NUM_LOCAL_EXPERTS, -1) - self.assertEqual(int(per_expert[int(has_tokens) :].count_nonzero()), 0) - if has_tokens: - self.assertGreater(int(per_expert[0].count_nonzero()), 0) + def test_dispatch_autograd_multiple_iterations(self): + """5 fwd+bwd iters on the same EpBuffer must be bit-stable.""" + buf = self._make_buffer() + topk_idx, tokens, w = _make_identity_inputs(self.cfg.rank, self.cfg.ep_size) - ops_none = self._moe_ops(config, self._make_buffer_from_config(config), None) - shape = (NUM_LOCAL_EXPERTS, ops[1].out_features, ops[1].in_features) - with torch.no_grad(): - ops_none[1].weight.rowwise_data.view(shape).copy_( - _gate_up_rows(ops[1].weight.rowwise_data.view(shape)) - ) - model = te_ops.Sequential(*ops_none) - out = self._moe_call(model, tokens, topk_idx, w, grad) + def one_step(): + tokens_p = tokens.detach().clone().requires_grad_(True) + out = self._moe_step(buf, topk_idx, tokens_p, w) + loss = 0.5 * (out.float() ** 2).sum() + loss.backward() + return out.detach().clone(), tokens_p.grad.detach().clone() + + out_ref, grad_ref = one_step() torch.cuda.synchronize() - self.assertTrue(self._moe_overlap_selected(model)) - self._assert_glu_none_matches(out, results[1][0], self._param_grads(model), results[1][1]) + for _ in range(4): + out_i, grad_i = one_step() + torch.cuda.synchronize() + torch.testing.assert_close(out_i, out_ref, atol=0, rtol=0) + torch.testing.assert_close(grad_i, grad_ref, atol=0, rtol=0) - @_mxfp8_align_test - @_overlap_test - def test_moe_overlap_cuda_graph(self): - """The fused forward and backward, captured in a CUDA graph after warmup and replayed with - new routing, tokens, topk_weights and output gradient, match the unfused ops; in BF16 and, - where the overlap tests run MXFP8, under MXFP8 transport (its shared dispatch window, - requantization and weight gradients captured and replayed).""" - self._require_moe_overlap() - for recipe in [None] + ([MXFP8BlockScaling()] if _mxfp8_overlap() else []): - with self.subTest(recipe=recipe): - self._run_moe_overlap_cuda_graph(recipe) + # CUDA graph - def _run_moe_overlap_cuda_graph(self, recipe): - """Capture and replay the fused MoE under ``recipe`` (None for BF16) and match the unfused - ops run under the same autocast.""" - if recipe is not None: - self._require_mxfp8_shapes() - device = self.cfg.device - config = self._overlap_config(recipe) - ops = self._moe_ops(config, self._make_buffer_from_config(config)) - ref_ops = self._moe_ops(config, self._make_buffer_from_config(config)) - if recipe is not None: - # Power-of-two row and column factors give every scale block its own exponent. Both - # models share the weights. - gen = torch.Generator(device=device).manual_seed(6) - with torch.no_grad(): - for fc, ref_fc in ((ops[1], ref_ops[1]), (ops[3], ref_ops[3])): - for w_fused, w_ref in zip(fc.parameters(), ref_fc.parameters()): - shape = w_fused.shape - rows = torch.randint(-3, 4, (*shape[:-1], 1), device=device, generator=gen) - cols = torch.randint(-3, 4, shape[-1:], device=device, generator=gen) - values = torch.rand(shape, device=device, generator=gen) - 0.5 - w_fused.copy_(values * 0.1 * torch.exp2((rows + cols).float())) - w_ref.copy_(w_fused) - gen = torch.Generator(device=device).manual_seed(9) - random_idx, random_tokens, random_w = _make_moe_inputs(self.cfg.rank, self.cfg.ep_size) - replays = [ - ( - random_tokens, - random_idx, - random_w, - torch.randn(random_tokens.shape, device=device, generator=gen).to(torch.bfloat16), - ), - self._moe_calls(1)[0], - ] - # Static inputs, holding the captured call's values first. - tokens, topk_idx, w, grad = (t.clone() for t in self._moe_calls(2)[1]) - x = tokens.requires_grad_(True) - topk_w = w.requires_grad_(True) - model = te_ops.Sequential(*ops) - params = list(model.parameters()) - out = {} + def test_cuda_graph_capture(self): + """Capture raw dispatch+combine into a CUDA graph; replay must be bit-stable.""" + buf = self._make_buffer() + topk_idx, tokens, w = _make_identity_inputs(self.cfg.rank, self.cfg.ep_size) + recv_tokens, recv_w, _ = self._make_raw_recv() + result = torch.empty_like(tokens) def step(): - for t in (x, topk_w, *params): - t.grad = None - with te.autocast(enabled=recipe is not None, recipe=recipe): - out["y"] = model(x, topk_idx, topk_w, topk_idx) - out["y"].backward(grad) + ep_prepare(buf, topk_idx) + _ep_dispatch_raw(buf, topk_idx, tokens, w, recv_tokens, recv_w) + _ep_combine_raw(buf, self._weighted(recv_tokens, recv_w), result) - graph = self._capture(step) - self.assertTrue(self._moe_overlap_selected(model)) - results = [] - for call in replays: - with torch.no_grad(): - for static, value in zip((x, topk_idx, topk_w, grad), call): - static.copy_(value) - graph.replay() - got = ( - (out["y"].detach().clone(), x.grad.clone(), topk_w.grad.clone()), - [p.grad.clone() for p in params], - ) - ref_model = te_ops.Sequential(*ref_ops) - for p in ref_model.parameters(): - p.grad = None - with self._moe_fusion(False), te.autocast(enabled=recipe is not None, recipe=recipe): - ref = (self._moe_call(ref_model, *call), self._param_grads(ref_model)) - torch.cuda.synchronize() - results.append((got, ref)) - # Compare once every rank has run every replay, so a mismatch on one rank leaves no rank - # waiting in a later replay. - for got, ref in results: - if recipe is None: - self._assert_moe_close(got, ref) - else: - # The unfused MXFP8 ops round the SwiGLU output and requantize to E4M3, so compare - # outputs and gradients in norm at the E4M3 tolerance. - self._assert_moe_close(got, ref, in_norm=True, outputs_in_norm=True, rtol=1 / 16) + for _ in range(3): + step() + torch.cuda.synchronize() - @_mxfp8_align_test - @_overlap_test - def test_moe_overlap_instances(self): - """Weights created in inference mode, which have no version counter, run in the fused op - with the FC1 rows reordered at each call. Two FusedMoE instances, each with its own - EpBuffer, interleave safely: the second instance's forward and backward between the first - instance's forward and backward leave the first instance's output and gradients identical - to running it alone. One buffer and op instance per outstanding call.""" - self._require_moe_overlap() - config = self._overlap_config() - with torch.inference_mode(): - ops = self._moe_ops(config, self._make_buffer_from_config(config), None) - model = te_ops.Sequential(*ops) - topk_idx, tokens, w = _make_identity_inputs(self.cfg.rank, self.cfg.ep_size) - model(tokens, topk_idx, w, topk_idx) - torch.cuda.synchronize() - self.assertTrue(self._moe_overlap_selected(model)) + # Routing is fixed per layer; prepare runs once before capture. + ep_prepare(buf, topk_idx) + torch.cuda.synchronize() - # Separate instances and buffers; _moe_ops seeds identical weights. - model_a = te_ops.Sequential(*self._moe_ops(config, self._make_buffer_from_config(config))) - model_b = te_ops.Sequential(*self._moe_ops(config, self._make_buffer_from_config(config))) - call_a, call_b = self._moe_calls(2) + graph = torch.cuda.CUDAGraph() + s = torch.cuda.Stream() + s.wait_stream(torch.cuda.current_stream()) + with torch.cuda.stream(s): + with torch.cuda.graph(graph): + _ep_dispatch_raw(buf, topk_idx, tokens, w, recv_tokens, recv_w) + _ep_combine_raw(buf, self._weighted(recv_tokens, recv_w), result) + torch.cuda.current_stream().wait_stream(s) + torch.cuda.synchronize() - def forward(model, call): - for p in model.parameters(): - p.grad = None - x = call[0].clone().requires_grad_(True) - topk_w = call[2].clone().requires_grad_(True) - return x, topk_w, model(x, call[1], topk_w, call[1]) + ref = result.clone() + for _ in range(5): + graph.replay() + torch.cuda.synchronize() + torch.testing.assert_close(result.float(), ref.float(), atol=0, rtol=0) - def backward(model, x, topk_w, y, grad): - y.backward(grad) - torch.cuda.synchronize() - return [y.detach(), x.grad, topk_w.grad] + self._param_grads(model) + def _caller_recv(self): + """A persistent recv token + weight buffer pair sized to recv_capacity_per_rank, for + capturing a caller-provided-recv dispatch.""" + rc = self.cfg.recv_capacity_per_rank + return ( + torch.empty(rc, HIDDEN_DIM, dtype=torch.bfloat16, device=self.cfg.device), + torch.empty(rc, dtype=torch.float32, device=self.cfg.device), + ) - # Each call run alone, as the serial reference. - xa, wa, ya = forward(model_a, call_a) - alone_a = backward(model_a, xa, wa, ya, call_a[3]) - self.assertTrue(self._moe_overlap_selected(model_a)) - xb, wb, yb = forward(model_b, call_b) - alone_b = backward(model_b, xb, wb, yb, call_b[3]) - self.assertTrue(self._moe_overlap_selected(model_b)) + def test_fused_count_mode_parity(self): + """Under CUDA graph capture with a caller recv buffer, dispatch derives + tokens_per_expert / total_recv_tokens from the fused count scan instead of the + AllGather prepare. Zeroing the counts before replay forces the replayed graph to + repopulate them; the result must match the AllGather counts for the same routing.""" + if not FUSED_COUNT: + self.skipTest("fused count-mode dispatch not enabled") + if EAGER: + self.skipTest("fused count mode requires non-eager static recv capacity") + topk_idx, tokens, w = _make_identity_inputs(self.cfg.rank, self.cfg.ep_size) - # Interleaved: the second instance's whole call lands between the first's forward and - # backward; separate buffers keep each call's routing state intact. - xa, wa, ya = forward(model_a, call_a) - xb, wb, yb = forward(model_b, call_b) - inter_b = backward(model_b, xb, wb, yb, call_b[3]) - inter_a = backward(model_a, xa, wa, ya, call_a[3]) - self._assert_moe_close(inter_a, alone_a, UNFUSED_MLP_REFERENCE, outputs_in_norm=False) - self._assert_moe_close(inter_b, alone_b, UNFUSED_MLP_REFERENCE, outputs_in_norm=False) + # Reference counts via the AllGather prepare path. + ref_buf = self._make_buffer() + ref_tokens_per_expert = ep_prepare(ref_buf, topk_idx).clone() + torch.cuda.synchronize() + ref_total = int(ref_buf.total_recv_tokens.item()) - # Autograd + # Fused path: capture a caller-recv dispatch, clear the counts, then replay so the + # replayed graph is the sole source of the counts. + buf = self._make_buffer() + rbuf_t, rbuf_w = self._caller_recv() + graph = self._capture( + lambda: ep_dispatch( + buf, tokens, topk_idx, w, recv_tokens=rbuf_t, recv_topk_weights=rbuf_w + ) + ) + buf.tokens_per_expert.zero_() + buf.total_recv_tokens.zero_() + graph.replay() + torch.cuda.synchronize() - @_zero_copy_test_include - def test_dispatch_autograd(self): - """0.5*||recv_tokens||^2 ; grad_tokens equals TOP_K * tokens. Covers the - EpBuffer-owned recv tokens (symm-mem under zero-copy) and, in normal - mode, a caller-supplied recv_tokens buffer.""" - if ZERO_COPY: - cases = [("buffer_owned", None)] - else: - rt_buf, _rw_buf, _ = self._make_raw_recv() - cases = [ - ("default_alloc", None), - ("caller_recv", rt_buf), - ] - for label, recv_tokens in cases: - with self.subTest(case=label): - buf = self._make_buffer() - topk_idx, tokens, w = _make_identity_inputs(self.cfg.rank, self.cfg.ep_size) - tokens_p = tokens.detach().clone().requires_grad_(True) - rt, rw, _tc = ep_dispatch(buf, tokens_p, topk_idx, w, recv_tokens=recv_tokens) - if recv_tokens is not None: # caller-supplied recv_tokens must be used in place - self.assertEqual(rt.data_ptr(), recv_tokens.data_ptr()) - rt = self._stage_grad_symm(rt) - rw = self._stage_grad_symm(rw) - (0.5 * (rt.float() ** 2).sum() + 0.0 * rw.float().sum()).backward() - torch.cuda.synchronize() - torch.testing.assert_close( - tokens_p.grad.float(), tokens.float() * float(TOP_K), atol=5e-2, rtol=5e-2 - ) + torch.testing.assert_close(buf.tokens_per_expert, ref_tokens_per_expert, atol=0, rtol=0) + self.assertEqual(int(buf.total_recv_tokens.item()), ref_total) - # MXFP8 dispatch + def test_fused_count_mode_changing_routing(self): + """Routing may differ between graph replays. Each replay must re-derive its counts from + its own routing rather than reuse the captured step's values (stale-count guard).""" + if not FUSED_COUNT: + self.skipTest("fused count-mode dispatch not enabled") + if EAGER: + self.skipTest("fused count mode requires non-eager static recv capacity") + idx_a, tokens, w = _make_identity_inputs(self.cfg.rank, self.cfg.ep_size) + idx_b = _make_skewed_routing(self.cfg.rank, self.cfg.ep_size) # skews expert/rank totals + + buf = self._make_buffer() + topk_idx, rbuf_t, rbuf_w = idx_a.clone(), *self._caller_recv() + graph = self._capture( + lambda: ep_dispatch( + buf, tokens, topk_idx, w, recv_tokens=rbuf_t, recv_topk_weights=rbuf_w + ) + ) - def _mxfp8_quantizer(self): - from transformer_engine.pytorch.tensor.mxfp8_tensor import MXFP8Quantizer + ref_tpes = [] + for routing in (idx_b, idx_a): + # Reference counts for this routing via the AllGather prepare path. + ref_buf = self._make_buffer() + ref_tpe = ep_prepare(ref_buf, routing).clone() + torch.cuda.synchronize() + ref_tpes.append(ref_tpe) - return MXFP8Quantizer(fp8_dtype=tex.DType.kFloat8E4M3, rowwise=True, columnwise=False) + topk_idx.copy_(routing) + buf.tokens_per_expert.zero_() + buf.total_recv_tokens.zero_() + graph.replay() + torch.cuda.synchronize() - def _assert_mxfp8_matches_bf16(self, recv_mx, tokens, topk_idx, w, tc): - """Dequantized MXFP8 recv matches a bf16 dispatch of the same tokens, per expert. Row - order within an expert's block can differ between the two dispatch kernels, so compare - by sorted row sums (order-tolerant) instead of position.""" - ref_tokens = self._mxfp8_quantizer().quantize(tokens).dequantize() - ref_recv, _rw, _tc = ep_dispatch(self._make_buffer(alignment=256), ref_tokens, topk_idx, w) - torch.cuda.synchronize() - got = _degroup_mxfp8(recv_mx).float() - cum = [0] + tc.cumsum(0).tolist() - for lo, hi in zip(cum[:-1], cum[1:]): - torch.testing.assert_close( - got[lo:hi].sum(dim=1).sort().values, - ref_recv[lo:hi].float().sum(dim=1).sort().values, - atol=1e-1, - rtol=1e-1, + torch.testing.assert_close(buf.tokens_per_expert, ref_tpe, atol=0, rtol=0) + self.assertEqual( + int(buf.total_recv_tokens.item()), int(ref_buf.total_recv_tokens.item()) ) - @_eager_test_include - @_zero_copy_test_include - @_mxfp8_align_test - def test_dispatch_mxfp8(self): - """MXFP8 dispatch quantizes bf16 tokens internally; recv (a per-expert GroupedTensor) - dequantized matches a bf16 dispatch of the same tokens. Under zero-copy the recv data and - scales are symm-mem backed.""" - self._require_mxfp8_shapes() - topk_idx, tokens, w = _make_identity_inputs(self.cfg.rank, self.cfg.ep_size) - buf = self._make_buffer(dispatch_fwd_quant_recipe=MXFP8BlockScaling(), alignment=256) - recv_mx, _rw, tc = ep_dispatch(buf, tokens, topk_idx, w) - if ZERO_COPY: - self.assertTrue(is_symm_backed(recv_mx.rowwise_data)) - self.assertTrue(is_symm_backed(recv_mx.scale_inv)) - self._assert_mxfp8_matches_bf16(recv_mx, tokens, topk_idx, w, tc) + # Guard the guard: if the two routings happen to produce identical counts, reusing a + # stale copy would pass unnoticed and this test would stop detecting the bug. + self.assertFalse(torch.equal(ref_tpes[0], ref_tpes[1])) - @_eager_test_include - @_mxfp8_align_test - def test_dispatch_mxfp8_autograd(self): - """MXFP8 dispatch fwd+bwd. Seeding the recv grad with ones scatters TOP_K back to each token - under identity routing, so grad_tokens equals TOP_K through the dispatch backward and the - input quantizer STE. Exercises the fused eager MXFP8 dispatch backward.""" - self._require_mxfp8_shapes() + @_overflow_test_include + def test_fused_count_mode_overflow(self): + """Fused count-mode dispatch under capture reports the pre-drop recv total and caps the + per-expert counts at recv_capacity, matching the AllGather prepare overflow semantics.""" + if not FUSED_COUNT: + self.skipTest("fused count-mode dispatch not enabled") + if not OVERFLOW: + self.skipTest("overflow-only assertions") + if EAGER: + self.skipTest("fused count mode requires non-eager static recv capacity") topk_idx, tokens, w = _make_identity_inputs(self.cfg.rank, self.cfg.ep_size) - tokens_p = tokens.detach().clone().requires_grad_(True) - buf = self._make_buffer(dispatch_fwd_quant_recipe=MXFP8BlockScaling(), alignment=256) - recv_mx, _rw, _tc = ep_dispatch(buf, tokens_p, topk_idx, w) - g_recv = torch.ones(recv_mx.shape, dtype=torch.bfloat16, device=self.cfg.device) - torch.autograd.backward(recv_mx, grad_tensors=g_recv) - torch.cuda.synchronize() - torch.testing.assert_close( - tokens_p.grad.float(), - torch.full_like(tokens_p, float(TOP_K)).float(), - atol=5e-2, - rtol=5e-2, + expected_recv = TOKENS_PER_RANK * TOP_K + self.assertGreater(expected_recv, self.cfg.recv_capacity_per_rank) + + buf = self._make_buffer() + rbuf_t, rbuf_w = self._caller_recv() + graph = self._capture( + lambda: ep_dispatch( + buf, tokens, topk_idx, w, recv_tokens=rbuf_t, recv_topk_weights=rbuf_w + ) ) + buf.tokens_per_expert.zero_() + buf.total_recv_tokens.zero_() + graph.replay() + torch.cuda.synchronize() + + self.assertEqual(int(buf.total_recv_tokens.item()), expected_recv) + self.assertEqual(int(buf.tokens_per_expert.sum().item()), self.cfg.recv_capacity_per_rank) - @_zero_copy_test_include @_mxfp8_align_test - def test_caller_provides_dispatch_recv_mxfp8(self): - """One caller-supplied buffer holds the recv data followed by the e8m0 scales; ep_dispatch - slices it and the returned GroupedTensor views the data and scale regions of that buffer.""" + def test_dispatch_mxfp8_fused_capture(self): + """Fused count-mode MXFP8 dispatch with a caller recv buffer. The returned GroupedTensor + views the caller buffer's data then scale regions; counts, payload/weights (per-expert, + order-tolerant), and total must match the AllGather prepare.""" + if not FUSED_COUNT: + self.skipTest("fused count-mode dispatch not enabled") + if EAGER: + self.skipTest("fused count mode requires non-eager static recv capacity") self._require_mxfp8_shapes() from transformer_engine.pytorch.constants import MXFP8_BLOCK_SCALING_SIZE rc = self.cfg.recv_capacity_per_rank cols = HIDDEN_DIM // MXFP8_BLOCK_SCALING_SIZE nbytes = rc * (HIDDEN_DIM + cols) # fp8 data + e8m0 scales, one byte per element - if ZERO_COPY: - recv_buf = symm_mem_alloc((nbytes,), torch.uint8, self.ep_group) - else: - recv_buf = torch.empty(nbytes, dtype=torch.uint8, device=self.cfg.device) + recv_buf = torch.empty(nbytes, dtype=torch.uint8, device=self.cfg.device) + rbuf_w = torch.empty(rc, dtype=torch.float32, device=self.cfg.device) buf = self._make_buffer(dispatch_fwd_quant_recipe=MXFP8BlockScaling(), alignment=256) topk_idx, tokens, w = _make_identity_inputs(self.cfg.rank, self.cfg.ep_size) - recv_mx, _rw, tc = ep_dispatch(buf, tokens, topk_idx, w, recv_tokens=recv_buf) - # the returned GroupedTensor views the caller buffer's data then scale regions + + # Reference counts via the AllGather prepare path (alignment=256, no quant). + ref_tokens_per_expert = ep_prepare(self._make_buffer(alignment=256), topk_idx).clone() + torch.cuda.synchronize() + + out = {} + + def step(): + out["recv_mx"], out["rw"], _tc = ep_dispatch( + buf, tokens, topk_idx, w, recv_tokens=recv_buf, recv_topk_weights=rbuf_w + ) + + graph = self._capture(step) + buf.tokens_per_expert.zero_() + buf.total_recv_tokens.zero_() + graph.replay() + torch.cuda.synchronize() + + # The returned GroupedTensor views the caller buffer's data then scale regions, and the + # replayed fused scan repopulates the per-expert counts to match the AllGather path. + recv_mx = out["recv_mx"] self.assertEqual(recv_mx.rowwise_data.data_ptr(), recv_buf.data_ptr()) self.assertEqual(recv_mx.scale_inv.data_ptr(), recv_buf.data_ptr() + rc * HIDDEN_DIM) - self._assert_mxfp8_matches_bf16(recv_mx, tokens, topk_idx, w, tc) + torch.testing.assert_close(buf.tokens_per_expert, ref_tokens_per_expert, atol=0, rtol=0) - @_zero_copy_test_include - def test_caller_provides_dispatch_recv_tokens(self): - """Caller-supplied recv_tokens (symm-mem-backed in zero-copy): ep_dispatch - writes into it and returns a view of the caller's buffer.""" - if ZERO_COPY: - rc = self.cfg.recv_capacity_per_rank - rt_buf = symm_mem_alloc((rc, HIDDEN_DIM), torch.bfloat16, self.ep_group) - else: - rt_buf, _rw_buf, _ = self._make_raw_recv() - buf = self._make_buffer() - topk_idx, tokens, w = _make_identity_inputs(self.cfg.rank, self.cfg.ep_size) - tokens_p = tokens.detach().clone().requires_grad_(True) - rt, rw, _ = ep_dispatch(buf, tokens_p, topk_idx, w, recv_tokens=rt_buf) - self.assertEqual(rt.data_ptr(), rt_buf.data_ptr()) - rt = self._stage_grad_symm(rt) - rw = self._stage_grad_symm(rw) - (0.5 * (rt.float() ** 2).sum() + 0.0 * rw.float().sum()).backward() + # Replayed payload correctness: received tokens/scales, weights, and total count must + # come from the replay's own dispatch, not a stale copy from the captured step. + self._assert_mxfp8_matches_bf16(recv_mx, tokens, topk_idx, w, buf.tokens_per_expert) + ref_buf = self._make_buffer(alignment=256) + _ref_recv, ref_rw, _ref_tc = ep_dispatch(ref_buf, tokens, topk_idx, w) torch.cuda.synchronize() - torch.testing.assert_close( - tokens_p.grad.float(), tokens.float() * float(TOP_K), atol=5e-2, rtol=5e-2 - ) + cum = [0] + buf.tokens_per_expert.cumsum(0).tolist() + for lo, hi in zip(cum[:-1], cum[1:]): + torch.testing.assert_close( + out["rw"][lo:hi].sort().values, ref_rw[lo:hi].sort().values, atol=0, rtol=0 + ) + self.assertEqual(int(buf.total_recv_tokens.item()), int(ref_buf.total_recv_tokens.item())) + + # PP-1F1B handle isolation @_zero_copy_test_include - def test_caller_provides_grad_expert_out(self): - """Caller-supplied grad_out (symm-mem-backed in zero-copy): ep_combine's - backward scatters the expert-out grad into it.""" + def test_pp_1f1b_two_handles(self): + """PP-1F1B interleave (F0 F1 B0 F2 B1 B2) over 3 per-microbatch buffers, + run eagerly and replayed from a CUDA graph capturing the full fwd+bwd + schedule (prepare included; routing is fixed so replay reproduces it).""" + for capture in (False, True): + with self.subTest(capture=capture): + self._run_1f1b(capture) + + def _run_1f1b(self, capture): + T, H = TOKENS_PER_RANK, HIDDEN_DIM + idx, _toks, w = _make_identity_inputs(self.cfg.rank, self.cfg.ep_size) + scales = (0.13, 0.41, 0.77) + buffers, tokens, tokens_p = [], [], [] + for s in scales: + buffers.append(self._make_buffer()) + t = torch.full( + (T, H), s + self.cfg.rank * 0.01, dtype=torch.bfloat16, device=self.cfg.device + ) + tokens.append(t) + tokens_p.append(t.detach().clone().requires_grad_(True)) + + recv = [None, None, None] + # Per-microbatch grad-staging buffers, symm-mem under zero-copy and + # pre-allocated so nothing is allocated/freed mid-interleave. + recv_w = [None, None, None] rc = self.cfg.recv_capacity_per_rank if ZERO_COPY: - gbuf = symm_mem_alloc((rc, HIDDEN_DIM), torch.bfloat16, self.ep_group) + gbuf_t = [symm_mem_alloc((rc, H), torch.bfloat16, self.ep_group) for _ in scales] + gbuf_w = [symm_mem_alloc((rc,), torch.float32, self.ep_group) for _ in scales] + # Persistent symm-mem recv buffers per microbatch: leaving recv None + # pool-allocates, which is not CUDA-graph capturable. + rbuf_t = [symm_mem_alloc((rc, H), torch.bfloat16, self.ep_group) for _ in scales] + rbuf_w = [symm_mem_alloc((rc,), torch.float32, self.ep_group) for _ in scales] else: - gbuf = torch.empty(rc, HIDDEN_DIM, dtype=torch.bfloat16, device=self.cfg.device) - gbuf.zero_() - buf = self._make_buffer() - topk_idx, tokens, w = _make_identity_inputs(self.cfg.rank, self.cfg.ep_size) - tokens_p = tokens.detach().clone().requires_grad_(True) - recv_t, recv_w, _ = ep_dispatch(buf, tokens_p, topk_idx, w) - recv_t = self._stage_grad_symm(recv_t) - recv_w = self._stage_grad_symm(recv_w) - expert_out = self._expert_out(self._weighted(recv_t, recv_w)) - out = ep_combine(buf, expert_out, grad_out=gbuf) - (0.5 * (out.float() ** 2).sum()).backward() - torch.cuda.synchronize() - torch.testing.assert_close(out.float(), tokens.float(), atol=5e-2, rtol=5e-2) - torch.testing.assert_close(tokens_p.grad.float(), tokens.float(), atol=5e-2, rtol=5e-2) - # the caller-owned buffer was used as the combine-bwd scatter target - self.assertGreater(gbuf.abs().sum().item(), 0.0) + gbuf_t = gbuf_w = [None, None, None] + rbuf_t = rbuf_w = [None, None, None] - @_zero_copy_test_include - @_mxfp8_align_test - def test_combine_bwd_mxfp8_caller_grad_out(self): - """MXFP8 combine backward into a single caller buffer sliced into data + e8m0 scales: the - returned per-expert GroupedTensor views those regions and, dequantized, matches a bf16 - combine backward reference on the same routing. Under zero-copy the caller buffer and combine - input are symm-mem backed.""" - self._require_mxfp8_shapes() - from transformer_engine.pytorch.constants import MXFP8_BLOCK_SCALING_SIZE + def fwd(k): + rt, rw, _ = ep_dispatch( + buffers[k], + tokens_p[k], + idx, + w, + recv_tokens=rbuf_t[k], + recv_topk_weights=rbuf_w[k], + ) + recv[k] = self._stage_grad_symm(rt, gbuf_t[k]) + recv_w[k] = self._stage_grad_symm(rw, gbuf_w[k]) + + def bwd(k): + (0.5 * (recv[k].float() ** 2).sum() + 0.0 * recv_w[k].float().sum()).backward() + recv[k] = None + recv_w[k] = None + + def interleave(): + fwd(0) + fwd(1) + bwd(0) + fwd(2) + bwd(1) + bwd(2) - rc = self.cfg.recv_capacity_per_rank - cols = HIDDEN_DIM // MXFP8_BLOCK_SCALING_SIZE - topk_idx, tokens, w = _make_identity_inputs(self.cfg.rank, self.cfg.ep_size) - eo_vals = ( - torch.linspace(-0.5, 0.5, rc * HIDDEN_DIM, device=self.cfg.device) - .reshape(rc, HIDDEN_DIM) - .to(torch.bfloat16) - ) - # MXFP8 combine backward writes into one caller buffer (data then e8m0 scales) - buf_mx = self._make_buffer(combine_bwd_quant_recipe=MXFP8BlockScaling(), alignment=256) - _recv, _rw, tc = ep_dispatch(buf_mx, tokens, topk_idx, w) # seeds the routing - nbytes = rc * (HIDDEN_DIM + cols) - if ZERO_COPY: - grad_buf = symm_mem_alloc((nbytes,), torch.uint8, self.ep_group) + def zero_grads(): + for tp in tokens_p: + if tp.grad is not None: + tp.grad.zero_() + + if not capture: + interleave() else: - grad_buf = torch.empty(nbytes, dtype=torch.uint8, device=self.cfg.device) - src_mx = eo_vals.detach().clone().requires_grad_(True) - out_mx = ep_combine(buf_mx, self._expert_out(src_mx), grad_out=grad_buf) - (0.5 * (out_mx.float() ** 2).sum()).backward() - g_mx = src_mx.grad # per-expert GroupedTensor viewing grad_buf - self.assertEqual(g_mx.rowwise_data.data_ptr(), grad_buf.data_ptr()) - self.assertEqual(g_mx.scale_inv.data_ptr(), grad_buf.data_ptr() + rc * HIDDEN_DIM) - # bf16 reference combine backward on the same routing - buf_bf = self._make_buffer(alignment=256) - ep_dispatch(buf_bf, tokens, topk_idx, w) - src_bf = eo_vals.detach().clone().requires_grad_(True) - out_bf = ep_combine(buf_bf, self._expert_out(src_bf)) - (0.5 * (out_bf.float() ** 2).sum()).backward() - torch.cuda.synchronize() - n = int(tc.sum()) - torch.testing.assert_close( - _degroup_mxfp8(g_mx).float(), src_bf.grad.float()[:n], atol=5e-2, rtol=5e-2 - ) + # Warmup on a side stream, then capture the full schedule and replay. + # Grads stay pre-allocated (zeroed, not None) so backward accumulates + # in place during both capture and replay. + s = torch.cuda.Stream() + s.wait_stream(torch.cuda.current_stream()) + with torch.cuda.stream(s): + for _ in range(3): + zero_grads() + interleave() + torch.cuda.current_stream().wait_stream(s) + torch.cuda.synchronize() + + zero_grads() + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph): + interleave() + zero_grads() + graph.replay() - @_eager_test_include - @_zero_copy_test_include - @_mxfp8_align_test - def test_combine_bwd_mxfp8(self): - """MXFP8 combine backward with an internally allocated grad target: the returned per-expert - GroupedTensor, dequantized, matches a bf16 combine backward reference on the same routing. - Under zero-copy the combine input is symm-mem backed. - """ - self._require_mxfp8_shapes() - topk_idx, tokens, w = _make_identity_inputs(self.cfg.rank, self.cfg.ep_size) - buf_mx = self._make_buffer(combine_bwd_quant_recipe=MXFP8BlockScaling(), alignment=256) - _recv, _rw, tc = ep_dispatch(buf_mx, tokens, topk_idx, w) # seeds the routing - # Combine input rows match the recv total (per-step in eager, capacity otherwise). - rows = int(buf_mx.total_recv_tokens.item()) if EAGER else self.cfg.recv_capacity_per_rank - eo_vals = ( - torch.linspace(-0.5, 0.5, rows * HIDDEN_DIM, device=self.cfg.device) - .reshape(rows, HIDDEN_DIM) - .to(torch.bfloat16) - ) - src_mx = eo_vals.detach().clone().requires_grad_(True) - out_mx = ep_combine(buf_mx, self._expert_out(src_mx)) - (0.5 * (out_mx.float() ** 2).sum()).backward() - g_mx = src_mx.grad # per-expert GroupedTensor - # bf16 reference combine backward on the same routing - buf_bf = self._make_buffer(alignment=256) - ep_dispatch(buf_bf, tokens, topk_idx, w) - src_bf = eo_vals.detach().clone().requires_grad_(True) - out_bf = ep_combine(buf_bf, self._expert_out(src_bf)) - (0.5 * (out_bf.float() ** 2).sum()).backward() torch.cuda.synchronize() - n = int(tc.sum()) - torch.testing.assert_close( - _degroup_mxfp8(g_mx).float(), src_bf.grad.float()[:n], atol=5e-2, rtol=5e-2 - ) + for k in range(3): + torch.testing.assert_close( + tokens_p[k].grad.float(), + tokens[k].float() * float(TOP_K), + atol=5e-2, + rtol=5e-2, + ) @_zero_copy_test_include - def test_zero_copy_pool_auto_alloc(self): - """Zero-copy with recv/grad left None: ep_dispatch/ep_combine allocate their IO - tensors from the symm-mem pool (is_symm_backed). This is the primary mcore - path — mcore hands no caller buffers, TE pools them on the fly.""" - if not ZERO_COPY: - self.skipTest("zero-copy pool auto-alloc only") + @_eager_test_include + def test_combine_autograd(self): + """ep_combine fwd+bwd; bwd grad target is the EpBuffer symm buffer (zc) or in-flight.""" buf = self._make_buffer() topk_idx, tokens, w = _make_identity_inputs(self.cfg.rank, self.cfg.ep_size) tokens_p = tokens.detach().clone().requires_grad_(True) - recv_t, recv_w, _ = ep_dispatch(buf, tokens_p, topk_idx, w) # recv_tokens=None -> pool - self.assertTrue(is_symm_backed(recv_t)) # dispatch recv came from the symm-mem pool + recv_t, recv_w, _ = ep_dispatch(buf, tokens_p, topk_idx, w) recv_t = self._stage_grad_symm(recv_t) recv_w = self._stage_grad_symm(recv_w) expert_out = self._expert_out(self._weighted(recv_t, recv_w)) - out = ep_combine(buf, expert_out) # grad_out=None -> bwd allocs the grad from the pool + out = ep_combine(buf, expert_out) (0.5 * (out.float() ** 2).sum()).backward() torch.cuda.synchronize() torch.testing.assert_close(out.float(), tokens.float(), atol=5e-2, rtol=5e-2) torch.testing.assert_close(tokens_p.grad.float(), tokens.float(), atol=5e-2, rtol=5e-2) - # Multi-iter stability - - @_eager_test_include - def test_dispatch_autograd_multiple_iterations(self): - """5 fwd+bwd iters on the same EpBuffer must be bit-stable.""" - buf = self._make_buffer() - topk_idx, tokens, w = _make_identity_inputs(self.cfg.rank, self.cfg.ep_size) - - def one_step(): - tokens_p = tokens.detach().clone().requires_grad_(True) - out = self._moe_step(buf, topk_idx, tokens_p, w) - loss = 0.5 * (out.float() ** 2).sum() - loss.backward() - return out.detach().clone(), tokens_p.grad.detach().clone() - - out_ref, grad_ref = one_step() - torch.cuda.synchronize() - for _ in range(4): - out_i, grad_i = one_step() - torch.cuda.synchronize() - torch.testing.assert_close(out_i, out_ref, atol=0, rtol=0) - torch.testing.assert_close(grad_i, grad_ref, atol=0, rtol=0) - - # CUDA graph - - def test_cuda_graph_capture(self): - """Capture raw dispatch+combine into a CUDA graph; replay must be bit-stable.""" - buf = self._make_buffer() - topk_idx, tokens, w = _make_identity_inputs(self.cfg.rank, self.cfg.ep_size) - recv_tokens, recv_w, _ = self._make_raw_recv() - result = torch.empty_like(tokens) - - def step(): - ep_prepare(buf, topk_idx) - _ep_dispatch_raw(buf, topk_idx, tokens, w, recv_tokens, recv_w) - _ep_combine_raw(buf, self._weighted(recv_tokens, recv_w), result) - - for _ in range(3): - step() - torch.cuda.synchronize() - - # Routing is fixed per layer; prepare runs once before capture. - ep_prepare(buf, topk_idx) - torch.cuda.synchronize() - - graph = torch.cuda.CUDAGraph() - s = torch.cuda.Stream() - s.wait_stream(torch.cuda.current_stream()) - with torch.cuda.stream(s): - with torch.cuda.graph(graph): - _ep_dispatch_raw(buf, topk_idx, tokens, w, recv_tokens, recv_w) - _ep_combine_raw(buf, self._weighted(recv_tokens, recv_w), result) - torch.cuda.current_stream().wait_stream(s) - torch.cuda.synchronize() - ref = result.clone() - for _ in range(5): - graph.replay() - torch.cuda.synchronize() - torch.testing.assert_close(result.float(), ref.float(), atol=0, rtol=0) +class TestMoeEpSequential(_EpTestCase): + """Integration tests for Dispatch -> expert MLP -> Combine sequences.""" - def _capture(self, step): - """Warm up ``step`` on a side stream then capture it into a CUDA graph. Returns - the graph; the caller replays it. With NVTE_EP_FUSED_PREPARE_DISPATCH set, dispatch - under capture takes the fused count-mode path that derives the counts from the - dispatch scan.""" - s = torch.cuda.Stream() - s.wait_stream(torch.cuda.current_stream()) - with torch.cuda.stream(s): - for _ in range(3): - step() - torch.cuda.current_stream().wait_stream(s) - torch.cuda.synchronize() - graph = torch.cuda.CUDAGraph() - with torch.cuda.graph(graph): - step() - return graph + @staticmethod + def _reference_weights(op): + """Pack GroupedLinear weights into MoeEpReference ``(E, in, out)`` layout.""" + weight = op.weight + num_groups = op.num_groups + out_features = op.out_features + in_features = op.in_features + data = weight.rowwise_data.view( + num_groups, + out_features, + in_features, + ).permute(0, 2, 1) + if weight.quantizer is None: + return data.detach() + scale = ( + weight.scale_inv.view( + num_groups, + out_features, + in_features // 32, + ) + .view(torch.float8_e8m0fnu) + .permute(0, 2, 1) + ) + return BlockScaledTensor( + data=data.view(torch.float8_e4m3fn).detach(), + scale=scale.detach(), + format="mxfp8", + logical_shape=tuple(data.shape), + axis=1, + ) - def _caller_recv(self): - """A persistent recv token + weight buffer pair sized to recv_capacity_per_rank, for - capturing a caller-provided-recv dispatch.""" - rc = self.cfg.recv_capacity_per_rank - return ( - torch.empty(rc, HIDDEN_DIM, dtype=torch.bfloat16, device=self.cfg.device), - torch.empty(rc, dtype=torch.float32, device=self.cfg.device), + def test_runtime_buffer_config_mismatch(self): + config = self._make_config() + buffer = self._make_buffer_from_config(config) + topk_idx, tokens, topk_weights = _make_identity_inputs( + self.cfg.rank, + self.cfg.ep_size, + ) + dispatch = te_ops.MoeDispatch(config, buffer) + replacements = { + "top_k": config.top_k + 1, + "hidden_dim": config.hidden_dim + 1, + "num_local_experts": config.num_local_experts + 1, + "max_tokens_per_rank": config.max_tokens_per_rank + 1, + "recv_capacity_per_rank": config.recv_capacity_per_rank + 1, + "alignment": 1, + "payload_dtype": torch.float16, + "zero_copy": not config.zero_copy, + } + for field_name, wrong_value in replacements.items(): + with self.subTest(field_name=field_name): + original = getattr(buffer, field_name) + setattr(buffer, field_name, wrong_value) + try: + with self.assertRaisesRegex(ValueError, field_name): + dispatch(tokens, topk_idx, topk_weights) + finally: + setattr(buffer, field_name, original) + + wrong_config = replace(config, drop_on_overflow=not config.drop_on_overflow) + with self.assertRaisesRegex(ValueError, "drop_on_overflow"): + te_ops.MoeDispatch(wrong_config, buffer)(tokens, topk_idx, topk_weights) + with self.assertRaisesRegex(ValueError, "ep_group"): + te_ops.MoeDispatch(replace(config, ep_group=None), buffer)( + tokens, topk_idx, topk_weights + ) + expert_out = torch.empty( + self.cfg.recv_capacity_per_rank, + HIDDEN_DIM, + dtype=torch.bfloat16, + device=self.cfg.device, ) + with self.assertRaisesRegex(ValueError, "buffer config"): + original = buffer.hidden_dim + buffer.hidden_dim += 1 + try: + te_ops.MoeCombine(config, buffer)(expert_out, topk_idx) + finally: + buffer.hidden_dim = original - def test_fused_count_mode_parity(self): - """Under CUDA graph capture with a caller recv buffer, dispatch derives - tokens_per_expert / total_recv_tokens from the fused count scan instead of the - AllGather prepare. Zeroing the counts before replay forces the replayed graph to - repopulate them; the result must match the AllGather counts for the same routing.""" - if not FUSED_COUNT: - self.skipTest("fused count-mode dispatch not enabled") - if EAGER: - self.skipTest("fused count mode requires non-eager static recv capacity") - topk_idx, tokens, w = _make_identity_inputs(self.cfg.rank, self.cfg.ep_size) + # The communication recipes are backend configuration, so a config that + # disagrees with the buffer about the transport format is rejected. + mxfp8_config = replace( + config, + dispatch_fwd_quant_recipe=MXFP8BlockScaling(), + combine_bwd_quant_recipe=MXFP8BlockScaling(), + ) + mxfp8_buffer = self._make_buffer_from_config(mxfp8_config) + with self.assertRaisesRegex(ValueError, "dispatch_fwd_quant_recipe"): + te_ops.MoeDispatch(config, mxfp8_buffer)(tokens, topk_idx, topk_weights) + with self.assertRaisesRegex(ValueError, "combine_bwd_quant_recipe"): + te_ops.MoeCombine(config, mxfp8_buffer)(expert_out, topk_idx) - # Reference counts via the AllGather prepare path. - ref_buf = self._make_buffer() - ref_tokens_per_expert = ep_prepare(ref_buf, topk_idx).clone() + def _run_dispatch_combine_identity(self, *, mxfp8): + """Route, apply top-k weights, and combine back to local token order.""" + recipe = MXFP8BlockScaling() if mxfp8 else None + if mxfp8: + self._require_mxfp8_shapes() + config = self._make_config( + alignment=256 if mxfp8 else 0, + dispatch_fwd_quant_recipe=recipe, + combine_bwd_quant_recipe=recipe, + ) + buffer = self._make_buffer_from_config(config) + dispatch = te_ops.MoeDispatch(config, buffer) + combine = te_ops.MoeCombine(config, buffer) + topk_idx, tokens, topk_weights = _make_identity_inputs( + self.cfg.rank, + self.cfg.ep_size, + ) + recv_tokens, tokens_per_expert, recv_weights = dispatch( + tokens, + topk_idx, + topk_weights, + ) + if mxfp8: + # Convert to BF16 since combine only supports BF16 in NCCL EP + # for now. dequantizing to mxfp8 below changes its overall shape + # to sum(tokens_per_expert). + recv_tokens = _degroup_mxfp8(recv_tokens) + recv_weights = recv_weights[: recv_tokens.shape[0]] + weighted_expert_output = (recv_tokens.float() * recv_weights.float().unsqueeze(-1)).to( + torch.bfloat16 + ) + output = combine(weighted_expert_output, topk_idx) torch.cuda.synchronize() - ref_total = int(ref_buf.total_recv_tokens.item()) + torch.testing.assert_close(output, tokens, atol=5e-2, rtol=5e-2) + self.assertEqual(tokens_per_expert.data_ptr(), buffer.tokens_per_expert.data_ptr()) - # Fused path: capture a caller-recv dispatch, clear the counts, then replay so the - # replayed graph is the sole source of the counts. - buf = self._make_buffer() - rbuf_t, rbuf_w = self._caller_recv() - graph = self._capture( - lambda: ep_dispatch( - buf, tokens, topk_idx, w, recv_tokens=rbuf_t, recv_topk_weights=rbuf_w - ) - ) - buf.tokens_per_expert.zero_() - buf.total_recv_tokens.zero_() - graph.replay() + @_eager_test_include + @_mxfp8_align_test + @_overlap_test + def test_unfused_ops_on_overlap_group(self): + """On an overlap-pass group, MoeDispatch and MoeCombine run unfused and form an identity, + forward and backward.""" + config = self._overlap_config() + buffer = self._make_buffer_from_config(config) + dispatch = te_ops.MoeDispatch(config, buffer) + combine = te_ops.MoeCombine(config, buffer) + topk_idx, tokens, topk_weights = _make_identity_inputs(self.cfg.rank, self.cfg.ep_size) + x = tokens.clone().requires_grad_(True) + w = topk_weights.clone().requires_grad_(True) + recv_tokens, _tokens_per_expert, recv_weights = dispatch(x, topk_idx, w) + output = combine(recv_tokens * recv_weights.unsqueeze(-1).to(torch.bfloat16), topk_idx) + gen = torch.Generator(device=self.cfg.device).manual_seed(8) + grad_out = torch.randn(tokens.shape, device=self.cfg.device, generator=gen) + output.backward(grad_out.to(torch.bfloat16)) torch.cuda.synchronize() + torch.testing.assert_close(output, tokens, atol=5e-2, rtol=5e-2) + torch.testing.assert_close(x.grad.float(), grad_out, atol=5e-2, rtol=5e-2) + grad_w_ref = (tokens.float() * grad_out).sum(-1, keepdim=True).expand_as(w) + torch.testing.assert_close(w.grad.float(), grad_w_ref, atol=5e-1, rtol=5e-2) - torch.testing.assert_close(buf.tokens_per_expert, ref_tokens_per_expert, atol=0, rtol=0) - self.assertEqual(int(buf.total_recv_tokens.item()), ref_total) + @_eager_test_include + def test_dispatch_combine_identity_bf16(self): + """MoeDispatch and MoeCombine basic ops form an identity in BF16.""" + self._run_dispatch_combine_identity(mxfp8=False) - def test_fused_count_mode_changing_routing(self): - """Routing may differ between graph replays. Each replay must re-derive its counts from - its own routing rather than reuse the captured step's values (stale-count guard).""" - if not FUSED_COUNT: - self.skipTest("fused count-mode dispatch not enabled") - if EAGER: - self.skipTest("fused count mode requires non-eager static recv capacity") - idx_a, tokens, w = _make_identity_inputs(self.cfg.rank, self.cfg.ep_size) - idx_b = _make_skewed_routing(self.cfg.rank, self.cfg.ep_size) # skews expert/rank totals + @_eager_test_include + @_mxfp8_align_test + def test_dispatch_combine_identity_mxfp8(self): + """MoeDispatch and MoeCombine basic ops form an identity with MXFP8 transport.""" + self._run_dispatch_combine_identity(mxfp8=True) - buf = self._make_buffer() - topk_idx, rbuf_t, rbuf_w = idx_a.clone(), *self._caller_recv() - graph = self._capture( - lambda: ep_dispatch( - buf, tokens, topk_idx, w, recv_tokens=rbuf_t, recv_topk_weights=rbuf_w - ) + def _make_megamoe_model( + self, + *, + recipe, + accumulate_into_main_grad=False, + delay_wgrad_compute=False, + glu_interleave_size=None, + ): + """Build the exact five-op sequence recognized by MegaMoE fusion.""" + config = self._make_config( + alignment=256 if recipe is not None else 0, + dispatch_fwd_quant_recipe=recipe, + combine_bwd_quant_recipe=recipe, ) - - ref_tpes = [] - for routing in (idx_b, idx_a): - # Reference counts for this routing via the AllGather prepare path. - ref_buf = self._make_buffer() - ref_tpe = ep_prepare(ref_buf, routing).clone() - torch.cuda.synchronize() - ref_tpes.append(ref_tpe) - - topk_idx.copy_(routing) - buf.tokens_per_expert.zero_() - buf.total_recv_tokens.zero_() - graph.replay() - torch.cuda.synchronize() - - torch.testing.assert_close(buf.tokens_per_expert, ref_tpe, atol=0, rtol=0) - self.assertEqual( - int(buf.total_recv_tokens.item()), int(ref_buf.total_recv_tokens.item()) + buffer = self._make_buffer_from_config(config) + dispatch = te_ops.MoeDispatch(config, buffer) + init_ctx = ( + te.quantized_model_init(enabled=True, recipe=recipe) + if recipe is not None + else nullcontext() + ) + with init_ctx: + fc1 = te_ops.GroupedLinear( + NUM_LOCAL_EXPERTS, + HIDDEN_DIM, + 2 * 256, + bias=False, + device=self.cfg.device, + dtype=torch.bfloat16, + single_grouped_weight=True, + accumulate_into_main_grad=accumulate_into_main_grad, + delay_wgrad_compute=delay_wgrad_compute, ) - - # Guard the guard: if the two routings happen to produce identical counts, reusing a - # stale copy would pass unnoticed and this test would stop detecting the bug. - self.assertFalse(torch.equal(ref_tpes[0], ref_tpes[1])) - - @_overflow_test_include - def test_fused_count_mode_overflow(self): - """Fused count-mode dispatch under capture reports the pre-drop recv total and caps the - per-expert counts at recv_capacity, matching the AllGather prepare overflow semantics.""" - if not FUSED_COUNT: - self.skipTest("fused count-mode dispatch not enabled") - if not OVERFLOW: - self.skipTest("overflow-only assertions") - if EAGER: - self.skipTest("fused count mode requires non-eager static recv capacity") - topk_idx, tokens, w = _make_identity_inputs(self.cfg.rank, self.cfg.ep_size) - expected_recv = TOKENS_PER_RANK * TOP_K - self.assertGreater(expected_recv, self.cfg.recv_capacity_per_rank) - - buf = self._make_buffer() - rbuf_t, rbuf_w = self._caller_recv() - graph = self._capture( - lambda: ep_dispatch( - buf, tokens, topk_idx, w, recv_tokens=rbuf_t, recv_topk_weights=rbuf_w + activation = te_ops.ScaledSwiGLU( + glu_interleave_size=glu_interleave_size, ) - ) - buf.tokens_per_expert.zero_() - buf.total_recv_tokens.zero_() - graph.replay() - torch.cuda.synchronize() - - self.assertEqual(int(buf.total_recv_tokens.item()), expected_recv) - self.assertEqual(int(buf.tokens_per_expert.sum().item()), self.cfg.recv_capacity_per_rank) + fc2 = te_ops.GroupedLinear( + NUM_LOCAL_EXPERTS, + 256, + HIDDEN_DIM, + bias=False, + device=self.cfg.device, + dtype=torch.bfloat16, + single_grouped_weight=True, + accumulate_into_main_grad=accumulate_into_main_grad, + delay_wgrad_compute=delay_wgrad_compute, + ) + combine = te_ops.MoeCombine(config, buffer) + dispatch.set_extra_output_channel(0, "tokens_per_expert", output_to_caller=False) + dispatch.set_extra_output_channel(1, "routing_weights", output_to_caller=False) + fc1.set_extra_input_channel(0, "tokens_per_expert") + activation.set_extra_input_channel(0, "routing_weights") + fc2.set_extra_input_channel(0, "tokens_per_expert") + model = te_ops.Sequential(dispatch, fc1, activation, fc2, combine) + return model, fc1, fc2, buffer - @_mxfp8_align_test - def test_dispatch_mxfp8_fused_capture(self): - """Fused count-mode MXFP8 dispatch with a caller recv buffer. The returned GroupedTensor - views the caller buffer's data then scale regions; counts, payload/weights (per-expert, - order-tolerant), and total must match the AllGather prepare.""" - if not FUSED_COUNT: - self.skipTest("fused count-mode dispatch not enabled") - if EAGER: - self.skipTest("fused count mode requires non-eager static recv capacity") - self._require_mxfp8_shapes() - from transformer_engine.pytorch.constants import MXFP8_BLOCK_SCALING_SIZE + @_eager_test_include + def test_megamoe_bf16_numerics(self): + self._run_megamoe_vs_reference(quantization="bf16") - rc = self.cfg.recv_capacity_per_rank - cols = HIDDEN_DIM // MXFP8_BLOCK_SCALING_SIZE - nbytes = rc * (HIDDEN_DIM + cols) # fp8 data + e8m0 scales, one byte per element - recv_buf = torch.empty(nbytes, dtype=torch.uint8, device=self.cfg.device) - rbuf_w = torch.empty(rc, dtype=torch.float32, device=self.cfg.device) - buf = self._make_buffer(dispatch_fwd_quant_recipe=MXFP8BlockScaling(), alignment=256) - topk_idx, tokens, w = _make_identity_inputs(self.cfg.rank, self.cfg.ep_size) + @_eager_test_include + @_mxfp8_align_test + def test_megamoe_mxfp8_numerics(self): + self._run_megamoe_vs_reference(quantization="mxfp8") - # Reference counts via the AllGather prepare path (alignment=256, no quant). - ref_tokens_per_expert = ep_prepare(self._make_buffer(alignment=256), topk_idx).clone() - torch.cuda.synchronize() + @_mxfp8_align_test + def test_megamoe_mxfp8_cuda_graph_matches_eager(self): + """Unfused Sequential forward/backward graph replay matches eager execution.""" + self._run_megamoe_mxfp8_cuda_graph_matches_eager() - out = {} + def _run_megamoe_mxfp8_cuda_graph_matches_eager(self): + recipe = MXFP8BlockScaling() + graph_model, graph_fc1, graph_fc2, _ = self._make_megamoe_model( + recipe=recipe, + ) + eager_model, eager_fc1, eager_fc2, _ = self._make_megamoe_model( + recipe=recipe, + ) + eager_model.load_state_dict(graph_model.state_dict()) - def step(): - out["recv_mx"], out["rw"], _tc = ep_dispatch( - buf, tokens, topk_idx, w, recv_tokens=recv_buf, recv_topk_weights=rbuf_w - ) + topk_idx, tokens, topk_weights = _make_moe_inputs( + self.cfg.rank, + self.cfg.ep_size, + self.cfg.device, + ) - graph = self._capture(step) - buf.tokens_per_expert.zero_() - buf.total_recv_tokens.zero_() - graph.replay() - torch.cuda.synchronize() + static_tokens = tokens.requires_grad_(True) + static_topk_idx = topk_idx + static_topk_weights = topk_weights.requires_grad_(True) + static_dy = torch.randn_like(static_tokens) + graphed_model = te.make_graphed_callables( + graph_model, + (static_tokens, static_topk_idx, static_topk_weights, static_topk_idx), + num_warmup_iters=3, + enabled=True, + recipe=recipe, + ) - # The returned GroupedTensor views the caller buffer's data then scale regions, and the - # replayed fused scan repopulates the per-expert counts to match the AllGather path. - recv_mx = out["recv_mx"] - self.assertEqual(recv_mx.rowwise_data.data_ptr(), recv_buf.data_ptr()) - self.assertEqual(recv_mx.scale_inv.data_ptr(), recv_buf.data_ptr() + rc * HIDDEN_DIM) - torch.testing.assert_close(buf.tokens_per_expert, ref_tokens_per_expert, atol=0, rtol=0) + def reset_graphed_model(): + # Release captured NCCL work before the process group is destroyed. + graphed_model.reset() + torch.cuda.synchronize() - # Replayed payload correctness: received tokens/scales, weights, and total count must - # come from the replay's own dispatch, not a stale copy from the captured step. - self._assert_mxfp8_matches_bf16(recv_mx, tokens, topk_idx, w, buf.tokens_per_expert) - ref_buf = self._make_buffer(alignment=256) - _ref_recv, ref_rw, _ref_tc = ep_dispatch(ref_buf, tokens, topk_idx, w) - torch.cuda.synchronize() - cum = [0] + buf.tokens_per_expert.cumsum(0).tolist() - for lo, hi in zip(cum[:-1], cum[1:]): - torch.testing.assert_close( - out["rw"][lo:hi].sort().values, ref_rw[lo:hi].sort().values, atol=0, rtol=0 - ) - self.assertEqual(int(buf.total_recv_tokens.item()), int(ref_buf.total_recv_tokens.item())) + self.addCleanup(reset_graphed_model) - # PP-1F1B handle isolation + # Replace the capture-time contents while retaining captured addresses. + with torch.no_grad(): + static_tokens.copy_(torch.randn_like(static_tokens)) + static_topk_weights.copy_(torch.rand_like(static_topk_weights)) + static_dy.copy_(torch.randn_like(static_dy)) - @_zero_copy_test_include - def test_pp_1f1b_two_handles(self): - """PP-1F1B interleave (F0 F1 B0 F2 B1 B2) over 3 per-microbatch buffers, - run eagerly and replayed from a CUDA graph capturing the full fwd+bwd - schedule (prepare included; routing is fixed so replay reproduces it).""" - for capture in (False, True): - with self.subTest(capture=capture): - self._run_1f1b(capture) + for parameter in graph_model.parameters(): + parameter.grad = torch.zeros_like(parameter) + if static_tokens.grad is not None: + static_tokens.grad.zero_() + if static_topk_weights.grad is not None: + static_topk_weights.grad.zero_() + with te.autocast(enabled=True, recipe=recipe): + graph_out = graphed_model( + static_tokens, + static_topk_idx, + static_topk_weights, + static_topk_idx, + ) + graph_out_snapshot = graph_out.detach().clone() + graph_out.backward(static_dy) + torch.cuda.synchronize() + graph_grad_results = ( + static_tokens.grad.detach().clone(), + static_topk_weights.grad.detach().clone(), + graph_fc1.weight.grad.detach().clone(), + graph_fc2.weight.grad.detach().clone(), + ) - def _run_1f1b(self, capture): - T, H = TOKENS_PER_RANK, HIDDEN_DIM - idx, _toks, w = _make_identity_inputs(self.cfg.rank, self.cfg.ep_size) - scales = (0.13, 0.41, 0.77) - buffers, tokens, tokens_p = [], [], [] - for s in scales: - buffers.append(self._make_buffer()) - t = torch.full( - (T, H), s + self.cfg.rank * 0.01, dtype=torch.bfloat16, device=self.cfg.device + eager_tokens = static_tokens.detach().clone().requires_grad_(True) + eager_topk_weights = static_topk_weights.detach().clone().requires_grad_(True) + for parameter in eager_model.parameters(): + parameter.grad = torch.zeros_like(parameter) + with te.autocast(enabled=True, recipe=recipe): + eager_out = eager_model( + eager_tokens, + static_topk_idx, + eager_topk_weights, + static_topk_idx, ) - tokens.append(t) - tokens_p.append(t.detach().clone().requires_grad_(True)) + tolerances = {"rtol": 0.125, "atol": 0.25} + torch.testing.assert_close(graph_out_snapshot, eager_out, **tolerances) - recv = [None, None, None] - # Per-microbatch grad-staging buffers, symm-mem under zero-copy and - # pre-allocated so nothing is allocated/freed mid-interleave. - recv_w = [None, None, None] - rc = self.cfg.recv_capacity_per_rank - if ZERO_COPY: - gbuf_t = [symm_mem_alloc((rc, H), torch.bfloat16, self.ep_group) for _ in scales] - gbuf_w = [symm_mem_alloc((rc,), torch.float32, self.ep_group) for _ in scales] - # Persistent symm-mem recv buffers per microbatch: leaving recv None - # pool-allocates, which is not CUDA-graph capturable. - rbuf_t = [symm_mem_alloc((rc, H), torch.bfloat16, self.ep_group) for _ in scales] - rbuf_w = [symm_mem_alloc((rc,), torch.float32, self.ep_group) for _ in scales] - else: - gbuf_t = gbuf_w = [None, None, None] - rbuf_t = rbuf_w = [None, None, None] + eager_out.backward(static_dy) + torch.cuda.synchronize() + eager_grad_results = ( + eager_tokens.grad, + eager_topk_weights.grad, + eager_fc1.weight.grad, + eager_fc2.weight.grad, + ) - def fwd(k): - rt, rw, _ = ep_dispatch( - buffers[k], - tokens_p[k], - idx, - w, - recv_tokens=rbuf_t[k], - recv_topk_weights=rbuf_w[k], - ) - recv[k] = self._stage_grad_symm(rt, gbuf_t[k]) - recv_w[k] = self._stage_grad_symm(rw, gbuf_w[k]) + for graph_result, eager_result in zip( + graph_grad_results, + eager_grad_results, + ): + torch.testing.assert_close(graph_result, eager_result, **tolerances) - def bwd(k): - (0.5 * (recv[k].float() ** 2).sum() + 0.0 * recv_w[k].float().sum()).backward() - recv[k] = None - recv_w[k] = None + @_eager_test_include + def test_megamoe_main_grad_accumulation_bf16(self): + self._run_megamoe_vs_reference( + quantization="bf16", + accumulate_into_main_grad=True, + ) - def interleave(): - fwd(0) - fwd(1) - bwd(0) - fwd(2) - bwd(1) - bwd(2) + @_eager_test_include + @_mxfp8_align_test + def test_megamoe_main_grad_accumulation(self): + self._run_megamoe_vs_reference( + quantization="mxfp8", + accumulate_into_main_grad=True, + ) - def zero_grads(): - for tp in tokens_p: - if tp.grad is not None: - tp.grad.zero_() + @_eager_test_include + def test_megamoe_main_grad_overwrite_bf16(self): + self._run_megamoe_vs_reference( + quantization="bf16", + accumulate_into_main_grad=True, + overwrite_main_grad=True, + ) - if not capture: - interleave() - else: - # Warmup on a side stream, then capture the full schedule and replay. - # Grads stay pre-allocated (zeroed, not None) so backward accumulates - # in place during both capture and replay. - s = torch.cuda.Stream() - s.wait_stream(torch.cuda.current_stream()) - with torch.cuda.stream(s): - for _ in range(3): - zero_grads() - interleave() - torch.cuda.current_stream().wait_stream(s) - torch.cuda.synchronize() + @_eager_test_include + @_mxfp8_align_test + def test_megamoe_main_grad_overwrite(self): + self._run_megamoe_vs_reference( + quantization="mxfp8", + accumulate_into_main_grad=True, + overwrite_main_grad=True, + ) - zero_grads() - graph = torch.cuda.CUDAGraph() - with torch.cuda.graph(graph): - interleave() - zero_grads() - graph.replay() + @_eager_test_include + def test_megamoe_delayed_wgrad_bf16(self): + self._run_megamoe_vs_reference( + quantization="bf16", + delay_wgrad_compute=True, + ) - torch.cuda.synchronize() - for k in range(3): - torch.testing.assert_close( - tokens_p[k].grad.float(), - tokens[k].float() * float(TOP_K), - atol=5e-2, - rtol=5e-2, - ) + @_eager_test_include + @_mxfp8_align_test + def test_megamoe_delayed_wgrad(self): + self._run_megamoe_vs_reference( + quantization="mxfp8", + delay_wgrad_compute=True, + ) - @_zero_copy_test_include @_eager_test_include - def test_combine_autograd(self): - """ep_combine fwd+bwd; bwd grad target is the EpBuffer symm buffer (zc) or in-flight.""" - buf = self._make_buffer() - topk_idx, tokens, w = _make_identity_inputs(self.cfg.rank, self.cfg.ep_size) - tokens_p = tokens.detach().clone().requires_grad_(True) - recv_t, recv_w, _ = ep_dispatch(buf, tokens_p, topk_idx, w) - recv_t = self._stage_grad_symm(recv_t) - recv_w = self._stage_grad_symm(recv_w) - expert_out = self._expert_out(self._weighted(recv_t, recv_w)) - out = ep_combine(buf, expert_out) - (0.5 * (out.float() ** 2).sum()).backward() - torch.cuda.synchronize() - torch.testing.assert_close(out.float(), tokens.float(), atol=5e-2, rtol=5e-2) - torch.testing.assert_close(tokens_p.grad.float(), tokens.float(), atol=5e-2, rtol=5e-2) + def test_megamoe_delayed_main_grad_bf16(self): + self._run_megamoe_vs_reference( + quantization="bf16", + accumulate_into_main_grad=True, + delay_wgrad_compute=True, + ) + @_eager_test_include + @_mxfp8_align_test + def test_megamoe_delayed_main_grad(self): + self._run_megamoe_vs_reference( + quantization="mxfp8", + accumulate_into_main_grad=True, + delay_wgrad_compute=True, + ) -class TestMoeEpSequential(_EpTestCase): - """Integration tests for Dispatch -> expert MLP -> Combine sequences.""" + def _run_megamoe_vs_reference( + self, + *, + quantization, + accumulate_into_main_grad=False, + overwrite_main_grad=False, + delay_wgrad_compute=False, + ): + """Compare the five-op MoE sequence with the PyTorch EP reference. - @staticmethod - def _reference_weights(op): - """Pack GroupedLinear weights into MoeEpReference ``(E, in, out)`` layout.""" - weight = op.weight - num_groups = op.num_groups - out_features = op.out_features - in_features = op.in_features - data = weight.rowwise_data.view( - num_groups, - out_features, - in_features, - ).permute(0, 2, 1) - if weight.quantizer is None: - return data.detach() - scale = ( - weight.scale_inv.view( - num_groups, - out_features, - in_features // 32, - ) - .view(torch.float8_e8m0fnu) - .permute(0, 2, 1) - ) - return BlockScaledTensor( - data=data.view(torch.float8_e4m3fn).detach(), - scale=scale.detach(), - format="mxfp8", - logical_shape=tuple(data.shape), - axis=1, + The fuser selects MegaMoE when its runtime gates pass. Otherwise this + exercises the same sequence as separate NCCL EP and grouped-MLP ops. + """ + recipe = MXFP8BlockScaling() if quantization == "mxfp8" else None + model, fc1, fc2, _ = self._make_megamoe_model( + recipe=recipe, + accumulate_into_main_grad=accumulate_into_main_grad, + delay_wgrad_compute=delay_wgrad_compute, + glu_interleave_size=32 if quantization == "mxfp8" else None, ) + generator = torch.Generator(device=self.cfg.device) + generator.manual_seed(3100 + self.cfg.rank) + with torch.no_grad(): + for op in (fc1, fc2): + weights = op.weight.quantized_tensors + if weights is None: + weights = op.weight.split_into_quantized_tensors() + for expert in range(NUM_LOCAL_EXPERTS): + weight = ( + torch.randn( + weights[expert].shape, + generator=generator, + dtype=torch.float32, + device=self.cfg.device, + ) + * 0.1 + ).to(torch.bfloat16) + weights[expert].copy_(weight) + if quantization == "mxfp8": + self.assertIsInstance(weights[expert], MXFP8Tensor) - def test_runtime_buffer_config_mismatch(self): - config = self._make_config() - buffer = self._make_buffer_from_config(config) - topk_idx, tokens, topk_weights = _make_identity_inputs( + topk_idx, tokens, topk_weights = _make_moe_inputs( self.cfg.rank, self.cfg.ep_size, + self.cfg.device, ) - dispatch = te_ops.MoeDispatch(config, buffer) - replacements = { - "top_k": config.top_k + 1, - "hidden_dim": config.hidden_dim + 1, - "num_local_experts": config.num_local_experts + 1, - "max_tokens_per_rank": config.max_tokens_per_rank + 1, - "recv_capacity_per_rank": config.recv_capacity_per_rank + 1, - "alignment": 1, - "payload_dtype": torch.float16, - "zero_copy": not config.zero_copy, - } - for field_name, wrong_value in replacements.items(): - with self.subTest(field_name=field_name): - original = getattr(buffer, field_name) - setattr(buffer, field_name, wrong_value) - try: - with self.assertRaisesRegex(ValueError, field_name): - dispatch(tokens, topk_idx, topk_weights) - finally: - setattr(buffer, field_name, original) + seq_tokens = tokens.requires_grad_(True) + seq_topk_weights = topk_weights.requires_grad_(True) + main_grad_sentinel = 0.5 + if accumulate_into_main_grad: + for op in (fc1, fc2): + op.weight.main_grad = torch.full( + op.weight.size(), + main_grad_sentinel, + dtype=torch.float32, + device=op.weight.device, + ) + op.weight.overwrite_main_grad = overwrite_main_grad + op.weight.zero_out_wgrad = False + op.weight.grad_added_to_main_grad = False + autocast_ctx = ( + te.autocast(enabled=True, recipe=recipe) if recipe is not None else nullcontext() + ) + with autocast_ctx: + seq_out = model( + seq_tokens, + topk_idx, + seq_topk_weights, + topk_idx, + ) - wrong_config = replace(config, drop_on_overflow=not config.drop_on_overflow) - with self.assertRaisesRegex(ValueError, "drop_on_overflow"): - te_ops.MoeDispatch(wrong_config, buffer)(tokens, topk_idx, topk_weights) - with self.assertRaisesRegex(ValueError, "ep_group"): - te_ops.MoeDispatch(replace(config, ep_group=None), buffer)( - tokens, topk_idx, topk_weights + self.assertEqual(seq_out.dtype, torch.bfloat16) + + fc1_weight = self._reference_weights(fc1) + fc2_weight = self._reference_weights(fc2) + emulate_mxfp8 = quantization == "mxfp8" + reference = MoeEpReference( + num_experts=self.cfg.num_experts, + hidden_size=HIDDEN_DIM, + intermediate_size=256, + top_k=TOP_K, + ep_group=self.ep_group, + max_tokens_per_rank=TOKENS_PER_RANK, + output_format=MoeFormat.BF16, + combine_format=MoeFormat.BF16, + apply_topk_in_fc1=True, + generate_c=True, + intermediate_format=MoeFormat.MXFP8 if emulate_mxfp8 else None, + backward_operand_format=MoeFormat.MXFP8 if emulate_mxfp8 else None, + backward_wgrad_mode="operands", + token_padding_size=256, + weight_interleave_size=32 if quantization == "mxfp8" else None, + ) + if emulate_mxfp8: + reference_activation = quantize_blockwise( + tokens.detach(), + MoeFormat.MXFP8, + axis=1, ) - expert_out = torch.empty( - self.cfg.recv_capacity_per_rank, - HIDDEN_DIM, - dtype=torch.bfloat16, - device=self.cfg.device, + else: + reference_activation = tokens.detach() + if emulate_mxfp8 and not isinstance(fc1_weight, BlockScaledTensor): + fc1_weight = quantize_blockwise(fc1_weight, MoeFormat.MXFP8, axis=1) + if emulate_mxfp8 and not isinstance(fc2_weight, BlockScaledTensor): + fc2_weight = quantize_blockwise(fc2_weight, MoeFormat.MXFP8, axis=1) + reference_outputs = reference( + reference_activation, + fc1_weight, + fc2_weight, + topk_idx, + topk_weights.detach(), ) - with self.assertRaisesRegex(ValueError, "buffer config"): - original = buffer.hidden_dim - buffer.hidden_dim += 1 - try: - te_ops.MoeCombine(config, buffer)(expert_out, topk_idx) - finally: - buffer.hidden_dim = original + ref_out, fc1_c, route_metadata, wgrad_forward_stash = reference_outputs - # The communication recipes are backend configuration, so a config that - # disagrees with the buffer about the transport format is rejected. - mxfp8_config = replace( - config, - dispatch_fwd_quant_recipe=MXFP8BlockScaling(), - combine_bwd_quant_recipe=MXFP8BlockScaling(), + tolerances = {"rtol": 0.125, "atol": 0.25} + torch.testing.assert_close(seq_out, ref_out, **tolerances) + + dy = ( + torch.randn( + seq_out.shape, + generator=generator, + dtype=torch.float32, + device=self.cfg.device, + ) + * 0.1 + ).to(torch.bfloat16) + seq_out.backward(dy) + if delay_wgrad_compute: + fc1.backward_dw() + fc2.backward_dw() + grad_tokens, grad_topk_weights, wgrad_operands = reference.backward( + dy, + fc1_weight, + fc2_weight, + topk_idx, + topk_weights.detach(), + fc1_c, + route_metadata, + wgrad_forward_stash=wgrad_forward_stash, ) - mxfp8_buffer = self._make_buffer_from_config(mxfp8_config) - with self.assertRaisesRegex(ValueError, "dispatch_fwd_quant_recipe"): - te_ops.MoeDispatch(config, mxfp8_buffer)(tokens, topk_idx, topk_weights) - with self.assertRaisesRegex(ValueError, "combine_bwd_quant_recipe"): - te_ops.MoeCombine(config, mxfp8_buffer)(expert_out, topk_idx) + grad_fc1, grad_fc2 = wgrad_operands.dense_wgrads() + reference_wgrads = (grad_fc1, grad_fc2) - def _run_dispatch_combine_identity(self, *, mxfp8): - """Route, apply top-k weights, and combine back to local token order.""" - recipe = MXFP8BlockScaling() if mxfp8 else None - if mxfp8: - self._require_mxfp8_shapes() - config = self._make_config( - alignment=256 if mxfp8 else 0, - dispatch_fwd_quant_recipe=recipe, - combine_bwd_quant_recipe=recipe, + torch.cuda.synchronize() + torch.testing.assert_close( + seq_tokens.grad, + grad_tokens.to(dtype=seq_tokens.dtype), + **tolerances, ) - buffer = self._make_buffer_from_config(config) + torch.testing.assert_close(seq_topk_weights.grad, grad_topk_weights.float(), **tolerances) + for op, ref_grad in zip((fc1, fc2), reference_wgrads): + expected_grad = ref_grad.transpose(1, 2) + if accumulate_into_main_grad: + if not overwrite_main_grad: + expected_grad = expected_grad + main_grad_sentinel + torch.testing.assert_close( + op.weight.main_grad, + expected_grad.to(dtype=op.weight.main_grad.dtype), + **tolerances, + ) + self.assertTrue(op.weight.grad_added_to_main_grad) + self.assertIsNone(op.weight.grad) + continue + seq_grad = op.weight.grad + self.assertEqual(seq_grad.dtype, torch.bfloat16) + self.assertEqual( + tuple(seq_grad.shape), + (NUM_LOCAL_EXPERTS, op.out_features, op.in_features), + ) + self.assertTrue(seq_grad.is_contiguous()) + torch.testing.assert_close( + seq_grad, + expected_grad.to(dtype=seq_grad.dtype), + **tolerances, + ) + + def _moe_ops( + self, + config, + buffer, + glu_interleave_size=32, + accumulate_into_main_grad=False, + *, + ffn=HIDDEN_DIM, + activation=None, + fc_kwargs=({}, {}), + **linear_kwargs, + ): + """MoeDispatch, GroupedLinear, ``activation`` (default ScaledSwiGLU), GroupedLinear and + MoeCombine over ``buffer``, with the routing channels connected and fixed weights (BF16 + unless ``linear_kwargs`` change the GroupedLinear settings; ``fc_kwargs`` adds settings + of the first and of the second GroupedLinear).""" + device = self.cfg.device + gen = torch.Generator(device=device).manual_seed(5) + linear_kwargs = { + "bias": False, + "dtype": torch.bfloat16, + "single_grouped_weight": True, + "split_alignment": OVERLAP_ALIGNMENT, + "accumulate_into_main_grad": accumulate_into_main_grad, + **linear_kwargs, + } dispatch = te_ops.MoeDispatch(config, buffer) - combine = te_ops.MoeCombine(config, buffer) - topk_idx, tokens, topk_weights = _make_identity_inputs( - self.cfg.rank, - self.cfg.ep_size, - ) - recv_tokens, tokens_per_expert, recv_weights = dispatch( - tokens, - topk_idx, - topk_weights, + fc1 = te_ops.GroupedLinear( + NUM_LOCAL_EXPERTS, HIDDEN_DIM, 2 * ffn, device=device, **linear_kwargs, **fc_kwargs[0] ) - if mxfp8: - # Convert to BF16 since combine only supports BF16 in NCCL EP - # for now. dequantizing to mxfp8 below changes its overall shape - # to sum(tokens_per_expert). - recv_tokens = _degroup_mxfp8(recv_tokens) - recv_weights = recv_weights[: recv_tokens.shape[0]] - weighted_expert_output = (recv_tokens.float() * recv_weights.float().unsqueeze(-1)).to( - torch.bfloat16 + fc2 = te_ops.GroupedLinear( + NUM_LOCAL_EXPERTS, ffn, HIDDEN_DIM, device=device, **linear_kwargs, **fc_kwargs[1] ) - output = combine(weighted_expert_output, topk_idx) - torch.cuda.synchronize() - torch.testing.assert_close(output, tokens, atol=5e-2, rtol=5e-2) - self.assertEqual(tokens_per_expert.data_ptr(), buffer.tokens_per_expert.data_ptr()) + act = activation or te_ops.ScaledSwiGLU(glu_interleave_size=glu_interleave_size) + combine = te_ops.MoeCombine(config, buffer) + with torch.no_grad(): + for fc in (fc1, fc2): + for w in fc.parameters(): + w.copy_((torch.rand(w.shape, device=device, generator=gen) - 0.5) * 0.1) + dispatch.set_extra_output_channel(0, "tokens_per_expert", output_to_caller=False) + dispatch.set_extra_output_channel(1, "routing_weights", output_to_caller=False) + fc1.set_extra_input_channel(0, "tokens_per_expert") + act.set_extra_input_channel(0, "routing_weights") + fc2.set_extra_input_channel(0, "tokens_per_expert") + return dispatch, fc1, act, fc2, combine + + @_eager_test_include + @_overflow_test_include + @_mxfp8_align_test + @_overlap_test + def test_moe_overlap_op(self): + """The fused MoE op matches the same ops run unfused: output and every + gradient, also when tokens overflow the capacity and are dropped. Skipped where the + overlapped GEMMs cannot run.""" + self._check_moe_overlap_op(None) @_eager_test_include + @_overflow_test_include @_mxfp8_align_test @_overlap_test - def test_unfused_ops_on_overlap_group(self): - """On an overlap-pass group, MoeDispatch and MoeCombine run unfused and form an identity, - forward and backward.""" + def test_moe_overlap_op_mxfp8(self): + """Under MXFP8 with MXFP8 EP transport the fused op matches the unfused ops, with weight + scales that differ across blocks in both directions. The fused op dispatches x and dY in + place from the EP dispatch window. An unset config transport runs MXFP8.""" + self._require_mxfp8_shapes() + recipe = MXFP8BlockScaling() + with mock.patch.object( + tex, "ep_dispatch_gemm_fwd", wraps=tex.ep_dispatch_gemm_fwd + ) as fwd, mock.patch.object( + tex, "ep_combine_gemm_bwd", wraps=tex.ep_combine_gemm_bwd + ) as bwd: + self._check_moe_overlap_op(recipe, recipe) + for call in fwd.call_args_list + bwd.call_args_list: + self.assertEqual(call.kwargs["symm_input"], tex.ep_zero_copy_supported()) + # MXFP8 FusedMoE quantizes the EP transport itself, so an unset config transport fuses. config = self._overlap_config() - buffer = self._make_buffer_from_config(config) - dispatch = te_ops.MoeDispatch(config, buffer) - combine = te_ops.MoeCombine(config, buffer) - topk_idx, tokens, topk_weights = _make_identity_inputs(self.cfg.rank, self.cfg.ep_size) - x = tokens.clone().requires_grad_(True) - w = topk_weights.clone().requires_grad_(True) - recv_tokens, _tokens_per_expert, recv_weights = dispatch(x, topk_idx, w) - output = combine(recv_tokens * recv_weights.unsqueeze(-1).to(torch.bfloat16), topk_idx) - gen = torch.Generator(device=self.cfg.device).manual_seed(8) - grad_out = torch.randn(tokens.shape, device=self.cfg.device, generator=gen) - output.backward(grad_out.to(torch.bfloat16)) - torch.cuda.synchronize() - torch.testing.assert_close(output, tokens, atol=5e-2, rtol=5e-2) - torch.testing.assert_close(x.grad.float(), grad_out, atol=5e-2, rtol=5e-2) - grad_w_ref = (tokens.float() * grad_out).sum(-1, keepdim=True).expand_as(w) - torch.testing.assert_close(w.grad.float(), grad_w_ref, atol=5e-1, rtol=5e-2) + model = te_ops.Sequential(*self._moe_ops(config, self._make_buffer_from_config(config))) + topk_idx, tokens, w = _make_identity_inputs(self.cfg.rank, self.cfg.ep_size) + with te.autocast(recipe=recipe): + model(tokens, topk_idx, w, topk_idx) + self.assertTrue(self._moe_overlap_selected(model)) @_eager_test_include - def test_dispatch_combine_identity_bf16(self): - """MoeDispatch and MoeCombine basic ops form an identity in BF16.""" - self._run_dispatch_combine_identity(mxfp8=False) + @_overflow_test_include + @_mxfp8_align_test + @_overlap_test + def test_moe_overlap_op_variants(self): + """The fused op matches the unfused ops, in BF16 and, where the overlap tests run MXFP8, in + MXFP8, also: without input and routing-weight gradients (no dispatch backward), with + MXFP8 weight parameters, with accumulate_into_main_grad, with an FFN size other than the + hidden size, and with FP32 weight parameters cast by + ``Module.to(torch.bfloat16)``.""" + # (recipe, _check_moe_overlap_op settings) + cases = [ + (None, {"input_grad": False}), + # ffn != hidden, so a transposed weight layout cannot pass. + (None, {"ffn": HIDDEN_DIM // 2}), + (None, {"main_grad": True}), + (None, {"params_to_bf16": True}), + (None, {"params_to_bf16": True, "main_grad": True}), + (None, {"frozen": (1,)}), + (None, {"frozen": (3,)}), + (None, {"frozen": (1, 3), "main_grad": True}), + ] + if _mxfp8_overlap(): + recipe = MXFP8BlockScaling() + cases += [ + (recipe, {"input_grad": False}), + (recipe, {"params_to_bf16": True}), + (recipe, {"quantized_weights": True}), + (recipe, {"frozen": (1,)}), + (recipe, {"frozen": (3,)}), + (recipe, {"frozen": (1, 3)}), + ] + cases += [(recipe, {"quantized_weights": q, "main_grad": True}) for q in (False, True)] + for recipe, settings in cases: + with self.subTest(recipe=recipe, **settings): + self._check_moe_overlap_op(recipe, recipe, **settings) + + def _check_moe_overlap_op( + self, recipe, transport=None, quantized_weights=False, main_grad=False, input_grad=True, + params_to_bf16=False, ffn=HIDDEN_DIM, frozen=(), + ): # fmt: skip + from transformer_engine.pytorch.ops.fused import moe_overlap + + device = self.cfg.device + config = self._overlap_config(transport) + # Where FusedMoE cannot run, the overlap raises, so there is nothing to compare. + if not moe_overlap.FusedMoE.is_supported() or ( + recipe is not None + and not (moe_overlap.GroupedMLP_CuTeGEMMGLU.is_supported() and transport is not None) + ): + self.skipTest("FusedMoE is not supported here") + # SM 10.7 runs the MXFP8 weight gradients into main_grad only above 256 receive rows. + if ( + main_grad + and len(frozen) < 2 + and recipe is not None + and torch.cuda.get_device_capability() == (10, 7) + and config.recv_capacity_per_rank == 256 + ): + self.skipTest( + "SM 10.7 MXFP8 main_grad weight gradients need more than 256 receive rows" + ) + with te.quantized_model_init(enabled=quantized_weights, recipe=recipe): + buffer = self._make_buffer_from_config(config) + ops = self._moe_ops( + config, + buffer, + accumulate_into_main_grad=main_grad, + ffn=ffn, + dtype=torch.float32 if params_to_bf16 else torch.bfloat16, + ) + gen = torch.Generator(device=device).manual_seed(6) + if recipe is not None: + # Power-of-two factors per row and column give every scale block its own exponent. + with torch.no_grad(): + for fc in (ops[1], ops[3]): + for w in fc.parameters(): + rows = torch.randint( + -3, 4, (*w.shape[:-1], 1), device=device, generator=gen + ) + cols = torch.randint(-3, 4, w.shape[-1:], device=device, generator=gen) + values = torch.rand(w.shape, device=device, generator=gen) - 0.5 + w.copy_(values * 0.1 * torch.exp2((rows + cols).float())) + if params_to_bf16: + for op in ops: + op.to(torch.bfloat16) + # The weights of the GroupedLinear ops at these positions (1: FC1, 3: FC2) are frozen. + for idx in frozen: + ops[idx].weight.requires_grad_(False) + topk_idx, tokens, w = _make_identity_inputs(self.cfg.rank, self.cfg.ep_size) + grad_out = torch.randn(tokens.shape, device=device, generator=gen).to(torch.bfloat16) + + def run(fused): + if not fused and params_to_bf16: + # The BF16 grouped MLP fusion reads the weight data as stored, so this reference + # runs the GroupedLinear ops, which cast it, and not FusedMoE. + ctx = contextlib.ExitStack() + ctx.enter_context( + mock.patch.object( + moe_overlap.GroupedMLP_CuTeGEMMGLUBf16, "is_supported", return_value=False + ) + ) + ctx.enter_context(self._moe_fusion(False)) + elif not fused: + ctx = self._moe_fusion(False) + elif input_grad: + ctx = contextlib.nullcontext() + else: + ctx = mock.patch.object( + moe_overlap.tex, "ep_dispatch_gemm_bwd", side_effect=AssertionError("called") + ) + # Each run publishes its own counts: a stale value would show. + buffer.tokens_per_expert.fill_(-1) + buffer.total_recv_tokens.fill_(-1) + if fused: + # The fused op uses its own counts and recv total, not the reference's. + buffer.tokens_per_expert_i32.fill_(-1) + buffer.total_recv_tokens_i32.fill_(-1) + # Paged stashing pages the tensors that carry a token count. + stashable = [] + num_tokens = [] - @_eager_test_include - @_mxfp8_align_test - def test_dispatch_combine_identity_mxfp8(self): - """MoeDispatch and MoeCombine basic ops form an identity with MXFP8 transport.""" - self._run_dispatch_combine_identity(mxfp8=True) + def pack(tensor): + if hasattr(tensor, "grouped_tensor_num_tokens"): + stashable.append((tensor.dtype, tensor.shape, tensor.nbytes)) + n = tensor.grouped_tensor_num_tokens + num_tokens.append(n.clone() if torch.is_tensor(n) else n) + return tensor - def _make_megamoe_model( - self, - *, - recipe, - accumulate_into_main_grad=False, - delay_wgrad_compute=False, - glu_interleave_size=None, - ): - """Build the exact five-op sequence recognized by MegaMoE fusion.""" - config = self._make_config( - alignment=256 if recipe is not None else 0, - dispatch_fwd_quant_recipe=recipe, - combine_bwd_quant_recipe=recipe, - ) - buffer = self._make_buffer_from_config(config) - dispatch = te_ops.MoeDispatch(config, buffer) - init_ctx = ( - te.quantized_model_init(enabled=True, recipe=recipe) - if recipe is not None - else nullcontext() - ) - with init_ctx: - fc1 = te_ops.GroupedLinear( - NUM_LOCAL_EXPERTS, - HIDDEN_DIM, - 2 * 256, - bias=False, - device=self.cfg.device, - dtype=torch.bfloat16, - single_grouped_weight=True, - accumulate_into_main_grad=accumulate_into_main_grad, - delay_wgrad_compute=delay_wgrad_compute, - ) - activation = te_ops.ScaledSwiGLU( - glu_interleave_size=glu_interleave_size, - ) - fc2 = te_ops.GroupedLinear( - NUM_LOCAL_EXPERTS, - 256, - HIDDEN_DIM, - bias=False, - device=self.cfg.device, - dtype=torch.bfloat16, - single_grouped_weight=True, - accumulate_into_main_grad=accumulate_into_main_grad, - delay_wgrad_compute=delay_wgrad_compute, - ) - combine = te_ops.MoeCombine(config, buffer) - dispatch.set_extra_output_channel(0, "tokens_per_expert", output_to_caller=False) - dispatch.set_extra_output_channel(1, "routing_weights", output_to_caller=False) - fc1.set_extra_input_channel(0, "tokens_per_expert") - activation.set_extra_input_channel(0, "routing_weights") - fc2.set_extra_input_channel(0, "tokens_per_expert") - model = te_ops.Sequential(dispatch, fc1, activation, fc2, combine) - return model, fc1, fc2, buffer + with ctx, te.autocast( + enabled=recipe is not None, recipe=recipe + ), torch.autograd.graph.saved_tensors_hooks(pack, lambda tensor: tensor): + model = te_ops.Sequential(*ops) + x = tokens.clone().requires_grad_(input_grad) + topk_w = w.clone().requires_grad_(input_grad) + for p in model.parameters(): + p.grad = None + if main_grad: + p.main_grad = torch.full(p.shape, 0.5, dtype=torch.float32, device=device) + p.grad_added_to_main_grad = False + y = model(x, topk_idx, topk_w, topk_idx) + y.backward(grad_out) + torch.cuda.synchronize() + fused_ops = self._moe_overlap_selected(model) + trained = [p for p in model.parameters() if p.requires_grad] + if main_grad: + self.assertTrue(all(p.grad_added_to_main_grad for p in trained)) + grads = [(p.main_grad if main_grad else p.grad).clone() for p in trained] + counts = [int(n) for n in num_tokens] + published = (buffer.tokens_per_expert.clone(), int(buffer.total_recv_tokens.item())) + return ( + y.detach(), x.grad, topk_w.grad, grads, bool(fused_ops), stashable, counts, + published, + ) # fmt: skip - @_eager_test_include - def test_megamoe_bf16_numerics(self): - self._run_megamoe_vs_reference(quantization="bf16") + ref = run(False) + out = run(True) + self.assertFalse(ref[4]) + self.assertTrue(out[4], "fusion selection") + # The launcher requires this line from every rank of an overlap pass. + print(f"OVERLAP_EXECUTED rank={self.cfg.rank}", flush=True) + reason = _moe_overlap_unsupported_reason( + config, ffn, params_dtype=torch.bfloat16, + glu_interleave_size=32, single_grouped_weight=True, recipe=recipe, + primary_weights_in_fp8=quantized_weights, + ) # fmt: skip + self.assertIsNone(reason, "the fuser selects FusedMoE but the support check rejects it") + # Row tensors saved: recv tokens (and their scales), the FC1 output and the routing + # weights, plus the SwiGLU output in BF16. A frozen weight leaves out the input of its + # weight gradient: the recv tokens and scales for FC1, the SwiGLU output (BF16) for FC2. + fc1_inputs, fc2_inputs = (2, 0) if recipe is not None else (1, 1) + stashed = 4 - (fc1_inputs if 1 in frozen else 0) - (fc2_inputs if 3 in frozen else 0) + self.assertEqual(len(out[5]), stashed, "the fused op saves the stashable tensors") + # Their token count is the number of received rows kept. + kept = int(buffer.tokens_per_expert_i32.sum()) + self.assertEqual(out[6], [kept] * stashed, "stashed token counts") + # The fused op publishes the buffer counters as the unfused ops do: the kept tokens per + # expert and the recv total before any drop, which exceeds the kept total on overflow. + self.assertTrue(torch.equal(out[7][0], ref[7][0]), "published per-expert counts") + self.assertEqual(out[7][1], ref[7][1], "published recv total") + self.assertEqual(int(out[7][0].sum()), kept, "published per-expert counts sum") + if OVERFLOW: + self.assertGreater(out[7][1], config.recv_capacity_per_rank, "overflow recv total") + self.assertGreater(out[7][1], kept, "recv total counts the dropped tokens") + else: + self.assertGreaterEqual(out[7][1], kept) + if recipe is not None: + # The FC2 dgrad recomputes the SwiGLU output, so no [rows, ffn] tensor is saved: + # the recv tokens and scales, the FC1 output and the recv routing weights. + rows = next(shape[0] for dtype, shape, _ in out[5] if dtype == torch.float32) + saved = sum(nbytes for _, _, nbytes in out[5]) + ffn = ops[3].in_features + recv_bytes = 0 if 1 in frozen else HIDDEN_DIM + HIDDEN_DIM // 32 + self.assertEqual(saved, rows * (recv_bytes + 2 * ffn * 2 + 4), "saved bytes") + # Where the unfused ops compute the SwiGLU output in their own kernel, single elements may + # round to another value, so those results are compared in norm. The unfused MXFP8 ops also + # round the FC2 dgrad and the SwiGLU backward output to BF16 before quantizing them, so + # outputs and weight gradients may differ by up to the E4M3 epsilon. + norm_rtol = 2e-2 if recipe is None else 1 / 32 + unfused_reference = UNFUSED_BF16_MLP_REFERENCE if recipe is None else UNFUSED_MLP_REFERENCE + outputs_in_norm = unfused_reference or params_to_bf16 + outputs_rtol = 1 / 16 if recipe is not None and unfused_reference else norm_rtol + if not input_grad: + self.assertTrue(all(g is None for g in out[1:3] + ref[1:3])) + for got, want in zip(out[: 3 if input_grad else 1], ref[:3]): + if outputs_in_norm: + _assert_close_in_norm(got, want, rtol=outputs_rtol) + else: + torch.testing.assert_close(got, want, rtol=2e-2, atol=2e-2) + for g, g_ref in zip(out[3], ref[3]): + if recipe is None and not (UNFUSED_BF16_MLP_REFERENCE or params_to_bf16): + torch.testing.assert_close(g, g_ref, rtol=2e-2, atol=2e-2) + else: + _assert_close_in_norm(g, g_ref, rtol=outputs_rtol) @_eager_test_include @_mxfp8_align_test - def test_megamoe_mxfp8_numerics(self): - self._run_megamoe_vs_reference(quantization="mxfp8") + @_overlap_test + def test_moe_overlap_cpu_offload(self): + """Under CPU offload the tensors the fused op saves come back bitwise, and its output and + gradients match those without offload.""" + from transformer_engine.pytorch import cpu_offload - @_mxfp8_align_test - def test_megamoe_mxfp8_cuda_graph_matches_eager(self): - """Unfused Sequential forward/backward graph replay matches eager execution.""" - self._run_megamoe_mxfp8_cuda_graph_matches_eager() + self._require_moe_overlap() + tokens, topk_idx, w, grad_out = self._moe_calls(1)[0] + for recipe in [None] + ([MXFP8BlockScaling()] if _mxfp8_overlap() else []): + config = self._overlap_config(recipe) + ops = self._moe_ops(config, self._make_buffer_from_config(config)) + results = [] + for offload in (False, True): + saved = [] + for p in ops[1].parameters(): + p.grad = None + for p in ops[3].parameters(): + p.grad = None + with te.autocast(enabled=recipe is not None, recipe=recipe): + model = te_ops.Sequential(*ops) + x = tokens.clone().requires_grad_(True) + topk_w = w.clone().requires_grad_(True) + if offload: + ctx, sync, controller = cpu_offload.get_cpu_offload_context( + enabled=True, model_layers=1, manual_synchronization=True + ) + sync_state = ctx.offload_synchronizer + push, pop = sync_state.push_tensor, sync_state.pop_tensor - def _run_megamoe_mxfp8_cuda_graph_matches_eager(self): - recipe = MXFP8BlockScaling() - graph_model, graph_fc1, graph_fc2, _ = self._make_megamoe_model( - recipe=recipe, - ) - eager_model, eager_fc1, eager_fc2, _ = self._make_megamoe_model( - recipe=recipe, - ) - eager_model.load_state_dict(graph_model.state_dict()) + def push_tensor(tensor, push=push): + saved.append([tensor.detach().reshape(-1).view(torch.uint8).cpu()]) + return len(saved) - 1, push(tensor) - topk_idx, tokens, topk_weights = _make_moe_inputs( - self.cfg.rank, - self.cfg.ep_size, - self.cfg.device, - ) + def pop_tensor(packed, pop=pop): + tensor = pop(packed[1]) + saved[packed[0]].append(tensor.detach().reshape(-1).view(torch.uint8)) + return tensor - static_tokens = tokens.requires_grad_(True) - static_topk_idx = topk_idx - static_topk_weights = topk_weights.requires_grad_(True) - static_dy = torch.randn_like(static_tokens) - graphed_model = te.make_graphed_callables( - graph_model, - (static_tokens, static_topk_idx, static_topk_weights, static_topk_idx), - num_warmup_iters=3, - enabled=True, - recipe=recipe, - ) + with mock.patch.object( + sync_state, "push_tensor", push_tensor + ), mock.patch.object(sync_state, "pop_tensor", pop_tensor): + with ctx: + y = model(x, topk_idx, topk_w, topk_idx) + y = sync(y) + controller.start_offload_layer(0) + controller.release_activation_forward_gpu_memory(0) + controller.start_reload_layer(0) + else: + y = model(x, topk_idx, topk_w, topk_idx) + y.backward(grad_out) + torch.cuda.synchronize() + self.assertTrue(self._moe_overlap_selected(model)) + self.assertEqual(bool(saved), offload, "offloaded tensors") + for before, after in saved: + self.assertTrue(torch.equal(before, after.cpu()), "a saved tensor changed") + grads = [p.grad.clone() for p in model.parameters()] + results.append([y.detach(), x.grad, topk_w.grad, *grads]) + with self.subTest(recipe=recipe): + for i, (got, want) in enumerate(zip(*results)): + if recipe is not None and i >= 3: + _assert_close_in_norm(got, want, rtol=1 / 32) + else: + torch.testing.assert_close(got, want, rtol=2e-2, atol=2e-2) - def reset_graphed_model(): - # Release captured NCCL work before the process group is destroyed. - graphed_model.reset() - torch.cuda.synchronize() + def _require_moe_overlap(self): + from transformer_engine.pytorch.ops.fused import moe_overlap - self.addCleanup(reset_graphed_model) + if not moe_overlap.FusedMoE.is_supported(): + self.skipTest( + "FusedMoE needs SM 10.0, 10.3 or 10.7, NVTE_ENABLE_CUTEDSL_BACKEND=1," + " NVTE_MOE_OVERLAP and the BF16 cuDNN grouped GEMM kernels" + ) - # Replace the capture-time contents while retaining captured addresses. - with torch.no_grad(): - static_tokens.copy_(torch.randn_like(static_tokens)) - static_topk_weights.copy_(torch.rand_like(static_topk_weights)) - static_dy.copy_(torch.randn_like(static_dy)) + @staticmethod + def _moe_fusion(fused): + """Context in which the fuser may select FusedMoE, or keeps the MoE ops unfused.""" + from transformer_engine.pytorch.ops.fused import moe_overlap + + if fused: + return contextlib.nullcontext() + return mock.patch.object(moe_overlap, "_moe_overlap_available", return_value=False) + + @staticmethod + def _moe_overlap_selected(model): + """The FusedMoE ops of the plan ``model`` ran last.""" + from transformer_engine.pytorch.ops.fused import moe_overlap - for parameter in graph_model.parameters(): - parameter.grad = torch.zeros_like(parameter) - if static_tokens.grad is not None: - static_tokens.grad.zero_() - if static_topk_weights.grad is not None: - static_topk_weights.grad.zero_() - with te.autocast(enabled=True, recipe=recipe): - graph_out = graphed_model( - static_tokens, - static_topk_idx, - static_topk_weights, - static_topk_idx, - ) - graph_out_snapshot = graph_out.detach().clone() - graph_out.backward(static_dy) - torch.cuda.synchronize() - graph_grad_results = ( - static_tokens.grad.detach().clone(), - static_topk_weights.grad.detach().clone(), - graph_fc1.weight.grad.detach().clone(), - graph_fc2.weight.grad.detach().clone(), - ) + return [ + op + for group in model._module_groups + for op, _ in getattr(group, "_forward_ops", []) + if isinstance(op, moe_overlap.FusedMoE) + ] - eager_tokens = static_tokens.detach().clone().requires_grad_(True) - eager_topk_weights = static_topk_weights.detach().clone().requires_grad_(True) - for parameter in eager_model.parameters(): - parameter.grad = torch.zeros_like(parameter) - with te.autocast(enabled=True, recipe=recipe): - eager_out = eager_model( - eager_tokens, - static_topk_idx, - eager_topk_weights, - static_topk_idx, + def _moe_calls(self, num_calls): + """(tokens, topk_idx, topk_weights, grad_output) of calls that each route differently.""" + gen = torch.Generator(device=self.cfg.device).manual_seed(8) + topk_idx, tokens, w = _make_identity_inputs(self.cfg.rank, self.cfg.ep_size) + return [ + ( + tokens.roll(i, 0), + (topk_idx + i) % self.cfg.num_experts, + w, + torch.randn(tokens.shape, device=self.cfg.device, generator=gen).to(torch.bfloat16), ) - tolerances = {"rtol": 0.125, "atol": 0.25} - torch.testing.assert_close(graph_out_snapshot, eager_out, **tolerances) + for i in range(num_calls) + ] - eager_out.backward(static_dy) - torch.cuda.synchronize() - eager_grad_results = ( - eager_tokens.grad, - eager_topk_weights.grad, - eager_fc1.weight.grad, - eager_fc2.weight.grad, - ) + @staticmethod + def _moe_call(model, tokens, topk_idx, w, grad, *, tokens_grad=True, weights_grad=True): + """Forward, then backward when ``grad`` is given: (output, tokens grad, topk_weights + grad). Parameter gradients accumulate on the parameters.""" + x = tokens.clone().requires_grad_(tokens_grad) + topk_w = w.clone().requires_grad_(weights_grad) + y = model(x, topk_idx, topk_w, topk_idx) + if grad is not None: + y.backward(grad) + return y.detach(), x.grad, topk_w.grad - for graph_result, eager_result in zip( - graph_grad_results, - eager_grad_results, - ): - torch.testing.assert_close(graph_result, eager_result, **tolerances) + @staticmethod + def _param_grads(model): + return [None if p.grad is None else p.grad.clone() for p in model.parameters()] - @_eager_test_include - def test_megamoe_main_grad_accumulation_bf16(self): - self._run_megamoe_vs_reference( - quantization="bf16", - accumulate_into_main_grad=True, - ) + def _assert_moe_close( + self, got, ref, in_norm=UNFUSED_BF16_MLP_REFERENCE, outputs_in_norm=True, rtol=2e-2 + ): + """Fused and unfused MoE results, nested in lists, agree within ``rtol``; with in_norm the + grouped weight gradients in norm, and with outputs_in_norm as well the outputs and input + gradients.""" + if isinstance(ref, (list, tuple)): + self.assertEqual(len(got), len(ref)) + for g, r in zip(got, ref): + self._assert_moe_close(g, r, in_norm, outputs_in_norm, rtol) + elif ref is None: + self.assertIsNone(got) + elif in_norm and (outputs_in_norm or ref.dim() == 3): + _assert_close_in_norm(got, ref, rtol=rtol) + else: + torch.testing.assert_close(got, ref, rtol=rtol, atol=rtol) - @_eager_test_include @_mxfp8_align_test - def test_megamoe_main_grad_accumulation(self): - self._run_megamoe_vs_reference( - quantization="mxfp8", - accumulate_into_main_grad=True, - ) - - @_eager_test_include - def test_megamoe_main_grad_overwrite_bf16(self): - self._run_megamoe_vs_reference( - quantization="bf16", - accumulate_into_main_grad=True, - overwrite_main_grad=True, + @_overlap_test + def test_moe_overlap_wgrad(self): + """With accumulate_into_main_grad, the fused op writes the weight gradients of two calls + into an FP32 or BF16 main_grad, accumulated or overwritten, as the unfused ops do.""" + self._require_moe_overlap() + config = self._overlap_config() + calls = self._moe_calls(2) + ops = self._moe_ops( + config, self._make_buffer_from_config(config), accumulate_into_main_grad=True ) + weights = (ops[1].weight, ops[3].weight) + for dtype, overwrite in itertools.product((torch.float32, torch.bfloat16), (False, True)): + results = [] + for fused in (False, True): + for p in weights: + p.grad = None + p.main_grad = torch.full(p.size(), 0.5, dtype=dtype, device=self.cfg.device) + p.overwrite_main_grad = overwrite + p.grad_added_to_main_grad = False + with self._moe_fusion(fused): + model = te_ops.Sequential(*ops) + outs = [self._moe_call(model, *call) for call in calls] + torch.cuda.synchronize() + self.assertEqual(bool(self._moe_overlap_selected(model)), fused) + for p in weights: + self.assertTrue(p.grad_added_to_main_grad) + results.append((outs, [p.main_grad.clone() for p in weights])) + with self.subTest(dtype=dtype, overwrite=overwrite): + self._assert_moe_close(results[1], results[0]) @_eager_test_include + @_overflow_test_include @_mxfp8_align_test - def test_megamoe_main_grad_overwrite(self): - self._run_megamoe_vs_reference( - quantization="mxfp8", - accumulate_into_main_grad=True, - overwrite_main_grad=True, - ) + @_overlap_test + def test_moe_overlap_inference(self): + """Forward only, under no_grad, the fused op matches the unfused ops and publishes the + same per-expert counts and recv total, also when tokens overflow the capacity. It is + selected with accumulate_into_main_grad, as no weight gradient runs.""" + from transformer_engine.pytorch.ops.fused import moe_overlap - @_eager_test_include - def test_megamoe_delayed_wgrad_bf16(self): - self._run_megamoe_vs_reference( - quantization="bf16", - delay_wgrad_compute=True, - ) + self._require_moe_overlap() + topk_idx, tokens, w = _make_identity_inputs(self.cfg.rank, self.cfg.ep_size) + for recipe in (None, MXFP8BlockScaling()): + if recipe is not None and not ( + _mxfp8_overlap() and moe_overlap.GroupedMLP_CuTeGEMMGLU.is_supported() + ): + continue + with self.subTest(recipe=recipe): + config = self._overlap_config(recipe) + buffer = self._make_buffer_from_config(config) + ops = self._moe_ops(config, buffer, accumulate_into_main_grad=True) + results = [] + for fused in (False, True): + # Each run publishes its own counts: a stale value would show. + buffer.tokens_per_expert.fill_(-1) + buffer.total_recv_tokens.fill_(-1) + with self._moe_fusion(fused), torch.no_grad(), te.autocast( + enabled=recipe is not None, recipe=recipe + ): + model = te_ops.Sequential(*ops) + out = model(tokens, topk_idx, w, topk_idx) + torch.cuda.synchronize() + self.assertEqual(bool(self._moe_overlap_selected(model)), fused) + results.append( + ( + out, + buffer.tokens_per_expert.clone(), + int(buffer.total_recv_tokens.item()), + ) + ) + (ref_out, ref_counts, ref_total), (out, counts, total) = results + _assert_close_in_norm(out, ref_out, rtol=2e-2 if recipe is None else 1 / 16) + self.assertTrue(torch.equal(counts, ref_counts), "published per-expert counts") + self.assertEqual(total, ref_total, "published recv total") + if OVERFLOW: + self.assertGreater(total, config.recv_capacity_per_rank) + self.assertGreater(total, int(counts.sum())) @_eager_test_include @_mxfp8_align_test - def test_megamoe_delayed_wgrad(self): - self._run_megamoe_vs_reference( - quantization="mxfp8", - delay_wgrad_compute=True, + @_overlap_test + def test_moe_overlap_rank_without_tokens(self): + """Every token picks the first expert of ranks 0 and 1, so the other ranks and the other + experts of ranks 0 and 1 receive no tokens. The fused op matches the unfused ops, and + the weight gradients of the experts without tokens are zero.""" + self._require_moe_overlap() + if self.cfg.ep_size < 3: + self.skipTest("needs a rank that receives no tokens") + config = self._overlap_config() + ops = self._moe_ops(config, self._make_buffer_from_config(config)) + tokens, _, w, grad = self._moe_calls(1)[0] + topk_idx = torch.tensor([0, NUM_LOCAL_EXPERTS], device=self.cfg.device).repeat( + TOKENS_PER_RANK, 1 ) + results = [] + for fused in (False, True): + for p in ops[1].parameters(): + p.grad = None + for p in ops[3].parameters(): + p.grad = None + with self._moe_fusion(fused): + model = te_ops.Sequential(*ops) + out = self._moe_call(model, tokens, topk_idx, w, grad) + torch.cuda.synchronize() + self.assertEqual(bool(self._moe_overlap_selected(model)), fused) + results.append((out, self._param_grads(model))) + self._assert_moe_close(results[1], results[0]) + has_tokens = self.cfg.rank < 2 + for g in results[1][1]: + per_expert = g.view(NUM_LOCAL_EXPERTS, -1) + self.assertEqual(int(per_expert[int(has_tokens) :].count_nonzero()), 0) + if has_tokens: + self.assertGreater(int(per_expert[0].count_nonzero()), 0) - @_eager_test_include - def test_megamoe_delayed_main_grad_bf16(self): - self._run_megamoe_vs_reference( - quantization="bf16", - accumulate_into_main_grad=True, - delay_wgrad_compute=True, - ) + @_mxfp8_align_test + @_overlap_test + def test_moe_overlap_cuda_graph(self): + """The fused forward and backward, captured in a CUDA graph after warmup and replayed with + new routing, tokens, topk_weights and output gradient, match the unfused ops; in BF16 and, + where the overlap tests run MXFP8, under MXFP8 transport (its shared dispatch window, + requantization and weight gradients captured and replayed).""" + self._require_moe_overlap() + for recipe in [None] + ([MXFP8BlockScaling()] if _mxfp8_overlap() else []): + with self.subTest(recipe=recipe): + self._run_moe_overlap_cuda_graph(recipe) + + def _run_moe_overlap_cuda_graph(self, recipe): + """Capture and replay the fused MoE under ``recipe`` (None for BF16) and match the unfused + ops run under the same autocast.""" + if recipe is not None: + self._require_mxfp8_shapes() + device = self.cfg.device + config = self._overlap_config(recipe) + ops = self._moe_ops(config, self._make_buffer_from_config(config)) + ref_ops = self._moe_ops(config, self._make_buffer_from_config(config)) + if recipe is not None: + # Power-of-two row and column factors give every scale block its own exponent. Both + # models share the weights. + gen = torch.Generator(device=device).manual_seed(6) + with torch.no_grad(): + for fc, ref_fc in ((ops[1], ref_ops[1]), (ops[3], ref_ops[3])): + for w_fused, w_ref in zip(fc.parameters(), ref_fc.parameters()): + shape = w_fused.shape + rows = torch.randint(-3, 4, (*shape[:-1], 1), device=device, generator=gen) + cols = torch.randint(-3, 4, shape[-1:], device=device, generator=gen) + values = torch.rand(shape, device=device, generator=gen) - 0.5 + w_fused.copy_(values * 0.1 * torch.exp2((rows + cols).float())) + w_ref.copy_(w_fused) + gen = torch.Generator(device=device).manual_seed(9) + random_idx, random_tokens, random_w = _make_moe_inputs(self.cfg.rank, self.cfg.ep_size) + replays = [ + ( + random_tokens, + random_idx, + random_w, + torch.randn(random_tokens.shape, device=device, generator=gen).to(torch.bfloat16), + ), + self._moe_calls(1)[0], + ] + # Static inputs, holding the captured call's values first. + tokens, topk_idx, w, grad = (t.clone() for t in self._moe_calls(2)[1]) + x = tokens.requires_grad_(True) + topk_w = w.requires_grad_(True) + model = te_ops.Sequential(*ops) + params = list(model.parameters()) + out = {} - @_eager_test_include - @_mxfp8_align_test - def test_megamoe_delayed_main_grad(self): - self._run_megamoe_vs_reference( - quantization="mxfp8", - accumulate_into_main_grad=True, - delay_wgrad_compute=True, - ) + def step(): + for t in (x, topk_w, *params): + t.grad = None + with te.autocast(enabled=recipe is not None, recipe=recipe): + out["y"] = model(x, topk_idx, topk_w, topk_idx) + out["y"].backward(grad) - def _run_megamoe_vs_reference( - self, - *, - quantization, - accumulate_into_main_grad=False, - overwrite_main_grad=False, - delay_wgrad_compute=False, - ): - """Compare the five-op MoE sequence with the PyTorch EP reference. + graph = self._capture(step) + self.assertTrue(self._moe_overlap_selected(model)) + results = [] + for call in replays: + with torch.no_grad(): + for static, value in zip((x, topk_idx, topk_w, grad), call): + static.copy_(value) + graph.replay() + got = ( + (out["y"].detach().clone(), x.grad.clone(), topk_w.grad.clone()), + [p.grad.clone() for p in params], + ) + ref_model = te_ops.Sequential(*ref_ops) + for p in ref_model.parameters(): + p.grad = None + with self._moe_fusion(False), te.autocast(enabled=recipe is not None, recipe=recipe): + ref = (self._moe_call(ref_model, *call), self._param_grads(ref_model)) + torch.cuda.synchronize() + results.append((got, ref)) + # Compare once every rank has run every replay, so a mismatch on one rank leaves no rank + # waiting in a later replay. + for got, ref in results: + if recipe is None: + self._assert_moe_close(got, ref) + else: + # The unfused MXFP8 ops round the SwiGLU output and requantize to E4M3, so compare + # outputs and gradients in norm at the E4M3 tolerance. + self._assert_moe_close(got, ref, in_norm=True, outputs_in_norm=True, rtol=1 / 16) - The fuser selects MegaMoE when its runtime gates pass. Otherwise this - exercises the same sequence as separate NCCL EP and grouped-MLP ops. - """ - recipe = MXFP8BlockScaling() if quantization == "mxfp8" else None - model, fc1, fc2, _ = self._make_megamoe_model( - recipe=recipe, - accumulate_into_main_grad=accumulate_into_main_grad, - delay_wgrad_compute=delay_wgrad_compute, - glu_interleave_size=32 if quantization == "mxfp8" else None, - ) - generator = torch.Generator(device=self.cfg.device) - generator.manual_seed(3100 + self.cfg.rank) - with torch.no_grad(): - for op in (fc1, fc2): - weights = op.weight.quantized_tensors - if weights is None: - weights = op.weight.split_into_quantized_tensors() - for expert in range(NUM_LOCAL_EXPERTS): - weight = ( - torch.randn( - weights[expert].shape, - generator=generator, - dtype=torch.float32, - device=self.cfg.device, - ) - * 0.1 - ).to(torch.bfloat16) - weights[expert].copy_(weight) - if quantization == "mxfp8": - self.assertIsInstance(weights[expert], MXFP8Tensor) + @_mxfp8_align_test + @_overlap_test + def test_moe_overlap_instances(self): + """Weights created in inference mode, which have no version counter, run in the fused op. + Two FusedMoE instances, each with its own + EpBuffer, interleave safely: the second instance's forward and backward between the first + instance's forward and backward leave the first instance's output and gradients identical + to running it alone. One buffer and op instance per outstanding call.""" + self._require_moe_overlap() + config = self._overlap_config() + with torch.inference_mode(): + ops = self._moe_ops(config, self._make_buffer_from_config(config)) + model = te_ops.Sequential(*ops) + topk_idx, tokens, w = _make_identity_inputs(self.cfg.rank, self.cfg.ep_size) + model(tokens, topk_idx, w, topk_idx) + torch.cuda.synchronize() + self.assertTrue(self._moe_overlap_selected(model)) - topk_idx, tokens, topk_weights = _make_moe_inputs( - self.cfg.rank, - self.cfg.ep_size, - self.cfg.device, - ) - seq_tokens = tokens.requires_grad_(True) - seq_topk_weights = topk_weights.requires_grad_(True) - main_grad_sentinel = 0.5 - if accumulate_into_main_grad: - for op in (fc1, fc2): - op.weight.main_grad = torch.full( - op.weight.size(), - main_grad_sentinel, - dtype=torch.float32, - device=op.weight.device, - ) - op.weight.overwrite_main_grad = overwrite_main_grad - op.weight.zero_out_wgrad = False - op.weight.grad_added_to_main_grad = False - autocast_ctx = ( - te.autocast(enabled=True, recipe=recipe) if recipe is not None else nullcontext() - ) - with autocast_ctx: - seq_out = model( - seq_tokens, - topk_idx, - seq_topk_weights, - topk_idx, - ) + # Separate instances and buffers; _moe_ops seeds identical weights. + model_a = te_ops.Sequential(*self._moe_ops(config, self._make_buffer_from_config(config))) + model_b = te_ops.Sequential(*self._moe_ops(config, self._make_buffer_from_config(config))) + call_a, call_b = self._moe_calls(2) - self.assertEqual(seq_out.dtype, torch.bfloat16) + def forward(model, call): + for p in model.parameters(): + p.grad = None + x = call[0].clone().requires_grad_(True) + topk_w = call[2].clone().requires_grad_(True) + return x, topk_w, model(x, call[1], topk_w, call[1]) - fc1_weight = self._reference_weights(fc1) - fc2_weight = self._reference_weights(fc2) - emulate_mxfp8 = quantization == "mxfp8" - reference = MoeEpReference( - num_experts=self.cfg.num_experts, - hidden_size=HIDDEN_DIM, - intermediate_size=256, - top_k=TOP_K, - ep_group=self.ep_group, - max_tokens_per_rank=TOKENS_PER_RANK, - output_format=MoeFormat.BF16, - combine_format=MoeFormat.BF16, - apply_topk_in_fc1=True, - generate_c=True, - intermediate_format=MoeFormat.MXFP8 if emulate_mxfp8 else None, - backward_operand_format=MoeFormat.MXFP8 if emulate_mxfp8 else None, - backward_wgrad_mode="operands", - token_padding_size=256, - weight_interleave_size=32 if quantization == "mxfp8" else None, - ) - if emulate_mxfp8: - reference_activation = quantize_blockwise( - tokens.detach(), - MoeFormat.MXFP8, - axis=1, - ) - else: - reference_activation = tokens.detach() - if emulate_mxfp8 and not isinstance(fc1_weight, BlockScaledTensor): - fc1_weight = quantize_blockwise(fc1_weight, MoeFormat.MXFP8, axis=1) - if emulate_mxfp8 and not isinstance(fc2_weight, BlockScaledTensor): - fc2_weight = quantize_blockwise(fc2_weight, MoeFormat.MXFP8, axis=1) - reference_outputs = reference( - reference_activation, - fc1_weight, - fc2_weight, - topk_idx, - topk_weights.detach(), - ) - ref_out, fc1_c, route_metadata, wgrad_forward_stash = reference_outputs + def backward(model, x, topk_w, y, grad): + y.backward(grad) + torch.cuda.synchronize() + return [y.detach(), x.grad, topk_w.grad] + self._param_grads(model) - tolerances = {"rtol": 0.125, "atol": 0.25} - torch.testing.assert_close(seq_out, ref_out, **tolerances) + # Each call run alone, as the serial reference. + xa, wa, ya = forward(model_a, call_a) + alone_a = backward(model_a, xa, wa, ya, call_a[3]) + self.assertTrue(self._moe_overlap_selected(model_a)) + xb, wb, yb = forward(model_b, call_b) + alone_b = backward(model_b, xb, wb, yb, call_b[3]) + self.assertTrue(self._moe_overlap_selected(model_b)) - dy = ( - torch.randn( - seq_out.shape, - generator=generator, - dtype=torch.float32, - device=self.cfg.device, - ) - * 0.1 - ).to(torch.bfloat16) - seq_out.backward(dy) - if delay_wgrad_compute: - fc1.backward_dw() - fc2.backward_dw() - grad_tokens, grad_topk_weights, wgrad_operands = reference.backward( - dy, - fc1_weight, - fc2_weight, - topk_idx, - topk_weights.detach(), - fc1_c, - route_metadata, - wgrad_forward_stash=wgrad_forward_stash, - ) - grad_fc1, grad_fc2 = wgrad_operands.dense_wgrads() - reference_wgrads = (grad_fc1, grad_fc2) + # Interleaved: the second instance's whole call lands between the first's forward and + # backward; separate buffers keep each call's routing state intact. + xa, wa, ya = forward(model_a, call_a) + xb, wb, yb = forward(model_b, call_b) + inter_b = backward(model_b, xb, wb, yb, call_b[3]) + inter_a = backward(model_a, xa, wa, ya, call_a[3]) + self._assert_moe_close(inter_a, alone_a, UNFUSED_MLP_REFERENCE, outputs_in_norm=False) + self._assert_moe_close(inter_b, alone_b, UNFUSED_MLP_REFERENCE, outputs_in_norm=False) - torch.cuda.synchronize() - torch.testing.assert_close( - seq_tokens.grad, - grad_tokens.to(dtype=seq_tokens.dtype), - **tolerances, - ) - torch.testing.assert_close(seq_topk_weights.grad, grad_topk_weights.float(), **tolerances) - for op, ref_grad in zip((fc1, fc2), reference_wgrads): - expected_grad = ref_grad.transpose(1, 2) - if accumulate_into_main_grad: - if not overwrite_main_grad: - expected_grad = expected_grad + main_grad_sentinel - torch.testing.assert_close( - op.weight.main_grad, - expected_grad.to(dtype=op.weight.main_grad.dtype), - **tolerances, - ) - self.assertTrue(op.weight.grad_added_to_main_grad) - self.assertIsNone(op.weight.grad) - continue - seq_grad = op.weight.grad - self.assertEqual(seq_grad.dtype, torch.bfloat16) - self.assertEqual( - tuple(seq_grad.shape), - (NUM_LOCAL_EXPERTS, op.out_features, op.in_features), - ) - self.assertTrue(seq_grad.is_contiguous()) - torch.testing.assert_close( - seq_grad, - expected_grad.to(dtype=seq_grad.dtype), - **tolerances, - ) + # Autograd def _init_distributed(): From 2c238281de9f2a26c67dc0c9eb04336587c17c3e Mon Sep 17 00:00:00 2001 From: Phuong Nguyen Date: Mon, 30 Nov 2026 20:26:40 -0800 Subject: [PATCH 12/67] Document that the fused dispatch writes total_recv_tokens from its expert layout Signed-off-by: Phuong Nguyen --- .../common/include/transformer_engine/ep_gemm.h | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/transformer_engine/common/include/transformer_engine/ep_gemm.h b/transformer_engine/common/include/transformer_engine/ep_gemm.h index 885fe815a1b..4defc8b2224 100644 --- a/transformer_engine/common/include/transformer_engine/ep_gemm.h +++ b/transformer_engine/common/include/transformer_engine/ep_gemm.h @@ -86,10 +86,11 @@ extern "C" { * int32 elements. Capacity mode writes it; eager mode builds * it from recv_tokens_per_expert. The last element is the * recv total; the per-expert counts are its diffs. - * \param[out] total_recv_tokens [1] int32 recv total before any overflow drop. The routing - * prepare writes it; null when the dispatch writes - * expert_token_offsets, where expert_token_offsets[-1] is - * the padded total of the kept rows. + * \param[out] total_recv_tokens [1] int32 recv total before any overflow drop, or null. + * The routing prepare writes it; when the dispatch writes + * expert_token_offsets instead (no drops), it is + * expert_token_offsets[-1], the padded total of the kept + * rows. * \param[in,out] workspace uint8 scratch, nvte_ep_overlap_workspace_size bytes. * \param[in] activation Activation between the grouped GEMMs; only * NVTE_Activation_Type::SWIGLU is supported. From 4e5c65c787535a4cfca08a3ec18b5e1cf8dc51ca Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Tue, 1 Dec 2026 04:33:22 +0000 Subject: [PATCH 13/67] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- transformer_engine/pytorch/ep.py | 2 +- transformer_engine/pytorch/ops/fused/moe_overlap.py | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/transformer_engine/pytorch/ep.py b/transformer_engine/pytorch/ep.py index e6a6ceb472b..312fee18e31 100644 --- a/transformer_engine/pytorch/ep.py +++ b/transformer_engine/pytorch/ep.py @@ -1151,7 +1151,7 @@ def _sym_dispatch_buffers(device, quantizer: "Quantizer") -> Optional[MXFP8Tenso if not isinstance(quantizer, MXFP8Quantizer): raise NotImplementedError( - "The EP dispatch buffers support only MXFP8; " f"got {type(quantizer).__name__}." + f"The EP dispatch buffers support only MXFP8; got {type(quantizer).__name__}." ) if not tex.ep_zero_copy_supported(): return None diff --git a/transformer_engine/pytorch/ops/fused/moe_overlap.py b/transformer_engine/pytorch/ops/fused/moe_overlap.py index 8d3e6b0978d..af6b501ce77 100644 --- a/transformer_engine/pytorch/ops/fused/moe_overlap.py +++ b/transformer_engine/pytorch/ops/fused/moe_overlap.py @@ -242,7 +242,8 @@ def _check_runtime_support(self, backward: bool) -> None: _, fc1_op, _, fc2_op, _ = self.basic_ops if fc1_op.need_backward_dw() or fc2_op.need_backward_dw(): raise RuntimeError( - "FusedMoE does not support delayed weight gradient computation (delay_wgrad_compute)." + "FusedMoE does not support delayed weight gradient computation" + " (delay_wgrad_compute)." ) config = self.basic_ops[0].config if ( From 7c2a99908c2654e683dfa508cc9ae74e3d7dd0eb Mon Sep 17 00:00:00 2001 From: Phuong Nguyen Date: Mon, 30 Nov 2026 20:59:57 -0800 Subject: [PATCH 14/67] [Common] Pass the NCCL EP readiness signal as a 2D tile Signed-off-by: Phuong Nguyen --- 3rdparty/nccl-extensions | 2 +- transformer_engine/common/ep/ep_backend.cpp | 18 +++++++++++------- 2 files changed, 12 insertions(+), 8 deletions(-) diff --git a/3rdparty/nccl-extensions b/3rdparty/nccl-extensions index 3a03258e981..26ee9375f11 160000 --- a/3rdparty/nccl-extensions +++ b/3rdparty/nccl-extensions @@ -1 +1 @@ -Subproject commit 3a03258e981bdb3d3d0c1eb8144eb8752e8d2fa1 +Subproject commit 26ee9375f112606cde0b8e31d3d1927aabb101d9 diff --git a/transformer_engine/common/ep/ep_backend.cpp b/transformer_engine/common/ep/ep_backend.cpp index 890e2b41aed..0d0f1893fce 100644 --- a/transformer_engine/common/ep/ep_backend.cpp +++ b/transformer_engine/common/ep/ep_backend.cpp @@ -121,7 +121,9 @@ struct SignalDesc { ncclEpTensor_t desc = NCCL_EP_TENSOR_INIT; ncclEpSignal_t sig = NCCL_EP_SIGNAL_INIT; - ncclEpSignal_t* attach(const EpSignal* signal, ncclEpSignalUnit_t unit, const char* call) { + // A row tile spans `granularity` rows and every column (dispatch), else every row and + // `granularity` hidden columns (combine). + ncclEpSignal_t* attach(const EpSignal* signal, bool row_tiles, const char* call) { if (signal == nullptr) { return nullptr; } @@ -131,8 +133,9 @@ struct SignalDesc { call, " signal must be a 1D int32 tensor"); NVTE_CHECK(signal->granularity > 0, call, " signal granularity must be positive"); desc = make_nccl_ep_tensor(signal->ready, shape); - sig.granularity = static_cast(signal->granularity); - sig.unit = unit; + const int tile = static_cast(signal->granularity); + sig.tile_rows = row_tiles ? tile : NCCL_EP_SIGNAL_TILE_FULL; + sig.tile_cols = row_tiles ? NCCL_EP_SIGNAL_TILE_FULL : tile; sig.signal = &desc; return &sig; } @@ -441,7 +444,8 @@ void EPBackend::init(ncclComm_t ep_comm, NVTEEpGroupConfig group_config) { std::snprintf(sm_buf, sizeof(sm_buf), "%d", device_sms); setenv("NCCL_EP_SHUFFLE_SMS", sm_buf, /*overwrite=*/0); setenv("NCCL_EP_PREPROCESS_NUM_SMS", sm_buf, /*overwrite=*/0); - // The signaled combine pushes its last chunk on its own SMs; 64 of them saturate NVLink. + // Split the signaled combine so its last chunk pushes on its own SMs; 64 of them saturate + // NVLink. NCCL EP splits only with this set, on every rank of the group. constexpr char kCombinePushLastChunkSms[] = "64"; setenv("NCCL_EP_HT_COMBINE_PUSH_LAST_CHUNK_SMS", kCombinePushLastChunkSms, /*overwrite=*/0); }); @@ -605,7 +609,7 @@ void EPBackend::issue_dispatch_locked( SignalDesc dispatch_signal_desc; out_struct.dispatch_signal = - dispatch_signal_desc.attach(dispatch_signal, NCCL_EP_SIGNAL_UNIT_ROWS, "dispatch"); + dispatch_signal_desc.attach(dispatch_signal, /*row_tiles=*/true, "dispatch"); ncclEpDispatchConfig_t dispatch_cfg = NCCL_EP_DISPATCH_CONFIG_INIT; dispatch_cfg.pass_direction = is_forward ? NCCL_EP_FWD_PASS : NCCL_EP_BWD_PASS; @@ -710,7 +714,7 @@ void EPBackend::combine(NVTETensor handle_mem, const NVTETensor expert_out, SignalDesc combine_signal_desc; in_struct.combine_signal = - combine_signal_desc.attach(combine_signal, NCCL_EP_SIGNAL_UNIT_COLUMNS, "combine"); + combine_signal_desc.attach(combine_signal, /*row_tiles=*/false, "combine"); ncclEpCombineOutputs_t out_struct = NCCL_EP_COMBINE_OUTPUTS_INIT; out_struct.tokens = &nccl_result_out; @@ -753,7 +757,7 @@ void EPBackend::dispatch_bwd(NVTETensor handle_mem, const NVTETensor grad, SignalDesc combine_signal_desc; in_struct.combine_signal = - combine_signal_desc.attach(combine_signal, NCCL_EP_SIGNAL_UNIT_COLUMNS, "combine"); + combine_signal_desc.attach(combine_signal, /*row_tiles=*/false, "combine"); ncclEpCombineOutputs_t out_struct = NCCL_EP_COMBINE_OUTPUTS_INIT; out_struct.tokens = &nccl_tok_out; From fd1cac5ededcfc69203c7b02b4a4fa130ea020de Mon Sep 17 00:00:00 2001 From: Phuong Nguyen Date: Mon, 30 Nov 2026 23:08:45 -0800 Subject: [PATCH 15/67] [Common] Chain EP weight gradients with PDL on cuDNN FE MXFP8 kernels Signed-off-by: Phuong Nguyen --- tests/pytorch/test_ep_gemm.py | 28 ++++- .../common/CuTeDSL/ep_gemm/_loader.py | 12 ++ .../common/CuTeDSL/ep_gemm/wgrad_gemm.py | 107 ++++++++++++++---- transformer_engine/common/ep/ep_gemm_api.cpp | 25 ++-- .../include/transformer_engine/ep_gemm.h | 3 +- 5 files changed, 135 insertions(+), 40 deletions(-) diff --git a/tests/pytorch/test_ep_gemm.py b/tests/pytorch/test_ep_gemm.py index aec7c951594..4fee11c9e6f 100644 --- a/tests/pytorch/test_ep_gemm.py +++ b/tests/pytorch/test_ep_gemm.py @@ -239,16 +239,18 @@ def test_combine_gemm_matches_reference(backward, mxfp8, rows_alignment, rows_pe assert torch.count_nonzero(d[used:]) == 0 -def _run_wgrad(rows_per_expert, mxfp8, fp32_out, accumulate): +def _run_wgrad(rows_per_expert, mxfp8, fp32_out, accumulate, n=512, kernel_class=None): """Launch the weight gradient over padded slabs and return (grad, x, init, weight_grad) with MXFP8 operands at unit scales in float32. ``weight_grad[e] = grad[e]^T @ x[e]``, written or - added to ``init``.""" + added to ``init``. With ``kernel_class``, the configuration must build that kernel.""" device = torch.device("cuda") - m, n, experts = 256, 512, len(rows_per_expert) + m, experts = 256, len(rows_per_expert) rows = sum(rows_per_expert) + TILE # spare tile: the capacity exceeds the rows in use - routed = max(sum(rows_per_expert) // experts, 1) + routed = sum(rows_per_expert) args = (rows, m, n, experts, 8, fp32_out, accumulate, False, 0, mxfp8, False, TILE, routed) - name = f"test_ep_wgrad_{rows}_{int(mxfp8)}_{int(fp32_out)}_{int(accumulate)}" + if kernel_class is not None: + assert isinstance(wgrad_gemm.build_kernel(wgrad_gemm._config(*args)), kernel_class) + name = f"test_ep_wgrad_{rows}_{n}_{int(mxfp8)}_{int(fp32_out)}_{int(accumulate)}" assert wgrad_gemm.get_ep_wgrad_function(name, *args) launches = [tvm_ffi.get_global_func(name)] if mxfp8 and wgrad_gemm.get_ep_wgrad_reads_descriptors(*args): @@ -317,3 +319,19 @@ def test_wgrad_gemm_matches_reference(mxfp8, fp32_out, accumulate, rows_per_expe tol = 2.0**-16 if fp32_out else 2.0**-8 err = (weight_grad - ref).abs() / ref.abs().clamp_min(1e-6) assert err.max() <= tol + + +def test_wgrad_gemm_reuse_matches_reference(): + """An MXFP8 weight gradient written in BF16 over short experts, with three or more units of N + tiles per M tile, keeps A across the N tiles of an expert (the A-reuse kernel) and matches a + float32 reference.""" + rows_per_expert = [2 * TILE, TILE, 0, 3 * TILE] + reuse = wgrad_gemm._mxfp8_kernels()[2] + grad, x, _, weight_grad = _run_wgrad(rows_per_expert, True, False, False, 3072, reuse) + ref = torch.zeros_like(weight_grad) + start = 0 + for e, count in enumerate(rows_per_expert): + ref[e] = grad[start : start + count].t() @ x[start : start + count] + start += count + err = (weight_grad - ref).abs() / ref.abs().clamp_min(1e-6) + assert err.max() <= 2.0**-8 diff --git a/transformer_engine/common/CuTeDSL/ep_gemm/_loader.py b/transformer_engine/common/CuTeDSL/ep_gemm/_loader.py index af36fef9ddc..0bf8042fd08 100644 --- a/transformer_engine/common/CuTeDSL/ep_gemm/_loader.py +++ b/transformer_engine/common/CuTeDSL/ep_gemm/_loader.py @@ -45,6 +45,14 @@ "moe_blockscaled_grouped_gemm_dglu_rubin": "dglu.moe_blockscaled_grouped_gemm_dglu_rubin", "moe_blockscaled_grouped_gemm_wgrad": "wgrad.moe_blockscaled_grouped_gemm_wgrad", "moe_blockscaled_grouped_gemm_wgrad_rubin": "wgrad.moe_blockscaled_grouped_gemm_wgrad_rubin", + "moe_blockscaled_grouped_gemm_wgrad_dense": "wgrad.moe_blockscaled_grouped_gemm_wgrad_dense", + "moe_blockscaled_grouped_gemm_wgrad_reuse": "wgrad.moe_blockscaled_grouped_gemm_wgrad_reuse", + "moe_blockscaled_grouped_gemm_wgrad_dense_rubin": ( + "wgrad.moe_blockscaled_grouped_gemm_wgrad_dense_rubin" + ), + "moe_blockscaled_grouped_gemm_wgrad_reuse_rubin": ( + "wgrad.moe_blockscaled_grouped_gemm_wgrad_reuse_rubin" + ), "moe_grouped_gemm_wgrad": "wgrad.moe_grouped_gemm_wgrad", } @@ -69,6 +77,8 @@ class GemmArch: "moe_blockscaled_grouped_gemm_glu_bias", "moe_blockscaled_grouped_gemm_dglu_dbias", "moe_blockscaled_grouped_gemm_wgrad", + "moe_blockscaled_grouped_gemm_wgrad_dense", + "moe_blockscaled_grouped_gemm_wgrad_reuse", ), ) # SM 10.7 (Rubin) has no BF16 kernels in cuDNN FE yet, so the BF16 roles reuse the SM 10.0 ones. @@ -83,6 +93,8 @@ class GemmArch: "moe_blockscaled_grouped_gemm_glu_rubin", "moe_blockscaled_grouped_gemm_dglu_rubin", "moe_blockscaled_grouped_gemm_wgrad_rubin", + "moe_blockscaled_grouped_gemm_wgrad_dense_rubin", + "moe_blockscaled_grouped_gemm_wgrad_reuse_rubin", ), ) # Kernels by compute capability; other architectures run the unfused ops. diff --git a/transformer_engine/common/CuTeDSL/ep_gemm/wgrad_gemm.py b/transformer_engine/common/CuTeDSL/ep_gemm/wgrad_gemm.py index 7c92c687d77..392ee77a0e9 100644 --- a/transformer_engine/common/CuTeDSL/ep_gemm/wgrad_gemm.py +++ b/transformer_engine/common/CuTeDSL/ep_gemm/wgrad_gemm.py @@ -10,7 +10,8 @@ [experts] int32, ``workspace`` uint8, stream. Each launch is a persistent grid that claims output tiles from an atomic counter in ``workspace``, -so launches sharing one workspace split the tiles across SMs. +so launches sharing one workspace split the tiles across SMs. It is a programmatic dependent of the +kernel before it and lets the kernel behind it start early. """ import functools @@ -47,6 +48,9 @@ class WgradConfig: fp32_out: bool = False # FP32 instead of BF16 weight gradient accumulate: bool = False # add to the weight gradient instead of writing it scaling_mode: int = DELAYED_TENSOR_SCALING # operand scaling (NVTEScalingMode) + wait_primary_at_start: bool = False # wait for the kernel before it ahead of any load + token_alignment: int = 0 # rows per expert slab are a multiple of it + routed_tokens: int = 0 # rows a rank receives on average # Kernels, workspace layouts and compiled functions are specific to the device architecture. capability: tuple = field(default_factory=device_compute_capability) @@ -56,31 +60,77 @@ def mxfp8(self) -> bool: return self.scaling_mode == MXFP8_1D_SCALING -def _mxfp8_kernel(): - """MXFP8 weight-gradient kernel class of the device and moe_utils.""" +def _mxfp8_kernels(): + """(stock, global-descriptor, A-reuse) MXFP8 weight-gradient kernel classes of the device and + moe_utils.""" if is_sm107(): - module, moe_utils = import_gemm_modules("moe_blockscaled_grouped_gemm_wgrad_rubin") - return module.BlockScaledMoEGroupedGemmWgradRubinKernel, moe_utils - module, moe_utils = import_gemm_modules("moe_blockscaled_grouped_gemm_wgrad") - return module.BlockScaledMoEGroupedGemmWgradKernel, moe_utils + stock, dense, reuse, moe_utils = import_gemm_modules( + "moe_blockscaled_grouped_gemm_wgrad_rubin", + "moe_blockscaled_grouped_gemm_wgrad_dense_rubin", + "moe_blockscaled_grouped_gemm_wgrad_reuse_rubin", + ) + return ( + stock.BlockScaledMoEGroupedGemmWgradRubinKernel, + dense.BlockScaledMoEGroupedGemmWgradDenseRubinKernel, + reuse.BlockScaledMoEGroupedGemmWgradReuseRubinKernel, + moe_utils, + ) + stock, dense, reuse, moe_utils = import_gemm_modules( + "moe_blockscaled_grouped_gemm_wgrad", + "moe_blockscaled_grouped_gemm_wgrad_dense", + "moe_blockscaled_grouped_gemm_wgrad_reuse", + ) + return ( + stock.BlockScaledMoEGroupedGemmWgradKernel, + dense.BlockScaledMoEGroupedGemmWgradDenseKernel, + reuse.BlockScaledMoEGroupedGemmWgradReuseKernel, + moe_utils, + ) + + +def _padded_tokens(cfg: WgradConfig) -> int: + """Rows a rank receives with each expert slab padded by half the token alignment on average: + the token count cuDNN FE picks the MXFP8 kernel and sizes its A ring from.""" + return cfg.routed_tokens + cfg.num_experts * cfg.token_alignment // 2 + + +def _global_descriptor_kernel(cfg: WgradConfig): + """Class of an MXFP8 weight gradient written in BF16, which reads global descriptors: the one + keeping A across the N tiles of an expert where cuDNN FE prefers it (short experts on + average), else the dense one; None for the others.""" + if cfg.accumulate or cfg.fp32_out: + return None + _, dense, reuse, _ = _mxfp8_kernels() + shape = {"ab_bits": 8, "c_bits": 16, "has_global_scale": False} + if not dense.can_implement(cfg.m, cfg.n, **shape): + return None + if reuse.prefer_over_dense( + cfg.m, cfg.n, **shape, tokens=_padded_tokens(cfg), experts=cfg.num_experts + ): + return reuse + return dense def reads_descriptors(cfg: WgradConfig) -> bool: """Whether the launches of ``cfg`` read per-expert descriptors from a ``descriptors_only`` launch.""" del cfg - # TODO(phuonguyen): cuDNN FE has no descriptors-only / reuse wgrad kernels, so the single - # kernel reads its operands directly and no descriptor pre-launch is needed. + # The cuDNN FE stock kernel builds its per-expert descriptors in its own helper kernel. return False def build_kernel(cfg: WgradConfig): """Weight-gradient kernel for ``cfg``. Persistent clusters claim output tiles from an atomic - counter in the workspace, so launches sharing one workspace split the tiles across SMs.""" - # cuDNN FE splits the output tiles across SMs with atomic_counter_claim. Its finer overlap is - # performance-only and not upstreamed yet: use_pdl (WAR for PR #2898), wait_primary_at_start, - # signal_unit_tokens, the MXFP8 descriptor-reuse kernels and the 256 x 512 wide BF16 kernel. - # TODO(phuonguyen): restore them once cuDNN FE adds them; correctness holds without them. + counter in the workspace, so launches sharing one workspace split the tiles across SMs. An + MXFP8 weight gradient written in BF16 reads A, B and the scales through global descriptors. + + A launch with ``wait_primary_at_start`` waits for the kernel before it, then lets the kernel + behind it start. Another launch follows one that did and reads nothing the kernel before it + writes: the global-descriptor kernels let the kernel behind them start at entry and wait at + exit; the others, which launch a helper kernel first, wait at start.""" + # TODO(phuonguyen): restore the wait on the dispatch readiness signal, a BF16 launch with no + # helper kernel in front and the 256 x 512 wide BF16 kernel on a shared counter once cuDNN FE + # adds them; correctness holds without them. common = dict( acc_dtype=cutlass.Float32, use_2cta_instrs=True, @@ -89,9 +139,21 @@ def build_kernel(cfg: WgradConfig): accumulate_on_output=cfg.accumulate, expert_cnt=cfg.num_experts, atomic_counter_claim=True, + use_pdl=True, ) if cfg.mxfp8: - kernel_class, moe_utils = _mxfp8_kernel() + stock, _, _, moe_utils = _mxfp8_kernels() + kernel_class = _global_descriptor_kernel(cfg) + if kernel_class is None: + kernel_class = stock + common["launch_pdl_dependents_at_entry"] = cfg.wait_primary_at_start + else: + common["pdl_mode"] = ( + "wait_then_trigger" if cfg.wait_primary_at_start else "trigger_then_wait_at_exit" + ) + if hasattr(kernel_class, "a_stages_for"): + # The A-reuse kernel sizes its A ring to the average padded expert. + common["a_stages"] = kernel_class.a_stages_for(_padded_tokens(cfg), cfg.num_experts) return kernel_class( sf_vec_size=SF_VEC_SIZE, weight_mode=moe_utils.MoEWeightMode.DENSE, @@ -102,6 +164,7 @@ def build_kernel(cfg: WgradConfig): return module.MoEGroupedGemmWgradBF16Kernel( weight_mode=moe_utils.MoEWeightMode.DENSE, input_order=moe_utils.WGradInputOrder.Tensor2D, + launch_pdl_dependents_at_entry=cfg.wait_primary_at_start, **common, ) @@ -188,14 +251,14 @@ def _config( rows, m, n, num_experts, num_clusters, fp32_out, accumulate, wait_primary_at_start, signal_unit_tokens, scaling_mode, descriptors_only, token_alignment, routed_tokens, ): # fmt: skip - """Build a WgradConfig from the entry-point arguments. The overlap-selection arguments - (wait_primary_at_start, signal_unit_tokens, descriptors_only, token_alignment, routed_tokens) select - cuDNN FE optimizations that are not upstreamed yet (see build_kernel); they are accepted for ABI - stability and currently ignored.""" - del wait_primary_at_start, signal_unit_tokens, descriptors_only, token_alignment, routed_tokens + """Build a WgradConfig from the entry-point arguments. signal_unit_tokens and + descriptors_only select cuDNN FE kernels that do not exist (see build_kernel); they are + accepted for ABI stability and ignored.""" + del signal_unit_tokens, descriptors_only return WgradConfig( - rows, m, n, num_experts, num_clusters, bool(fp32_out), bool(accumulate), int(scaling_mode) - ) + rows, m, n, num_experts, num_clusters, bool(fp32_out), bool(accumulate), int(scaling_mode), + bool(wait_primary_at_start), token_alignment, routed_tokens, + ) # fmt: skip def get_ep_wgrad_workspace_layout( diff --git a/transformer_engine/common/ep/ep_gemm_api.cpp b/transformer_engine/common/ep/ep_gemm_api.cpp index 6cd48bdbea1..185a83f8642 100644 --- a/transformer_engine/common/ep/ep_gemm_api.cpp +++ b/transformer_engine/common/ep/ep_gemm_api.cpp @@ -875,20 +875,24 @@ void nvte_ep_combine_gemm_bwd( &alpha, &prob, &norm_const, &ws, static_cast(stream)); } // The weight gradient once the GEMM and the requant complete: its base, which then lets its - // tail in. + // tail in. An added or FP32 one runs on every SM: its kernel launches a helper kernel in front, + // so a tail would wait for the base to complete. if (wgrad) { - launch_wgrad(*wgrad, scratch, ctx.num_clusters, true, 0, stream, false); - launch_wgrad(*wgrad, scratch, ctx.all_clusters - ctx.num_clusters, false, 0, stream, false); + // As wgrad_gemm.build_kernel: the dense kernel implements every MXFP8 shape TE takes, so + // only these get the stock kernel. + const bool helper = wgrad->config.accumulate || wgrad->config.fp32_out; + const int base_clusters = helper ? ctx.all_clusters : ctx.num_clusters; + launch_wgrad(*wgrad, scratch, base_clusters, true, 0, stream, false); + launch_wgrad(*wgrad, scratch, ctx.all_clusters - base_clusters, false, 0, stream, false); } return; } auto b = wrap_rowwise(weight, false); gemm(&a, &b, &c, &d, &dprob, &row_ends, &alpha, &prob, &ws, static_cast(stream)); - // The weight gradient once the GEMM completes: its base waits for the GEMM, then lets its tail in. - // Both launches claim from one shared tile counter, so the split does not re-run the whole GEMM. + // The weight gradient once the GEMM completes, on every SM: a BF16 tail would wait for its base + // to complete, as the BF16 kernel launches a helper kernel in front of it. if (wgrad) { - launch_wgrad(*wgrad, scratch, ctx.num_clusters, true, 0, stream, false); - launch_wgrad(*wgrad, scratch, ctx.all_clusters - ctx.num_clusters, false, 0, stream, false); + launch_wgrad(*wgrad, scratch, ctx.all_clusters, true, 0, stream, false); } } @@ -993,7 +997,8 @@ void nvte_ep_dispatch_gemm_bwd(NVTETensor handle_mem, const NVTETensor grad_gemm auto b = wrap_rowwise(weight, false); gemm(&a, &b, &d, &row_ends, &alpha, &prob, &ws, static_cast(stream)); } - // The weight gradient's base starts once the GEMM completes and lets the dispatch backward in. + // The weight gradient starts once the GEMM completes and lets the dispatch backward in. The + // dispatch backward completes after it, so a launch behind them would find no tiles left. if (wgrad) { launch_wgrad(*wgrad, scratch, ctx.num_clusters, true, 0, stream, false); } @@ -1005,10 +1010,6 @@ void nvte_ep_dispatch_gemm_bwd(NVTETensor handle_mem, const NVTETensor grad_gemm ctx.backend.dispatch_bwd(handle_mem, grad_recv_tokens, no_window, grad_recv_topk_weights, no_window, grad_tokens, grad_topk_weights, &combine_signal, &ctx.layer_cfg, stream); - // Its tail takes the tiles the base left; both claim from one shared counter. - if (wgrad) { - launch_wgrad(*wgrad, scratch, ctx.all_clusters - ctx.num_clusters, false, 0, stream, false); - } } } // extern "C" diff --git a/transformer_engine/common/include/transformer_engine/ep_gemm.h b/transformer_engine/common/include/transformer_engine/ep_gemm.h index 4defc8b2224..540eb1ce72f 100644 --- a/transformer_engine/common/include/transformer_engine/ep_gemm.h +++ b/transformer_engine/common/include/transformer_engine/ep_gemm.h @@ -230,10 +230,11 @@ void nvte_ep_combine_gemm_bwd( * Schedule (FC1 dgrad, then unsignaled combine overlaps wgrad; combine_bwd_num_sms; time --->): * FC1 dgrad |--- all SMs ---| * combine | |--- return dX, dprob ---| - * FC1 wgrad | |--- head ---------------|--- tail ---| + * FC1 wgrad | |--- other SMs ----------| * * Requirements: * - SM 10.0, 10.3 or 10.7; EP within one NVLink domain; num_comm_sms > 0; zero_copy off. + * - A PDL kernel launched after the call must wait before it reads the call's outputs. * - dispatch_output_per_expert_alignment: bfloat16 is 64, 128 or 256; MXFP8 is 256, or 128 * except on SM 10.7. * - NVTE_ENABLE_CUTEDSL_BACKEND=1 and NVTE_MOE_OVERLAP set. From f7eca1bfd357227f99db0f512db48082fc39743f Mon Sep 17 00:00:00 2001 From: Phuong Nguyen Date: Mon, 30 Nov 2026 23:08:45 -0800 Subject: [PATCH 16/67] [PyTorch] Skip EP overlap test passes at expert alignment 128 and 64 Signed-off-by: Phuong Nguyen --- tests/pytorch/distributed/run_test_ep.sh | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/tests/pytorch/distributed/run_test_ep.sh b/tests/pytorch/distributed/run_test_ep.sh index 9ed58792cfd..b2e61e042b8 100755 --- a/tests/pytorch/distributed/run_test_ep.sh +++ b/tests/pytorch/distributed/run_test_ep.sh @@ -176,7 +176,10 @@ else NVTE_EP_HIDDEN_DIM=1536 run_pass "overlap_h1536" 0 0 0 1 0 1 # Expert alignments below 256 (MXFP8 cases skip at 64): an expert's last GEMM tile holds fewer # rows. With 288 tokens per rank each expert also fills a whole tile; only the fused op tests run. - for align in 128 64; do + # TODO(phuonguyen): FusedMoE takes only alignment 256 until the cuDNN FE grouped GEMMs have + # tail-tile kernels; loop over 128 and 64 again then. + echo "SKIPPING the overlap passes at expert alignment 128 and 64: FusedMoE takes only 256." + for align in; 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 \ From 1fe6fd0aeb0acc4be1c50345c365a6f06e5a90aa Mon Sep 17 00:00:00 2001 From: Phuong Nguyen Date: Mon, 30 Nov 2026 21:12:38 -0800 Subject: [PATCH 17/67] [Common] Skip the columnwise dGLU outputs of frozen FusedMoE weights Signed-off-by: Phuong Nguyen --- tests/pytorch/distributed/run_ep.py | 21 +++++++++-- .../common/CuTeDSL/ep_gemm/_loader.py | 10 ++++++ .../common/CuTeDSL/ep_gemm/dispatch_gemm.py | 35 ++++++++++++------- transformer_engine/common/ep/ep_gemm_api.cpp | 28 +++++++++++---- transformer_engine/common/ep/ep_gemm_config.h | 6 +++- .../include/transformer_engine/ep_gemm.h | 4 ++- .../pytorch/csrc/extensions/ep.cpp | 15 ++++---- .../pytorch/ops/fused/moe_overlap.py | 22 +++++++++--- 8 files changed, 106 insertions(+), 35 deletions(-) diff --git a/tests/pytorch/distributed/run_ep.py b/tests/pytorch/distributed/run_ep.py index d18543e30fa..fd0a2668e04 100644 --- a/tests/pytorch/distributed/run_ep.py +++ b/tests/pytorch/distributed/run_ep.py @@ -1986,7 +1986,10 @@ def pack(tensor): num_tokens.append(n.clone() if torch.is_tensor(n) else n) return tensor - with ctx, te.autocast( + combine_bwd = mock.patch.object( + moe_overlap.tex, "ep_combine_gemm_bwd", wraps=moe_overlap.tex.ep_combine_gemm_bwd + ) + with ctx, combine_bwd as combine_bwd_spy, te.autocast( enabled=recipe is not None, recipe=recipe ), torch.autograd.graph.saved_tensors_hooks(pack, lambda tensor: tensor): model = te_ops.Sequential(*ops) @@ -2007,9 +2010,17 @@ def pack(tensor): grads = [(p.main_grad if main_grad else p.grad).clone() for p in trained] counts = [int(n) for n in num_tokens] published = (buffer.tokens_per_expert.clone(), int(buffer.total_recv_tokens.item())) + # Whether the MXFP8 combine backward writes the columnwise grad_gemm_out and act_out. + columnwise_outputs = None + if recipe is not None and combine_bwd_spy.called: + args, kwargs = combine_bwd_spy.call_args + columnwise_outputs = ( + args[7]._columnwise_data is not None, + kwargs["act_out"] is not None, + ) return ( y.detach(), x.grad, topk_w.grad, grads, bool(fused_ops), stashable, counts, - published, + published, columnwise_outputs, ) # fmt: skip ref = run(False) @@ -2051,6 +2062,12 @@ def pack(tensor): ffn = ops[3].in_features recv_bytes = 0 if 1 in frozen else HIDDEN_DIM + HIDDEN_DIM // 32 self.assertEqual(saved, rows * (recv_bytes + 2 * ffn * 2 + 4), "saved bytes") + # A frozen weight's gradient operand is not written (the columnwise grad_gemm_out only + # where the cuDNN FE dGLU can leave it out). + fc1_columnwise = 1 not in frozen or not moe_overlap._dglu_skips_column_outputs() + self.assertEqual( + out[8], (fc1_columnwise, 3 not in frozen), "columnwise grad_gemm_out and act_out" + ) # Where the unfused ops compute the SwiGLU output in their own kernel, single elements may # round to another value, so those results are compared in norm. The unfused MXFP8 ops also # round the FC2 dgrad and the SwiGLU backward output to BF16 before quantizing them, so diff --git a/transformer_engine/common/CuTeDSL/ep_gemm/_loader.py b/transformer_engine/common/CuTeDSL/ep_gemm/_loader.py index 0bf8042fd08..a74055a5436 100644 --- a/transformer_engine/common/CuTeDSL/ep_gemm/_loader.py +++ b/transformer_engine/common/CuTeDSL/ep_gemm/_loader.py @@ -186,6 +186,16 @@ def gemm_interface_reason(mxfp8=False) -> Optional[str]: return _gemm_interface_reason(device_compute_capability(), mxfp8) +@functools.lru_cache(maxsize=None) +def dglu_skips_column_outputs() -> bool: + """Whether the MXFP8 dGLU leaves out its columnwise D when given none (older cuDNN + frontends always write it).""" + try: + return getattr(importlib.import_module(_PKG), "DGLU_OPTIONAL_SFD_COL", False) + except ImportError: + return False + + def unsupported_device_reason(what): """Why ``what`` cannot run on the current device, or None.""" if device_compute_capability() in GEMM_ARCHS: diff --git a/transformer_engine/common/CuTeDSL/ep_gemm/dispatch_gemm.py b/transformer_engine/common/CuTeDSL/ep_gemm/dispatch_gemm.py index f7d7435b558..b1693b58dfd 100644 --- a/transformer_engine/common/CuTeDSL/ep_gemm/dispatch_gemm.py +++ b/transformer_engine/common/CuTeDSL/ep_gemm/dispatch_gemm.py @@ -21,7 +21,9 @@ MXFP8 scales: ``sfa`` is compact (as the dispatch delivers it) and ``sfb`` swizzled. The forward takes no ``prob`` and a ``norm_const`` [1] FP32 of 1. The backward writes ``sfd_row`` (swizzled), -``sfd_col`` and ``sfh_col`` (swizzled per expert). +``sfd_col`` and ``sfh_col`` (swizzled per expert). Without ``d_col`` or ``h`` in the configuration +the backward takes None for ``d_col`` and ``sfd_col``, or ``h`` and ``sfh_col``, and does not write +them. """ import functools @@ -71,6 +73,8 @@ class DispatchGemmConfig: scaling_mode: int = DELAYED_TENSOR_SCALING # operand scaling (NVTEScalingMode) token_alignment: int = ROWS_PER_TILE # rows per expert slab are a multiple of it device_layout: bool = False # forward: the dispatch writes the expert row ends + d_col: bool = True # MXFP8 backward: writes the columnwise d and its scales + h: bool = True # MXFP8 backward: writes the columnwise h and its scales activation: str = "swiglu" # Kernels, workspace layouts and compiled functions are specific to the device architecture. capability: tuple = field(default_factory=device_compute_capability) @@ -308,6 +312,11 @@ def launch_rubin( ) +def _optional_rows_view(t, rows, cols): + """``rows_view`` of an optional operand.""" + return None if t is None else rows_view(t, rows, cols) + + def _compile_backward_mxfp8(cfg: DispatchGemmConfig): """MXFP8 FC2 data gradient with the columnwise forward weight [experts, k, n] read N-major, SwiGLU backward in the epilogue, and the forward activation recomputed columnwise.""" @@ -322,10 +331,10 @@ def launch( kernel( rows_view(a, rows, k), weight, sfb, cutlass.Int32(0), cutlass.Int32(0), cutlass.Int64(0), OperandMajorMode.K, workspace.iterator, rows_view(c, rows, 2 * n), - rows_view(d, rows, 2 * n), rows_view(d_col, rows, 2 * n), sfa, sfd_row, sfd_col, None, - norm_const, expert_row_ends, alpha, alpha, prob_view(prob, rows), + rows_view(d, rows, 2 * n), _optional_rows_view(d_col, rows, 2 * n), sfa, sfd_row, + sfd_col, None, norm_const, expert_row_ends, alpha, alpha, prob_view(prob, rows), prob_view(dprob, rows), None, num_clusters, stream, - h_tensor=rows_view(h, rows, n), sfh_col_tensor=sfh_col, + h_tensor=_optional_rows_view(h, rows, n), sfh_col_tensor=sfh_col, ) # fmt: skip row_ends, alpha, prob, workspace = tail @@ -337,11 +346,11 @@ def launch( scale_fake(rows, k), fake_tensor(cutlass.BFloat16, (rows, 2 * n), (1, 0), 16), fp8_fake((rows, 2 * n), (1, 0)), - fp8_fake((rows, 2 * n), (1, 0)), - scale_fake(rows, 2 * n), + fp8_fake((rows, 2 * n), (1, 0)) if cfg.d_col else None, scale_fake(rows, 2 * n), - fp8_fake((rows, n), (1, 0)), - scale_fake(rows, n), + scale_fake(rows, 2 * n) if cfg.d_col else None, + fp8_fake((rows, n), (1, 0)) if cfg.h else None, + scale_fake(rows, n) if cfg.h else None, fake_tensor(cutlass.Float32, (rows,), (0,), 16), row_ends, alpha, @@ -360,31 +369,33 @@ def launch( def _config(rows, k, n, num_experts, num_clusters, backward, scaling_mode, token_alignment, - device_layout): # fmt: skip + device_layout, d_col, h): # fmt: skip """Build a DispatchGemmConfig from the entry-point arguments.""" return DispatchGemmConfig( rows, k, n, num_experts, num_clusters, bool(backward), int(scaling_mode), token_alignment, - bool(device_layout), + bool(device_layout), bool(d_col), bool(h), ) # fmt: skip def get_ep_dispatch_gemm_workspace_layout( rows, k, n, num_experts, num_clusters, backward, scaling_mode=DELAYED_TENSOR_SCALING, - token_alignment=ROWS_PER_TILE, device_layout=False, + token_alignment=ROWS_PER_TILE, device_layout=False, d_col=True, h=True, ): # fmt: skip """[total bytes, counter, signal, state] byte offsets of the workspace of this configuration.""" return list(workspace_layout(_config( rows, k, n, num_experts, num_clusters, backward, scaling_mode, token_alignment, device_layout, + d_col, h, ))) # fmt: skip def get_ep_dispatch_gemm_function( fn_name, rows, k, n, num_experts, num_clusters, backward, scaling_mode=DELAYED_TENSOR_SCALING, - token_alignment=ROWS_PER_TILE, device_layout=False, + token_alignment=ROWS_PER_TILE, device_layout=False, d_col=True, h=True, ) -> bool: # fmt: skip """Compile and register the GEMM of this configuration as ``fn_name``; return whether it is.""" cfg = _config( rows, k, n, num_experts, num_clusters, backward, scaling_mode, token_alignment, device_layout, + d_col, h, ) # fmt: skip compile_fn = _COMPILERS[cfg.backward, cfg.mxfp8] return register_function(fn_name, lambda: compile_fn(cfg), "EP dispatch grouped GEMM") diff --git a/transformer_engine/common/ep/ep_gemm_api.cpp b/transformer_engine/common/ep/ep_gemm_api.cpp index 185a83f8642..bb4f3f1f0f6 100644 --- a/transformer_engine/common/ep/ep_gemm_api.cpp +++ b/transformer_engine/common/ep/ep_gemm_api.cpp @@ -786,8 +786,12 @@ void nvte_ep_combine_gemm_bwd( check_mxfp8(grad_expert_out, false, "grad_expert_out"); check_mxfp8(weight, true, "weight"); check_mxfp8(grad_gemm_out, true, "grad_gemm_out"); - check_mxfp8(act_out, true, "act_out"); - NVTE_CHECK(nvte_tensor_shape(act_out).data[1] == ffn, "act_out must have ffn columns"); + if (act_out != nullptr) { + check_mxfp8(act_out, true, "act_out"); + NVTE_CHECK(nvte_tensor_shape(act_out).data[1] == ffn, "act_out must have ffn columns"); + } + NVTE_CHECK(act_out != nullptr || weight_grad == nullptr, + "the MXFP8 weight gradient reads the act_out this call writes"); check_ep_mxfp8_dims(hidden, ffn, ctx.alignment()); } else { NVTE_CHECK( @@ -809,8 +813,12 @@ void nvte_ep_combine_gemm_bwd( num_experts, scaling_mode); ep::WorkspaceLayout layout; - const ep::EpDispatchGemmConfig config{ + ep::EpDispatchGemmConfig config{ rows, hidden, ffn, num_experts, ctx.num_clusters, true, scaling_mode, ctx.alignment()}; + // MXFP8: the columnwise grad_gemm_out and act_out are written when set. + config.d_col = + mxfp8 && nvte_get_tensor_param(grad_gemm_out, kNVTEColumnwiseData).data_ptr != nullptr; + config.h = act_out != nullptr; const tvm::ffi::Function gemm = get_gemm(config, &layout); GemmScratch scratch = claim_scratch(ws_base, ws_bytes, layout.total_bytes, num_experts, rows, false, wgrad ? wgrad->layout.total_bytes : 0); @@ -854,11 +862,17 @@ void nvte_ep_combine_gemm_bwd( auto b = wrap_columnwise(weight, false); auto sfb = wrap_scales(weight, true, num_experts * hidden, ffn); auto sfa = wrap_scales(grad_expert_out, false, rows, hidden); - auto d_col = wrap_columnwise(grad_gemm_out, true); + // An output that is not written passes as None. + DLTensorWrapper d_col, sfd_col, h, sfh_col; + if (config.d_col) { + d_col = wrap_columnwise(grad_gemm_out, true); + sfd_col = wrap_scales(grad_gemm_out, true, rows, 2 * ffn); + } + if (config.h) { + h = wrap_columnwise(act_out, true); + sfh_col = wrap_scales(act_out, true, rows, ffn); + } auto sfd_row = wrap_scales(grad_gemm_out, false, rows, 2 * ffn); - auto sfd_col = wrap_scales(grad_gemm_out, true, rows, 2 * ffn); - auto h = wrap_columnwise(act_out, true); - auto sfh_col = wrap_scales(act_out, true, rows, ffn); auto norm_const = wrap_raw(scratch.alpha, kNVTEFloat32, 1); gemm(&a, &b, &sfb, &sfa, &c, &d, &d_col, &sfd_row, &sfd_col, &h, &sfh_col, &dprob, &row_ends, &alpha, &prob, &norm_const, &ws, static_cast(stream)); diff --git a/transformer_engine/common/ep/ep_gemm_config.h b/transformer_engine/common/ep/ep_gemm_config.h index d839acfb76e..85949409ea9 100644 --- a/transformer_engine/common/ep/ep_gemm_config.h +++ b/transformer_engine/common/ep/ep_gemm_config.h @@ -174,6 +174,10 @@ struct EpDispatchGemmConfig { // Forward: the dispatch writes the expert offsets and the row total, the word before the row // ends and the row ends, after the caller set them to -1. bool device_layout = false; + // MXFP8 backward: writes the columnwise d and h, the weight gradient operands of the first and + // second GEMM. + bool d_col = true; + bool h = true; bool is_mxfp8() const { return scaling_mode == NVTE_MXFP8_1D_SCALING; } @@ -182,7 +186,7 @@ struct EpDispatchGemmConfig { return std::make_tuple(static_cast(rows), static_cast(k), static_cast(n), static_cast(num_experts), num_clusters, backward, static_cast(scaling_mode), - static_cast(token_alignment), device_layout); + static_cast(token_alignment), device_layout, d_col, h); } std::string to_key() const { return config_key("ep_dispatch_gemm", args()); } diff --git a/transformer_engine/common/include/transformer_engine/ep_gemm.h b/transformer_engine/common/include/transformer_engine/ep_gemm.h index 540eb1ce72f..81cc320a733 100644 --- a/transformer_engine/common/include/transformer_engine/ep_gemm.h +++ b/transformer_engine/common/include/transformer_engine/ep_gemm.h @@ -193,11 +193,13 @@ void nvte_ep_combine_gemm_fwd(NVTETensor handle_mem, const NVTETensor gemm_in, * its columnwise data is set, also columnwise, its scales * GEMM-swizzled per expert slab, for the weight gradient. * \param[out] grad_gemm_out [recv_capacity, 2 * ffn_dim] gradient of gemm_out; MXFP8: - * rowwise and columnwise. + * rowwise and, when its columnwise data is set, also + * columnwise. * \param[out] grad_recv_topk_weights [recv_capacity] float32 gradient of recv_topk_weights. * \param[out] act_out [recv_capacity, ffn_dim] columnwise MXFP8 * recv_topk_weights * silu(gate) * up, the input of the * second GEMM's weight gradient; MXFP8 only, else null. + * Null with MXFP8 skips it; weight_grad must be null then. * \param[in,out] weight_grad [num_local_experts, hidden_dim, ffn_dim] bfloat16 or * float32 gradient of weight, or null. * \param[in] accumulate_weight_grad Add to weight_grad instead of writing it. diff --git a/transformer_engine/pytorch/csrc/extensions/ep.cpp b/transformer_engine/pytorch/csrc/extensions/ep.cpp index 019f9c6d666..339007d2477 100644 --- a/transformer_engine/pytorch/csrc/extensions/ep.cpp +++ b/transformer_engine/pytorch/csrc/extensions/ep.cpp @@ -1050,7 +1050,8 @@ void ep_combine_gemm_fwd(at::Tensor handle_mem, py::object gemm_in, at::Tensor e // MXFP8: the weight and act_out are columnwise with GEMM-swizzled scales; grad_result is rowwise // with compact scales, grad_expert_out rowwise with compact scales and columnwise when the weight -// gradient is computed, and grad_gemm_out rowwise and columnwise with swizzled scales. +// gradient is computed, and grad_gemm_out rowwise with swizzled scales. The columnwise +// grad_gemm_out and act_out, the weight gradient operands, are written when given. void ep_combine_gemm_bwd(at::Tensor handle_mem, py::object grad_result, at::Tensor gemm_out, at::Tensor recv_topk_weights, at::Tensor tokens_per_expert, py::object weight, py::object grad_expert_out, py::object grad_gemm_out, @@ -1078,7 +1079,7 @@ void ep_combine_gemm_bwd(at::Tensor handle_mem, py::object grad_result, at::Tens check_dense_cuda(grad_recv_topk_weights, "grad_recv_topk_weights"); const bool mxfp8 = is_mxfp8_object(grad_result); NVTE_CHECK(is_mxfp8_object(weight) == mxfp8 && is_mxfp8_object(grad_expert_out) == mxfp8 && - is_mxfp8_object(grad_gemm_out) == mxfp8 && act_out.has_value() == mxfp8 && + is_mxfp8_object(grad_gemm_out) == mxfp8 && (mxfp8 || !act_out.has_value()) && (!act_out.has_value() || is_mxfp8_object(*act_out)) && (!wgrad_input.has_value() || is_mxfp8_object(*wgrad_input) == mxfp8), "pass all of the operands as MXFP8 tensors, or all as torch tensors"); @@ -1091,12 +1092,12 @@ void ep_combine_gemm_bwd(at::Tensor handle_mem, py::object grad_result, at::Tens auto grad_gemm_out_te = operand_tensor(grad_gemm_out); auto grad_recv_topk_weights_te = makeTransformerEngineTensor(grad_recv_topk_weights); TensorWrapper act_out_te; - if (mxfp8) { + if (act_out.has_value()) { act_out_te = operand_tensor(*act_out); } - // The weight is [experts, hidden, ffn], and act_out is [rows, ffn]. - auto weight_te = - weight_operand(weight, tokens_per_expert.numel(), mxfp8 ? act_out_te.shape().data[1] : 0); + // The weight is [experts, hidden, ffn], and grad_gemm_out is [rows, 2 * ffn]. + auto weight_te = weight_operand(weight, tokens_per_expert.numel(), + mxfp8 ? grad_gemm_out_te.shape().data[1] / 2 : 0); WeightGradTensors wgrad(wgrad_input, weight_grad); const NVTECommWindow grad_result_win = symm_input ? make_input_window(grad_result) : kNoWindow; auto layer_cfg = make_layer_cfg(top_k, dispatch_output_per_expert_alignment, @@ -1113,7 +1114,7 @@ void ep_combine_gemm_bwd(at::Tensor handle_mem, py::object grad_result, at::Tens handle_mem_te.data(), grad_result_te.data(), grad_result_win, gemm_out_te.data(), recv_topk_weights_te.data(), tokens_per_expert_te.data(), weight_te.data(), wgrad.input(), grad_expert_out_te.data(), grad_gemm_out_te.data(), grad_recv_topk_weights_te.data(), - mxfp8 ? act_out_te.data() : nullptr, wgrad.output(), accumulate_weight_grad, + act_out.has_value() ? act_out_te.data() : nullptr, wgrad.output(), accumulate_weight_grad, workspace_te.data(), NVTE_Activation_Type::SWIGLU, &layer_cfg, stream); } diff --git a/transformer_engine/pytorch/ops/fused/moe_overlap.py b/transformer_engine/pytorch/ops/fused/moe_overlap.py index af6b501ce77..0526725a1d3 100644 --- a/transformer_engine/pytorch/ops/fused/moe_overlap.py +++ b/transformer_engine/pytorch/ops/fused/moe_overlap.py @@ -459,11 +459,14 @@ def empty(quantizer, cols): operands.transport_columnwise if fc2_ctx.weight_requires_grad else operands.transport, hidden, ) - grad_gemm = empty(operands.gemm_both, 2 * ffn) - # The columnwise grad_gemm_out feeds the FC1 weight gradient and act_out the FC2 one, so a - # frozen weight reads neither. TODO(phuonguyen): skip the unused one once the cuDNN FE dGLU - # kernel makes its columnwise D output optional (a generate_d_col flag like generate_h). - act_col = empty(operands.gemm_columnwise, ffn) + # The columnwise grad_gemm_out feeds the FC1 weight gradient and act_out the FC2 one, so + # the call writes neither for a frozen weight (the columnwise grad_gemm_out only where the + # cuDNN FE dGLU can leave it out). + grad_gemm_columnwise = fc1_ctx.weight_requires_grad or not _dglu_skips_column_outputs() + grad_gemm = empty( + operands.gemm_both if grad_gemm_columnwise else operands.gemm_rowwise, 2 * ffn + ) + act_col = empty(operands.gemm_columnwise, ffn) if fc2_ctx.weight_requires_grad else None grad_recv_weights = torch.empty(rows, dtype=torch.float32, device=device) grad_params = functools.partial( @@ -704,6 +707,15 @@ def _gemm_interface_reason(mxfp8: bool = False) -> Optional[str]: return gemm_interface_reason(mxfp8) +def _dglu_skips_column_outputs() -> bool: + """Whether the cuDNN FE MXFP8 dGLU can leave out the columnwise grad_gemm_out.""" + from ....common.CuTeDSL.ep_gemm._loader import ( # pylint: disable=import-outside-toplevel + dglu_skips_column_outputs, + ) + + return dglu_skips_column_outputs() + + def _mxfp8_quantizer(*, rowwise: bool, columnwise: bool, swizzled: bool) -> MXFP8Quantizer: """E4M3 quantizer of the MXFP8 EP transport and GEMM operands; it makes internal storages.""" quantizer = MXFP8Quantizer(DType.kFloat8E4M3, rowwise=rowwise, columnwise=columnwise) From 31f3e226d21c9d087ab4cc10a5ca10c443c7555f Mon Sep 17 00:00:00 2001 From: Phuong Nguyen Date: Mon, 30 Nov 2026 21:16:28 -0800 Subject: [PATCH 18/67] [PyTorch] Pass int64 expert offsets to the cuDNN FE grouped GEMMs Signed-off-by: Phuong Nguyen --- tests/pytorch/test_grouped_mlp.py | 100 ++++++++++++++++++ .../pytorch/ops/fused/grouped_mlp.py | 44 +++++--- 2 files changed, 130 insertions(+), 14 deletions(-) diff --git a/tests/pytorch/test_grouped_mlp.py b/tests/pytorch/test_grouped_mlp.py index 3f17f8f86c1..dfb6920d679 100644 --- a/tests/pytorch/test_grouped_mlp.py +++ b/tests/pytorch/test_grouped_mlp.py @@ -1829,6 +1829,75 @@ def test_grouped_mlp_glu_mxfp8_real_cudnn_fusion( ] assert traced_cudnn_grouped_glu_wrappers == expected_calls + @pytest.mark.skipif(not mxfp8_available, reason=reason_for_no_mxfp8) + @pytest.mark.parametrize( + "int64_offsets", + (False, True, None), + ids=("offsets_int32", "offsets_int64", "offsets_detected"), + ) + def test_grouped_mlp_mxfp8_offsets_dtype( + self, monkeypatch, int64_offsets: Optional[bool] + ) -> None: + """The cuDNN MXFP8 GEMMs take int64 offsets where the frontend accepts them. + + ``None`` keeps the dtype detected from the installed frontend. + """ + if not _cudnn_frontend_version_supported(): + pytest.skip("Requires cuDNN frontend >= 1.31.0") + if not device_is_blackwell: + pytest.skip("Requires Blackwell") + import cudnn + + supported = grouped_mlp_module._cudnn_frontend_supports_int64_offsets() + if int64_offsets and not supported: + pytest.skip("The cuDNN frontend takes only int32 offsets") + if int64_offsets is None: + int64_offsets = supported + else: + monkeypatch.setattr( + grouped_mlp_module, "_cudnn_frontend_supports_int64_offsets", lambda: int64_offsets + ) + offsets_dtypes = {} + for name, key in ( + ("grouped_gemm_glu_wrapper_sm100", "padded_offsets"), + ("grouped_gemm_dglu_wrapper_sm100", "padded_offsets"), + ("grouped_gemm_wgrad_wrapper_sm100", "offsets_tensor"), + ): + + def traced(*args, _wrapper=getattr(cudnn, name), _name=name, _key=key, **kwargs): + offsets_dtypes.setdefault(_name, set()).add(kwargs[_key].dtype) + return _wrapper(*args, **kwargs) + + monkeypatch.setattr(cudnn, name, traced) + fused_cls = te.ops.fused.GroupedMLP_CuTeGEMMGLU + _clear_grouped_glu_kernel_caches() + fused_cls.grouped_gemm_wgrad_kernel.cache_clear() + # FC2 bias-gradient accumulation uses an atomic Triton reduction. + monkeypatch.setenv("NVTE_ALLOW_NONDETERMINISTIC_ALGO", "1") + monkeypatch.delenv("NVTE_DISABLE_CUDNN_UNFUSED_GEMM_IN_GROUPED_MLP", raising=False) + monkeypatch.delenv("NVTE_DISABLE_CUTEDSL_WGRAD_FUSED_GROUPED_MLP", raising=False) + try: + self.test_grouped_mlp( + enable_fusion=True, + group_size=4, + bias=True, + hidden_size=128, + quantization="mxfp8", + single_grouped_weight=True, + activation="scaled_swiglu", + strict_fusion=True, + ) + torch.cuda.synchronize() + finally: + _clear_grouped_glu_kernel_caches() + fused_cls.grouped_gemm_wgrad_kernel.cache_clear() + expected = torch.int64 if int64_offsets else torch.int32 + assert offsets_dtypes == { + "grouped_gemm_glu_wrapper_sm100": {expected}, + "grouped_gemm_dglu_wrapper_sm100": {expected}, + "grouped_gemm_wgrad_wrapper_sm100": {expected}, + } + @pytest.mark.skipif(not nvfp4_available, reason=reason_for_no_nvfp4) @pytest.mark.parametrize("situ_betas", ((4.0, 25.0), (2.0, 8.0))) def test_grouped_mlp_situglu_nvfp4_real_cudnn_hadamard_fusion( @@ -4819,6 +4888,37 @@ def test_distributed_weight_dispatch(self) -> None: shard.main_grad.bfloat16(), ref_grad[: shard.shape[0]], rtol=0, atol=0 ) + def test_int64_offsets(self, monkeypatch) -> None: + """int64 cuDNN offsets give the results of int32 ones.""" + self._skip_unless_bf16_fusion() + if not grouped_mlp_module._cudnn_frontend_supports_int64_offsets(): + pytest.skip("The cuDNN frontend takes only int32 offsets") + fused_cls = grouped_mlp_module.GroupedMLP_CuTeGEMMGLUBf16 + num_groups = 2 + ops = _bf16_mlp_ops(num_groups=num_groups, single_grouped_weight=True) + split_sizes, x_ref, probs_ref = _bf16_mlp_inputs(ops, num_groups) + dy = torch.randn(x_ref.shape[0], ops[2].out_features, dtype=torch.bfloat16, device="cuda") + outs = [] + for int64_offsets in (False, True): + monkeypatch.setattr( + grouped_mlp_module, + "_cudnn_frontend_supports_int64_offsets", + lambda value=int64_offsets: value, + ) + model = te.ops.Sequential(*ops) + x = x_ref.clone().requires_grad_(True) + probs = probs_ref.clone().requires_grad_(True) + for p in model.parameters(): + p.grad = None + y = model(x, split_sizes, probs, split_sizes) + y.backward(dy) + assert isinstance(model._module_groups[0]._forward_ops[0][0], fused_cls) + outs.append((probs.grad, y, x.grad, *(p.grad for p in model.parameters()))) + # dprob is summed with atomics. + torch.testing.assert_close(outs[1][0], outs[0][0], **dtype_tols(torch.bfloat16)) + for got, want in zip(outs[1][1:], outs[0][1:]): + torch.testing.assert_close(got, want, rtol=0, atol=0) + @pytest.mark.parametrize( "fc1_scale_bias,fc2_scale_bias,should_fuse", ((False, True, True), (True, False, False), (True, True, False)), diff --git a/transformer_engine/pytorch/ops/fused/grouped_mlp.py b/transformer_engine/pytorch/ops/fused/grouped_mlp.py index e609a6e8bb5..c53c7f1ab5c 100644 --- a/transformer_engine/pytorch/ops/fused/grouped_mlp.py +++ b/transformer_engine/pytorch/ops/fused/grouped_mlp.py @@ -82,6 +82,21 @@ def _cudnn_frontend_version_supported() -> bool: return _cudnn_frontend_version_at_least("1.31.0") +@functools.lru_cache(maxsize=None) +def _cudnn_frontend_supports_int64_offsets() -> bool: + """Whether the cuDNN FE grouped GEMMs take int64 offsets as well as int32 ones.""" + try: + from cudnn.gemm.cutedsl import grouped # pylint: disable=import-outside-toplevel + except ImportError: + return False + return getattr(grouped, "INT64_OFFSETS", False) + + +def _cudnn_offsets_dtype() -> torch.dtype: + """Dtype of the expert offsets passed to the cuDNN FE grouped GEMMs.""" + return torch.int64 if _cudnn_frontend_supports_int64_offsets() else torch.int32 + + @functools.lru_cache(maxsize=None) def _cudnn_frontend_grouped_gemm_hadamard_supports(parameter: str) -> bool: """Whether the cuDNN FE grouped GEMM + Hadamard wrapper accepts ``parameter``. @@ -937,7 +952,8 @@ def _compute_grad_params( accumulate=accumulate_into_main_grad, ) elif cudnn_wgrad_kernel_fn is not None: - offsets = offsets if offsets.dtype == torch.int32 else offsets.to(dtype=torch.int32) + if offsets.dtype != torch.int32 and not _cudnn_frontend_supports_int64_offsets(): + offsets = offsets.to(dtype=torch.int32) gemm_fn = functools.partial( _cudnn_compute_wgrad, weight_shape=weight_shape, @@ -1388,11 +1404,15 @@ def fuser_forward( # Prepare split metadata if use_offsetless_metadata: - # cuDNN requires an int32 tensor descriptor, although its - # use_single_group_runtime_offsets specialization never loads the - # pointer. This view aliases the live caller-owned [M] int64 tensor, - # has value M, and requires no allocation or CUDA kernel. - split_points = split_sizes.view(torch.int32)[:1] + # The use_single_group_runtime_offsets specialization never loads + # the pointer. This aliases the live caller-owned [M] int64 tensor + # (an int32 view where cuDNN takes only int32 offsets), has value M, + # and requires no allocation or CUDA kernel. + split_points = ( + split_sizes[:1] + if _cudnn_frontend_supports_int64_offsets() + else split_sizes.view(torch.int32)[:1] + ) # Backward saves this slot for the generic path. The optimized # shared-expert path never consumes it. base_split_offsets = split_sizes @@ -1424,7 +1444,7 @@ def fuser_forward( ], include_leading_zero=[False, True, True, True, True, True], dtypes=[ - torch.int32, + _cudnn_offsets_dtype(), torch.int64, torch.int64, torch.int64, @@ -3820,7 +3840,7 @@ def fuser_forward( fc1_weight_requires_grad = requires_grad and fc1_weight_param.requires_grad fc2_weight_requires_grad = requires_grad and fc2_weight_param.requires_grad - # cuDNN padded offsets (int32) and dbias offsets (int64, leading zero). + # cuDNN padded offsets and dbias offsets (int64, leading zero). fc1_split_sizes = basic_op_extra_inputs[0][0] fc2_split_sizes = basic_op_extra_inputs[2][0] if ( @@ -3838,7 +3858,7 @@ def fuser_forward( device, strides=[1, 1], include_leading_zero=[False, True], - dtypes=[torch.int32, torch.int64], + dtypes=[_cudnn_offsets_dtype(), torch.int64], bulk_allocate=True, split_alignment=_BF16_M_ALIGNMENT, ) @@ -4104,11 +4124,7 @@ def fuser_backward( fc1_bias_grads = [fc1_dbias[idx] for idx in range(num_groups)] wgrad_kernel_fn = self.grouped_gemm_wgrad_kernel() - wgrad_offsets = ( - split_points - if split_points.dtype == torch.int32 - else split_points.to(dtype=torch.int32) - ) + wgrad_offsets = split_points # FC2 wgrad. fc2_grad_params = _compute_grad_params( From 54a81e93c2c2050f440cd3829357a813079cd68d Mon Sep 17 00:00:00 2001 From: Phuong Nguyen Date: Tue, 1 Dec 2026 10:00:02 -0800 Subject: [PATCH 19/67] [Common] Make NVTE_MOE_OVERLAP a 0/1 toggle and rename nvte_ep_overlap_workspace_size to nvte_ep_overlap_prepare Signed-off-by: Phuong Nguyen --- docs/api/pytorch.rst | 2 +- docs/envvars.rst | 23 ++---- tests/pytorch/distributed/run_test_ep.sh | 15 +--- tests/pytorch/test_ep_gemm.py | 4 +- .../cast/mxfp8/requantize_mxfp8_cutedsl.cuh | 2 +- transformer_engine/common/ep/ep_gemm_api.cpp | 22 +++--- .../include/transformer_engine/ep_gemm.h | 74 ++++++------------- .../pytorch/csrc/extensions/ep.cpp | 4 +- transformer_engine/pytorch/ep.py | 4 +- 9 files changed, 54 insertions(+), 96 deletions(-) diff --git a/docs/api/pytorch.rst b/docs/api/pytorch.rst index 2881da54ea7..c1d17c5541d 100644 --- a/docs/api/pytorch.rst +++ b/docs/api/pytorch.rst @@ -152,7 +152,7 @@ an ``EpBuffer``. A buffer holds the routing state of one call until its backward several calls in flight (for example pipeline microbatches) each need their own ``EpBuffer`` and op instance. The guide shows how to connect the per-expert counts and routing weights through the sequence's extra-tensor channels. With the overlap enabled (``NVTE_MOE_OVERLAP``) such a sequence -fuses into one op, or raises an error naming the reason when its settings are unsupported. +fuses into one op. If its settings are unsupported, an error names the reason. .. autoapiclass:: transformer_engine.pytorch.ops.MoeDispatch diff --git a/docs/envvars.rst b/docs/envvars.rst index 93d5233dd9e..ba8b2a89dbb 100644 --- a/docs/envvars.rst +++ b/docs/envvars.rst @@ -161,23 +161,16 @@ General ``WARN`` emits a warning explaining why CuTeDSL kernels are unavailable and falls back to CUDA kernels. ``ERROR`` raises an error and fails instead. Only effective when the CuTeDSL backend is enabled (see :envvar:`NVTE_ENABLE_CUTEDSL_BACKEND`). -.. - 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. - .. envvar:: NVTE_MOE_OVERLAP - :Type: ``str`` (directory) - :Default: unset (overlap off) - :Description: Directory of the CuTeDSL grouped GEMMs that overlap the NCCL EP dispatch and - combine with the expert GEMMs (``ep_gemm.h``, used by the fused - :class:`transformer_engine.pytorch.ops.MoeDispatch` expert MLP). The overlap is - off unless this is set together with ``NVTE_ENABLE_CUTEDSL_BACKEND=1``; then - ``ep_bootstrap`` defaults to 24 communication SMs unless ``max_num_sms`` is - given. If unset, the unfused ops run; if set, a dispatch, grouped MLP and combine - 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. + :Type: ``int`` (0 or 1) + :Default: ``0`` + :Description: Set to ``1`` to overlap the NCCL EP dispatch and combine with the expert grouped + GEMMs (``ep_gemm.h``, used by the fused + :class:`transformer_engine.pytorch.ops.MoeDispatch` expert MLP). Requires + ``NVTE_ENABLE_CUTEDSL_BACKEND=1`` and the CuTeDSL grouped GEMMs from the cuDNN + frontend. If ``0``, the unfused ops run; if ``1``, a dispatch, grouped MLP and + combine sequence that cannot run fused raises an error. .. envvar:: NVTE_GROUPED_TENSOR_HANDLE_POOL_SIZE_MB diff --git a/tests/pytorch/distributed/run_test_ep.sh b/tests/pytorch/distributed/run_test_ep.sh index b2e61e042b8..dbd141638c6 100755 --- a/tests/pytorch/distributed/run_test_ep.sh +++ b/tests/pytorch/distributed/run_test_ep.sh @@ -156,7 +156,7 @@ if [ $? -ne 0 ]; then cat "${PROBE_ERR}" OVERLAP_AVAILABLE=0 # A failed probe is not "unsupported": when the overlap was requested it is a failure. - if [ -n "${NVTE_MOE_OVERLAP:-}" ]; then + if [ "${NVTE_MOE_OVERLAP:-0}" != "0" ]; then echo "ERROR: the overlap availability probe failed with NVTE_MOE_OVERLAP set" RET=1 fi @@ -174,17 +174,8 @@ else NVTE_EP_COMM_SMS=12,20,24,16 run_pass "overlap_split_bwd" 0 0 0 1 0 1 # A hidden size that 1024 does not divide: the combine waits on whole rows. NVTE_EP_HIDDEN_DIM=1536 run_pass "overlap_h1536" 0 0 0 1 0 1 - # Expert alignments below 256 (MXFP8 cases skip at 64): an expert's last GEMM tile holds fewer - # rows. With 288 tokens per rank each expert also fills a whole tile; only the fused op tests run. - # TODO(phuonguyen): FusedMoE takes only alignment 256 until the cuDNN FE grouped GEMMs have - # tail-tile kernels; loop over 128 and 64 again then. - echo "SKIPPING the overlap passes at expert alignment 128 and 64: FusedMoE takes only 256." - for align in; 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 - done + # TODO(phuonguyen): FusedMoE takes only expert alignment 256 until the cuDNN FE grouped GEMMs + # have tail-tile kernels; add the alignment 128 and 64 passes back then. fi finish diff --git a/tests/pytorch/test_ep_gemm.py b/tests/pytorch/test_ep_gemm.py index 4fee11c9e6f..ff174b2be0f 100644 --- a/tests/pytorch/test_ep_gemm.py +++ b/tests/pytorch/test_ep_gemm.py @@ -14,8 +14,8 @@ # The optional CuTeDSL dependencies are imported only when the overlap is requested, where a # missing one fails the module. -if not os.environ.get("NVTE_MOE_OVERLAP"): - pytest.skip("NVTE_MOE_OVERLAP is not set", allow_module_level=True) +if os.environ.get("NVTE_MOE_OVERLAP", "0") == "0": + pytest.skip("NVTE_MOE_OVERLAP is not 1", allow_module_level=True) import tvm_ffi diff --git a/transformer_engine/common/cast/mxfp8/requantize_mxfp8_cutedsl.cuh b/transformer_engine/common/cast/mxfp8/requantize_mxfp8_cutedsl.cuh index 13b4af4bd2b..f1f649ed833 100644 --- a/transformer_engine/common/cast/mxfp8/requantize_mxfp8_cutedsl.cuh +++ b/transformer_engine/common/cast/mxfp8/requantize_mxfp8_cutedsl.cuh @@ -23,7 +23,7 @@ struct MXFP8RequantConfig { DType dtype; size_t rows, hidden, groups, uniform_rows; bool swizzled, rowwise_output, return_dequantized; - bool pdl = false; // run the warp-tile kernel as a programmatic dependent (EP overlap) + bool pdl = false; // run the warp-tile kernel as a programmatic dependent int sm_arch = cuda::sm_arch(); int sm_count = cuda::sm_count(); diff --git a/transformer_engine/common/ep/ep_gemm_api.cpp b/transformer_engine/common/ep/ep_gemm_api.cpp index bb4f3f1f0f6..51185f64364 100644 --- a/transformer_engine/common/ep/ep_gemm_api.cpp +++ b/transformer_engine/common/ep/ep_gemm_api.cpp @@ -155,7 +155,7 @@ ep::EpCombineGemmConfig combine_fwd_config(const EpGemmContext& ctx, size_t rows } // Per-call scratch for the GEMM's readiness flags and state, sliced from the caller's workspace. -// ScratchLayout is the byte layout; nvte_ep_overlap_workspace_size uses it to size the workspace +// ScratchLayout is the byte layout; nvte_ep_overlap_prepare uses it to size the workspace // without a buffer, and claim_scratch uses it to resolve the pointers in GemmScratch. struct ScratchLayout { size_t row_ends; // [num_experts] int32 per-expert row ends, the grouped GEMM layout operand @@ -197,7 +197,7 @@ GemmScratch claim_scratch(uint8_t* base, size_t workspace_bytes, size_t gemm_byt size_t num_experts, size_t rows, bool unit_probs, size_t wgrad_bytes) { const ScratchLayout l = scratch_layout(gemm_bytes, num_experts, rows, unit_probs, wgrad_bytes); NVTE_CHECK(l.total <= workspace_bytes, "the EP overlap workspace needs ", l.total, " bytes, got ", - workspace_bytes, "; size it with nvte_ep_overlap_workspace_size"); + workspace_bytes, "; size it with nvte_ep_overlap_prepare"); GemmScratch scratch{base}; if (wgrad_bytes > 0) { scratch.wgrad = base + l.wgrad; @@ -271,7 +271,7 @@ tvm::ffi::Function get_gemm(const Config& config, ep::WorkspaceLayout* layout) { auto kernel = config.get_kernel(); NVTE_CHECK(kernel.has_value(), "the EP grouped GEMM is not available: needs NVTE_ENABLE_CUTEDSL_BACKEND=1, " - "NVTE_MOE_OVERLAP and SM 10.0, 10.3 or 10.7"); + "NVTE_MOE_OVERLAP=1 and SM 10.0, 10.3 or 10.7"); const auto offsets = config.workspace_layout(); NVTE_CHECK(offsets.has_value(), "cannot query the GEMM workspace layout"); *layout = *offsets; @@ -446,7 +446,7 @@ void launch_requant(NVTETensor t, const GemmScratch& scratch, size_t rows, size_ cutedsl_backend::mxfp8_requantize_cutedsl(*in, out, nullptr, stream, /*pdl=*/true); NVTE_CHECK(ok, "the EP MXFP8 requant is not available: needs NVTE_ENABLE_CUTEDSL_BACKEND=1, " - "NVTE_MOE_OVERLAP and SM 10.0, 10.3 or 10.7"); + "NVTE_MOE_OVERLAP=1 and SM 10.0, 10.3 or 10.7"); } // Bytes of the chained weight-gradient workspace of a backward GEMM over num_experts slabs of @@ -481,7 +481,7 @@ size_t gemm_workspace_bytes(const Config& config) { const auto layout = config.workspace_layout(); NVTE_CHECK(layout.has_value(), "the EP grouped GEMM is not available: needs NVTE_ENABLE_CUTEDSL_BACKEND=1, " - "NVTE_MOE_OVERLAP and SM 10.0, 10.3 or 10.7"); + "NVTE_MOE_OVERLAP=1 and SM 10.0, 10.3 or 10.7"); return layout->total_bytes; } @@ -491,10 +491,10 @@ extern "C" { // Returns the max scratch over every op of the group, not per op: the scratch is small, so one // size that fits any call lets a caller size one workspace instead of querying each op. -size_t nvte_ep_overlap_workspace_size(size_t hidden_dim, size_t ffn_dim, size_t num_local_experts, - size_t recv_capacity, int with_weight_grad, int mxfp8, - const NVTEEpLayerConfig* layer_cfg) { - NVTE_API_CALL(nvte_ep_overlap_workspace_size); +size_t nvte_ep_overlap_prepare(size_t hidden_dim, size_t ffn_dim, size_t num_local_experts, + size_t recv_capacity, int with_weight_grad, int mxfp8, + const NVTEEpLayerConfig* layer_cfg) { + NVTE_API_CALL(nvte_ep_overlap_prepare); using namespace transformer_engine; const size_t ne = num_local_experts; const size_t rows = recv_capacity; @@ -1040,8 +1040,8 @@ namespace { extern "C" { -size_t nvte_ep_overlap_workspace_size(size_t, size_t, size_t, size_t, int, int, - const NVTEEpLayerConfig*) { +size_t nvte_ep_overlap_prepare(size_t, size_t, size_t, size_t, int, int, + const NVTEEpLayerConfig*) { ep_gemm_not_built(); } diff --git a/transformer_engine/common/include/transformer_engine/ep_gemm.h b/transformer_engine/common/include/transformer_engine/ep_gemm.h index 81cc320a733..37408f3da71 100644 --- a/transformer_engine/common/include/transformer_engine/ep_gemm.h +++ b/transformer_engine/common/include/transformer_engine/ep_gemm.h @@ -19,15 +19,26 @@ * * Overlap (each call draws its own schedule): * - Dispatch side: the dispatch leads, signaling each row tile; the GEMM consumes tiles beside - * it, then tails onto the SMs it frees. + * it (head), then runs its remaining tiles on all SMs once the dispatch frees its own (tail). * - Combine side: the GEMM leads. The forward combine follows the GEMM's hidden-column chunks * and takes the SMs it frees; the backward combine is unsignaled and overlaps only the weight * gradient. * - Backward C names overlap the opposite transfer (see the EP call column). * + * Requirements (all calls): + * - SM 10.0, 10.3 or 10.7; EP within one NVLink domain; num_comm_sms > 0; zero_copy off. + * - dispatch_output_per_expert_alignment: bfloat16 is 64, 128 or 256; MXFP8 is 256, or 128 + * except on SM 10.7. + * - NVTE_ENABLE_CUTEDSL_BACKEND=1 and NVTE_MOE_OVERLAP=1. + * - MXFP8: hidden_dim a multiple of 512, ffn_dim a multiple of 256. + * - First call per shape compiles its GEMM: run it at warmup, outside CUDA graph capture. + * - A group's calls on one stream, same order on every rank. A call throws otherwise. + * - A PDL kernel launched after nvte_ep_dispatch_gemm_bwd must wait before it reads the call's + * outputs. + * * SM budgets: NVTEEpGroupConfig *_num_sms fields (ep.h), set at nvte_ep_initialize, not layer_cfg. - * Workspace: caller-owned uint8, nvte_ep_overlap_workspace_size bytes. Each call resets it before - * use, so one buffer can be reused across the group's calls. + * Workspace: caller-owned uint8 of the size nvte_ep_overlap_prepare returns. Each call resets it + * before use, so one buffer can be reused across the group's calls. */ #ifndef TRANSFORMER_ENGINE_EP_GEMM_H_ @@ -54,15 +65,6 @@ extern "C" { * dispatch |--- deliver tiles ---| * FC1+SwiGLU |--- head ------------|--- tail ---| * - * Requirements: - * - SM 10.0, 10.3 or 10.7; EP within one NVLink domain; num_comm_sms > 0; zero_copy off. - * - dispatch_output_per_expert_alignment: bfloat16 is 64, 128 or 256; MXFP8 is 256, or 128 - * except on SM 10.7. - * - NVTE_ENABLE_CUTEDSL_BACKEND=1 and NVTE_MOE_OVERLAP set. - * - MXFP8: hidden_dim a multiple of 512, ffn_dim a multiple of 256. - * - First call per shape compiles its GEMM: run it at warmup, outside CUDA graph capture. - * - A group's calls on one stream, same order on every rank. A call throws otherwise. - * * \param[in,out] handle_mem uint8 routing-state buffer. * \param[in] topk_idx [T, top_k] int32 or int64 routing indices. * \param[in] tokens [T, hidden_dim] input tokens. @@ -91,7 +93,7 @@ extern "C" { * expert_token_offsets instead (no drops), it is * expert_token_offsets[-1], the padded total of the kept * rows. - * \param[in,out] workspace uint8 scratch, nvte_ep_overlap_workspace_size bytes. + * \param[in,out] workspace uint8 scratch of the size nvte_ep_overlap_prepare returns. * \param[in] activation Activation between the grouped GEMMs; only * NVTE_Activation_Type::SWIGLU is supported. * \param[in] layer_cfg Per-layer EP configuration. @@ -116,16 +118,7 @@ void nvte_ep_dispatch_gemm_fwd(NVTETensor handle_mem, const NVTETensor topk_idx, * * Schedule (FC2 leads, hidden chunks; combine_fwd_num_sms; time --->): * FC2 |--- head ---------------| - * combine |--- push chunks -----------------------------| - * - * Requirements: - * - SM 10.0, 10.3 or 10.7; EP within one NVLink domain; num_comm_sms > 0; zero_copy off. - * - dispatch_output_per_expert_alignment: bfloat16 is 64, 128 or 256; MXFP8 is 256, or 128 - * except on SM 10.7. - * - NVTE_ENABLE_CUTEDSL_BACKEND=1 and NVTE_MOE_OVERLAP set. - * - MXFP8: hidden_dim a multiple of 512, ffn_dim a multiple of 256. - * - First call per shape compiles its GEMM: run it at warmup, outside CUDA graph capture. - * - A group's calls on one stream, same order on every rank. A call throws otherwise. + * combine |--- push chunks ---------------| * * \param[in,out] handle_mem uint8 routing-state buffer. * \param[in] gemm_in [recv_capacity, ffn_dim] act_out of @@ -138,7 +131,7 @@ void nvte_ep_dispatch_gemm_fwd(NVTETensor handle_mem, const NVTETensor topk_idx, * \param[in] weight [num_local_experts, hidden_dim, ffn_dim] weights. * \param[out] expert_out [recv_capacity, hidden_dim] GEMM output. * \param[out] result [T, hidden_dim] combined output. - * \param[in,out] workspace uint8 scratch, nvte_ep_overlap_workspace_size bytes. + * \param[in,out] workspace uint8 scratch of the size nvte_ep_overlap_prepare returns. * \param[in] layer_cfg Per-layer EP configuration. * \param[in] stream CUDA stream. */ @@ -166,15 +159,6 @@ void nvte_ep_combine_gemm_fwd(NVTETensor handle_mem, const NVTETensor gemm_in, * bwd dispatch |--- deliver tiles ---| * dGLU |--- head ------------|--- tail ---| * - * Requirements: - * - SM 10.0, 10.3 or 10.7; EP within one NVLink domain; num_comm_sms > 0; zero_copy off. - * - dispatch_output_per_expert_alignment: bfloat16 is 64, 128 or 256; MXFP8 is 256, or 128 - * except on SM 10.7. - * - NVTE_ENABLE_CUTEDSL_BACKEND=1 and NVTE_MOE_OVERLAP set. - * - MXFP8: hidden_dim a multiple of 512, ffn_dim a multiple of 256. - * - First call per shape compiles its GEMM: run it at warmup, outside CUDA graph capture. - * - A group's calls on one stream, same order on every rank. A call throws otherwise. - * * \param[in,out] handle_mem uint8 routing-state buffer. * \param[in] grad_result [T, hidden_dim] gradient of result. * \param[in] grad_result_win Optional symm-mem window for grad_result (MXFP8: and, @@ -203,7 +187,7 @@ void nvte_ep_combine_gemm_fwd(NVTETensor handle_mem, const NVTETensor gemm_in, * \param[in,out] weight_grad [num_local_experts, hidden_dim, ffn_dim] bfloat16 or * float32 gradient of weight, or null. * \param[in] accumulate_weight_grad Add to weight_grad instead of writing it. - * \param[in,out] workspace uint8 scratch, nvte_ep_overlap_workspace_size bytes. + * \param[in,out] workspace uint8 scratch of the size nvte_ep_overlap_prepare returns. * \param[in] activation Activation whose backward runs between the grouped GEMMs; * only NVTE_Activation_Type::SWIGLU is supported. * \param[in] layer_cfg Per-layer EP configuration. @@ -234,16 +218,6 @@ void nvte_ep_combine_gemm_bwd( * combine | |--- return dX, dprob ---| * FC1 wgrad | |--- other SMs ----------| * - * Requirements: - * - SM 10.0, 10.3 or 10.7; EP within one NVLink domain; num_comm_sms > 0; zero_copy off. - * - A PDL kernel launched after the call must wait before it reads the call's outputs. - * - dispatch_output_per_expert_alignment: bfloat16 is 64, 128 or 256; MXFP8 is 256, or 128 - * except on SM 10.7. - * - NVTE_ENABLE_CUTEDSL_BACKEND=1 and NVTE_MOE_OVERLAP set. - * - MXFP8: hidden_dim a multiple of 512, ffn_dim a multiple of 256. - * - First call per shape compiles its GEMM: run it at warmup, outside CUDA graph capture. - * - A group's calls on one stream, same order on every rank. A call throws otherwise. - * * \param[in,out] handle_mem uint8 routing-state buffer. * \param[in] grad_gemm_out [recv_capacity, 2 * ffn_dim] from * nvte_ep_combine_gemm_bwd; MXFP8 with weight_grad: also @@ -263,7 +237,7 @@ void nvte_ep_combine_gemm_bwd( * \param[in,out] weight_grad [num_local_experts, 2 * ffn_dim, hidden_dim] bfloat16 or * float32 gradient of weight, or null. * \param[in] accumulate_weight_grad Add to weight_grad instead of writing it. - * \param[in,out] workspace uint8 scratch, nvte_ep_overlap_workspace_size bytes. + * \param[in,out] workspace uint8 scratch of the size nvte_ep_overlap_prepare returns. * \param[in] layer_cfg Per-layer EP configuration. * \param[in] stream CUDA stream. */ @@ -276,8 +250,8 @@ void nvte_ep_dispatch_gemm_bwd(NVTETensor handle_mem, const NVTETensor grad_gemm NVTETensor workspace, const NVTEEpLayerConfig* layer_cfg, cudaStream_t stream); -/*! \brief Bytes of a workspace that fits every overlapped GEMM call of a group. Queryable once the - * EP group is bootstrapped; call it at warmup, as it compiles the group's GEMMs. +/*! \brief Compile the group's overlapped GEMMs and return the bytes of a workspace that fits every + * call of the group. Queryable once the EP group is bootstrapped; call it at warmup. * * \param[in] hidden_dim Hidden size. * \param[in] ffn_dim Expert FFN size. @@ -288,9 +262,9 @@ void nvte_ep_dispatch_gemm_bwd(NVTETensor handle_mem, const NVTETensor grad_gemm * \param[in] layer_cfg Per-layer EP configuration. * \return Required workspace size in bytes. */ -size_t nvte_ep_overlap_workspace_size(size_t hidden_dim, size_t ffn_dim, size_t num_local_experts, - size_t recv_capacity, int with_weight_grad, int mxfp8, - const NVTEEpLayerConfig* layer_cfg); +size_t nvte_ep_overlap_prepare(size_t hidden_dim, size_t ffn_dim, size_t num_local_experts, + size_t recv_capacity, int with_weight_grad, int mxfp8, + const NVTEEpLayerConfig* layer_cfg); #ifdef __cplusplus } diff --git a/transformer_engine/pytorch/csrc/extensions/ep.cpp b/transformer_engine/pytorch/csrc/extensions/ep.cpp index 339007d2477..3192d0f633e 100644 --- a/transformer_engine/pytorch/csrc/extensions/ep.cpp +++ b/transformer_engine/pytorch/csrc/extensions/ep.cpp @@ -893,13 +893,13 @@ void ep_combine_bwd(at::Tensor handle_mem, at::Tensor grad, at::Tensor grad_expe } // Fresh per-call scratch for the overlapped GEMMs, sized for the group by -// nvte_ep_overlap_workspace_size. Allocated per call like the op's other IO tensors and kept alive +// nvte_ep_overlap_prepare. Allocated per call like the op's other IO tensors and kept alive // by the stream until the async GEMM completes; under graph capture it is served from the graph // pool, as those IO tensors are. at::Tensor overlap_workspace(int64_t hidden_dim, int64_t ffn_dim, int64_t num_local_experts, int64_t rows, bool with_weight_grad, bool mxfp8, const NVTEEpLayerConfig& layer_cfg, const at::Tensor& like) { - const int64_t bytes = static_cast(nvte_ep_overlap_workspace_size( + const int64_t bytes = static_cast(nvte_ep_overlap_prepare( hidden_dim, ffn_dim, num_local_experts, rows, with_weight_grad, mxfp8, &layer_cfg)); return at::empty({bytes}, like.options().dtype(at::kByte)); } diff --git a/transformer_engine/pytorch/ep.py b/transformer_engine/pytorch/ep.py index 312fee18e31..b98b9d9d46d 100644 --- a/transformer_engine/pytorch/ep.py +++ b/transformer_engine/pytorch/ep.py @@ -187,7 +187,7 @@ def ep_bootstrap( of trapping. Requires ``recv_capacity_per_rank``. ``max_num_sms`` defaults to 24 when the ``te.ops`` MoE overlap is available - (``NVTE_ENABLE_CUTEDSL_BACKEND=1``, ``NVTE_MOE_OVERLAP`` set) and ``zero_copy`` is off. + (``NVTE_ENABLE_CUTEDSL_BACKEND=1``, ``NVTE_MOE_OVERLAP=1``) and ``zero_copy`` is off. ``dispatch_fwd_num_sms``, ``combine_fwd_num_sms``, ``dispatch_bwd_num_sms`` and ``combine_bwd_num_sms`` set the SMs of the NCCL EP kernels of the dispatch and combine of the @@ -292,7 +292,7 @@ def _moe_overlap_available() -> bool: return ( get_device_compute_capability() in ((10, 0), (10, 3), (10, 7)) and os.environ.get("NVTE_ENABLE_CUTEDSL_BACKEND", "0") != "0" - and bool(os.environ.get("NVTE_MOE_OVERLAP")) + and os.environ.get("NVTE_MOE_OVERLAP", "0") != "0" and cutedsl_backend_built() ) From e94c0e44bb512c1d6d07f7e9a5da2ff69f1b0762 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Tue, 1 Dec 2026 18:11:43 +0000 Subject: [PATCH 20/67] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- transformer_engine/common/ep/ep_gemm_api.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/transformer_engine/common/ep/ep_gemm_api.cpp b/transformer_engine/common/ep/ep_gemm_api.cpp index 51185f64364..ba5343b92e7 100644 --- a/transformer_engine/common/ep/ep_gemm_api.cpp +++ b/transformer_engine/common/ep/ep_gemm_api.cpp @@ -1040,8 +1040,7 @@ namespace { extern "C" { -size_t nvte_ep_overlap_prepare(size_t, size_t, size_t, size_t, int, int, - const NVTEEpLayerConfig*) { +size_t nvte_ep_overlap_prepare(size_t, size_t, size_t, size_t, int, int, const NVTEEpLayerConfig*) { ep_gemm_not_built(); } From 8b3167b6c6b15860920ac6201a556a614aead4fc Mon Sep 17 00:00:00 2001 From: Phuong Nguyen Date: Tue, 1 Dec 2026 10:29:54 -0800 Subject: [PATCH 21/67] Clean up the MoE overlap alignment check, NVTE_MOE_OVERLAP wording and line widths, and test the toggle Signed-off-by: Phuong Nguyen --- docs/api/pytorch.rst | 2 +- .../pytorch/ep/bench/bench_moe_overlap.py | 2 +- tests/pytorch/distributed/run_ep.py | 2 +- tests/pytorch/distributed/run_test_ep.sh | 11 +++--- tests/pytorch/test_ep_gemm.py | 6 +-- tests/pytorch/test_nccl_ep_discovery.py | 38 +++++++++++++++++++ transformer_engine/common/ep/ep_gemm_api.cpp | 19 ++++------ .../include/transformer_engine/ep_gemm.h | 2 +- .../pytorch/ops/fused/moe_overlap.py | 17 +++------ 9 files changed, 64 insertions(+), 35 deletions(-) diff --git a/docs/api/pytorch.rst b/docs/api/pytorch.rst index c1d17c5541d..4e32113711c 100644 --- a/docs/api/pytorch.rst +++ b/docs/api/pytorch.rst @@ -151,7 +151,7 @@ NCCL-based dispatch and combine for experts sharded across ranks. See an ``EpBuffer``. A buffer holds the routing state of one call until its backward has run, so several calls in flight (for example pipeline microbatches) each need their own ``EpBuffer`` and op instance. The guide shows how to connect the per-expert counts and routing weights through the -sequence's extra-tensor channels. With the overlap enabled (``NVTE_MOE_OVERLAP``) such a sequence +sequence's extra-tensor channels. With the overlap enabled (``NVTE_MOE_OVERLAP=1``) such a sequence fuses into one op. If its settings are unsupported, an error names the reason. .. autoapiclass:: transformer_engine.pytorch.ops.MoeDispatch diff --git a/examples/pytorch/ep/bench/bench_moe_overlap.py b/examples/pytorch/ep/bench/bench_moe_overlap.py index bde9400fc38..f2b1f10181b 100644 --- a/examples/pytorch/ep/bench/bench_moe_overlap.py +++ b/examples/pytorch/ep/bench/bench_moe_overlap.py @@ -9,7 +9,7 @@ The op fuses an MoE MLP (dispatch, GroupedLinear, ScaledSwiGLU, GroupedLinear, combine) so the NCCL EP dispatch and combine overlap the expert GEMMs. Requires SM 10.0 or 10.3, an EP group -within one NVLink domain, NVTE_ENABLE_CUTEDSL_BACKEND=1 and NVTE_MOE_OVERLAP. The defaults match +within one NVLink domain, NVTE_ENABLE_CUTEDSL_BACKEND=1 and NVTE_MOE_OVERLAP=1. The defaults match the DeepSeek-V3 EP4 shape. """ diff --git a/tests/pytorch/distributed/run_ep.py b/tests/pytorch/distributed/run_ep.py index fd0a2668e04..2a0d17899d2 100644 --- a/tests/pytorch/distributed/run_ep.py +++ b/tests/pytorch/distributed/run_ep.py @@ -2161,7 +2161,7 @@ def _require_moe_overlap(self): if not moe_overlap.FusedMoE.is_supported(): self.skipTest( "FusedMoE needs SM 10.0, 10.3 or 10.7, NVTE_ENABLE_CUTEDSL_BACKEND=1," - " NVTE_MOE_OVERLAP and the BF16 cuDNN grouped GEMM kernels" + " NVTE_MOE_OVERLAP=1 and the BF16 cuDNN grouped GEMM kernels" ) @staticmethod diff --git a/tests/pytorch/distributed/run_test_ep.sh b/tests/pytorch/distributed/run_test_ep.sh index dbd141638c6..3c48bf907bf 100755 --- a/tests/pytorch/distributed/run_test_ep.sh +++ b/tests/pytorch/distributed/run_test_ep.sh @@ -99,7 +99,7 @@ run_pass() { echo "[${label}] SKIPPED: NCCL EP has no backward SM budgets" elif [ "${executed}" -lt "${NUM_RANKS}" ]; then echo "[${label}] ERROR: the fused overlap ops ran on ${executed} of ${NUM_RANKS} ranks;" \ - "set NVTE_ENABLE_CUTEDSL_BACKEND=1 and NVTE_MOE_OVERLAP" + "set NVTE_ENABLE_CUTEDSL_BACKEND=1 and NVTE_MOE_OVERLAP=1" RET=1 fi fi @@ -145,9 +145,9 @@ run_pass "fused_overflow" 0 0 1 0 1 run_pass "fused_mxfp8" 0 0 0 1 1 # Overlapped MoE ops (ep_gemm.h, te.ops FusedMoE): alignment 256, capacity and eager IO. Run only -# when the overlap is available (NVTE_ENABLE_CUTEDSL_BACKEND=1, NVTE_MOE_OVERLAP and SM 10.x). +# when the overlap is available (NVTE_ENABLE_CUTEDSL_BACKEND=1, NVTE_MOE_OVERLAP=1 and SM 10.x). # TODO(phuonguyen): once TE builds CuTeDSL by default and ships the cuDNN FE grouped GEMM kernels, -# set NVTE_ENABLE_CUTEDSL_BACKEND=1 and NVTE_MOE_OVERLAP here so the overlap passes run in CI +# set NVTE_ENABLE_CUTEDSL_BACKEND=1 and NVTE_MOE_OVERLAP=1 here so the overlap passes run in CI # instead of self-skipping. PROBE_ERR=$(mktemp) OVERLAP_AVAILABLE=$(python3 -c \ @@ -157,13 +157,14 @@ if [ $? -ne 0 ]; then OVERLAP_AVAILABLE=0 # A failed probe is not "unsupported": when the overlap was requested it is a failure. if [ "${NVTE_MOE_OVERLAP:-0}" != "0" ]; then - echo "ERROR: the overlap availability probe failed with NVTE_MOE_OVERLAP set" + echo "ERROR: the overlap availability probe failed with NVTE_MOE_OVERLAP=1" RET=1 fi fi rm -f "${PROBE_ERR}" if [ "${OVERLAP_AVAILABLE}" != "1" ]; then - echo "Overlapped MoE ops unavailable (needs NVTE_ENABLE_CUTEDSL_BACKEND=1, NVTE_MOE_OVERLAP, SM 10.x); SKIPPING overlap passes." + echo "Overlapped MoE ops unavailable (needs NVTE_ENABLE_CUTEDSL_BACKEND=1, NVTE_MOE_OVERLAP=1," \ + "SM 10.x); SKIPPING overlap passes." else run_pass "overlap" 0 0 0 1 0 1 run_pass "overlap_eager" 0 1 0 1 0 1 diff --git a/tests/pytorch/test_ep_gemm.py b/tests/pytorch/test_ep_gemm.py index ff174b2be0f..a9431938512 100644 --- a/tests/pytorch/test_ep_gemm.py +++ b/tests/pytorch/test_ep_gemm.py @@ -138,8 +138,7 @@ def _run_gemm(rows_per_expert, rows_alignment, mxfp8, tail_clusters, device_layo [ (TILE, False, [2 * TILE, TILE, 0, 3 * TILE]), (TILE, True, [2 * TILE, TILE, 0, 3 * TILE]), - # TODO(phuonguyen): cuDNN FE has no tail-tile kernels yet; restore the 64/128 alignment - # cases (experts padded below a full tile) once they land. + # TODO(phuonguyen): add the 64/128 alignment cases once cuDNN FE has tail-tile kernels. ], ) @pytest.mark.parametrize("tail_clusters", [0, 4]) @@ -218,8 +217,7 @@ def _run_combine(rows_per_expert, rows_alignment, mxfp8, backward): (False, True, TILE, [2 * TILE, TILE, 0, 3 * TILE]), (True, False, TILE, [2 * TILE, TILE, 0, 3 * TILE]), (True, True, TILE, [2 * TILE, TILE, 0, 3 * TILE]), - # TODO(phuonguyen): cuDNN FE has no tail-tile kernels yet; restore the 128 alignment case - # once they land. + # TODO(phuonguyen): add the 128 alignment case once cuDNN FE has tail-tile kernels. ], ) def test_combine_gemm_matches_reference(backward, mxfp8, rows_alignment, rows_per_expert): diff --git a/tests/pytorch/test_nccl_ep_discovery.py b/tests/pytorch/test_nccl_ep_discovery.py index ac7edbc3d0a..6fc20e72ee9 100644 --- a/tests/pytorch/test_nccl_ep_discovery.py +++ b/tests/pytorch/test_nccl_ep_discovery.py @@ -2,6 +2,8 @@ # # See LICENSE for license information. +import pytest + import transformer_engine @@ -58,3 +60,39 @@ def test_nccl_ep_library_not_found(monkeypatch): monkeypatch.setattr(transformer_engine, "find_library", lambda _: None) assert not transformer_engine._nccl_ep_library_installed() + + +@pytest.mark.parametrize("value,expected", [(None, False), ("0", False), ("1", True)]) +def test_moe_overlap_toggle(monkeypatch, value, expected): + from transformer_engine.pytorch import ep + + monkeypatch.setattr(ep.torch.cuda, "is_available", lambda: True) + monkeypatch.setattr(ep, "get_device_compute_capability", lambda: (10, 0)) + monkeypatch.setattr(ep, "cutedsl_backend_built", lambda: True) + monkeypatch.setenv("NVTE_ENABLE_CUTEDSL_BACKEND", "1") + if value is None: + monkeypatch.delenv("NVTE_MOE_OVERLAP", raising=False) + else: + monkeypatch.setenv("NVTE_MOE_OVERLAP", value) + assert ep._moe_overlap_available() is expected + + +def test_moe_overlap_rejects_unsupported_alignment(monkeypatch): + import torch + from transformer_engine.pytorch.ep import EpConfig + from transformer_engine.pytorch.ops.fused import moe_overlap + + monkeypatch.setattr(moe_overlap.FusedMoE, "is_supported", classmethod(lambda cls: True)) + config = EpConfig( + top_k=2, + hidden_dim=1024, + num_local_experts=4, + max_tokens_per_rank=256, + recv_capacity_per_rank=1024, + ep_group=None, + alignment=128, + ) + reason = moe_overlap._moe_overlap_unsupported_reason( + config, 1024, params_dtype=torch.bfloat16, glu_interleave_size=32 + ) + assert reason is not None and "alignment" in reason diff --git a/transformer_engine/common/ep/ep_gemm_api.cpp b/transformer_engine/common/ep/ep_gemm_api.cpp index ba5343b92e7..0785b0209b7 100644 --- a/transformer_engine/common/ep/ep_gemm_api.cpp +++ b/transformer_engine/common/ep/ep_gemm_api.cpp @@ -63,9 +63,6 @@ size_t combine_chunk(size_t n) { return n % 1024 == 0 ? 1024 : whole_row_chunk(n); } -// The combine (or dispatch backward) starts at the GEMM's entry and waits on its chunk flags. -constexpr bool kCombineAtGemmEntry = true; - // Group and layer state checked by every entry point. struct EpGemmContext { ep::EPBackend& backend; @@ -147,7 +144,7 @@ ep::EpCombineGemmConfig combine_fwd_config(const EpGemmContext& ctx, size_t rows num_experts, ctx.num_clusters, combine_chunk(n), - kCombineAtGemmEntry, + true, false, scaling_mode, ctx.alignment(), @@ -450,7 +447,7 @@ void launch_requant(NVTETensor t, const GemmScratch& scratch, size_t rows, size_ } // Bytes of the chained weight-gradient workspace of a backward GEMM over num_experts slabs of -// [m, n], as make_wgrad sizes it; the max over the output precisions, which the query does not know. +// [m, n], as make_wgrad sizes it; the max over the output precisions, which the query lacks. size_t wgrad_workspace_bytes(const EpGemmContext& ctx, size_t rows, size_t m, size_t n, size_t num_experts, NVTEScalingMode scaling_mode) { const size_t routed_tokens = @@ -501,8 +498,8 @@ size_t nvte_ep_overlap_prepare(size_t hidden_dim, size_t ffn_dim, size_t num_loc const NVTEScalingMode mx = mxfp8 != 0 ? NVTE_MXFP8_1D_SCALING : NVTE_DELAYED_TENSOR_SCALING; const bool wg = with_weight_grad != 0; size_t need = 0; - // Largest scratch of a call whose GEMM uses `config`; unit_probs sizes the per-row ones buffer and - // wgrad the weight-gradient workspace. + // Largest scratch of a call whose GEMM uses `config`; unit_probs sizes the per-row ones buffer + // and wgrad the weight-gradient workspace. const auto consider = [&](const auto& config, bool unit_probs, size_t wgrad) { need = std::max( need, scratch_layout(gemm_workspace_bytes(config), ne, rows, unit_probs, wgrad).total); @@ -536,7 +533,7 @@ size_t nvte_ep_overlap_prepare(size_t hidden_dim, size_t ffn_dim, size_t num_loc const size_t wgrad = wg ? wgrad_workspace_bytes(ctx, rows, 2 * ffn_dim, hidden_dim, ne, mx) : 0; consider(ep::EpCombineGemmConfig{rows, 2 * ffn_dim, hidden_dim, ne, wg ? ctx.all_clusters : ctx.num_clusters, n_chunk, - !plain && kCombineAtGemmEntry, true, mx, ctx.alignment()}, + !plain, true, mx, ctx.alignment()}, true, wgrad); } return need; @@ -953,8 +950,8 @@ void nvte_ep_dispatch_gemm_bwd(NVTETensor handle_mem, const NVTETensor grad_gemm const bool requant = wgrad && mxfp8 && nvte_get_tensor_param(wgrad_input, kNVTERowwiseData).data_ptr != nullptr; // With the weight gradient the dispatch backward starts behind the weight gradient's base, which - // waits for the GEMM to complete: the GEMM publishes nothing and runs in the stock tile order, and - // the one flag of the whole row is reset to 0, published. + // waits for the GEMM to complete: the GEMM publishes nothing and runs in the stock tile order, + // and the one flag of the whole row is reset to 0, published. const bool plain = wgrad && ctx.num_clusters > 0; const size_t n_chunk = plain ? 0 : combine_chunk(hidden); const size_t chunk = plain ? whole_row_chunk(hidden) : n_chunk; @@ -968,7 +965,7 @@ void nvte_ep_dispatch_gemm_bwd(NVTETensor handle_mem, const NVTETensor grad_gemm num_experts, wgrad ? ctx.all_clusters : ctx.num_clusters, n_chunk, - !plain && kCombineAtGemmEntry, + !plain, true, scaling_mode, ctx.alignment()}; diff --git a/transformer_engine/common/include/transformer_engine/ep_gemm.h b/transformer_engine/common/include/transformer_engine/ep_gemm.h index 37408f3da71..526b0cad580 100644 --- a/transformer_engine/common/include/transformer_engine/ep_gemm.h +++ b/transformer_engine/common/include/transformer_engine/ep_gemm.h @@ -28,7 +28,7 @@ * Requirements (all calls): * - SM 10.0, 10.3 or 10.7; EP within one NVLink domain; num_comm_sms > 0; zero_copy off. * - dispatch_output_per_expert_alignment: bfloat16 is 64, 128 or 256; MXFP8 is 256, or 128 - * except on SM 10.7. + * except on SM 10.7. The cuDNN FE kernels run alignment 256 only until they have tail tiles. * - NVTE_ENABLE_CUTEDSL_BACKEND=1 and NVTE_MOE_OVERLAP=1. * - MXFP8: hidden_dim a multiple of 512, ffn_dim a multiple of 256. * - First call per shape compiles its GEMM: run it at warmup, outside CUDA graph capture. diff --git a/transformer_engine/pytorch/ops/fused/moe_overlap.py b/transformer_engine/pytorch/ops/fused/moe_overlap.py index 0526725a1d3..54c10c9d925 100644 --- a/transformer_engine/pytorch/ops/fused/moe_overlap.py +++ b/transformer_engine/pytorch/ops/fused/moe_overlap.py @@ -84,8 +84,8 @@ class FusedMoE(FusedOperation): - Recipe of none or ``MXFP8BlockScaling``. Notes: - - With the overlap enabled (``NVTE_MOE_OVERLAP``), a ``Sequential`` of these ops that does not - meet the requirements raises an error naming the reason, instead of running unfused. + - With the overlap enabled (``NVTE_MOE_OVERLAP=1``), a ``Sequential`` of these ops that does + not meet the requirements raises an error naming the reason, instead of running unfused. - Each GEMM allocates a small uint8 workspace for its flags and state in the binding, freed after the call; the calls of an EP group must run on one CUDA stream. - With a fixed receive capacity the op can be captured in a CUDA graph after a warmup call; @@ -865,22 +865,17 @@ def _moe_overlap_unsupported_reason( """ if not FusedMoE.is_supported(): reason = ( - "needs SM 10.0, 10.3 or 10.7, NVTE_ENABLE_CUTEDSL_BACKEND=1, NVTE_MOE_OVERLAP and" + "needs SM 10.0, 10.3 or 10.7, NVTE_ENABLE_CUTEDSL_BACKEND=1, NVTE_MOE_OVERLAP=1 and" " the BF16 cuDNN grouped GEMM kernels" ) mismatch = _gemm_interface_reason() if _moe_overlap_available() else None return f"{reason}: {mismatch}" if mismatch else reason if config.payload_dtype is not torch.bfloat16: return "needs a BF16 payload" - alignments = (64, 128, _TILE) - if isinstance(recipe, MXFP8BlockScaling): - # The SM 10.7 MXFP8 GEMMs have no tail tiles. - alignments = (_TILE,) if get_device_compute_capability() == (10, 7) else (128, _TILE) # TODO(phuonguyen): the cuDNN FE grouped GEMMs have no tail-tile kernels, so every expert must - # pad to a full 256-row tile. Delete this line to restore 64/128 alignment once tail-tiles land. - alignments = (_TILE,) - if config.alignment not in alignments: - return f"the EP alignment must be one of {alignments}" + # pad to a full 256-row tile. Accept 64/128 alignment again once tail-tiles land. + if config.alignment != _TILE: + return f"the EP alignment must be {_TILE}" if config.zero_copy: return "zero-copy EP is not supported" if recipe is not None: From c458e504d95efb69c1800f4410ba77b1fd7d85cc Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Tue, 1 Dec 2026 18:55:52 +0000 Subject: [PATCH 22/67] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- transformer_engine/common/ep/ep_gemm_api.cpp | 17 +++++------------ 1 file changed, 5 insertions(+), 12 deletions(-) diff --git a/transformer_engine/common/ep/ep_gemm_api.cpp b/transformer_engine/common/ep/ep_gemm_api.cpp index 0785b0209b7..f6b94499d79 100644 --- a/transformer_engine/common/ep/ep_gemm_api.cpp +++ b/transformer_engine/common/ep/ep_gemm_api.cpp @@ -532,8 +532,8 @@ size_t nvte_ep_overlap_prepare(size_t hidden_dim, size_t ffn_dim, size_t num_loc const size_t n_chunk = plain ? 0 : combine_chunk(hidden_dim); const size_t wgrad = wg ? wgrad_workspace_bytes(ctx, rows, 2 * ffn_dim, hidden_dim, ne, mx) : 0; consider(ep::EpCombineGemmConfig{rows, 2 * ffn_dim, hidden_dim, ne, - wg ? ctx.all_clusters : ctx.num_clusters, n_chunk, - !plain, true, mx, ctx.alignment()}, + wg ? ctx.all_clusters : ctx.num_clusters, n_chunk, !plain, + true, mx, ctx.alignment()}, true, wgrad); } return need; @@ -959,16 +959,9 @@ void nvte_ep_dispatch_gemm_bwd(NVTETensor handle_mem, const NVTETensor grad_gemm // With the weight gradient the GEMM runs alone on every SM, and the weight gradient beside the // dispatch backward. ep::WorkspaceLayout layout; - const ep::EpCombineGemmConfig config{rows, - k, - hidden, - num_experts, - wgrad ? ctx.all_clusters : ctx.num_clusters, - n_chunk, - !plain, - true, - scaling_mode, - ctx.alignment()}; + const ep::EpCombineGemmConfig config{ + rows, k, hidden, num_experts, wgrad ? ctx.all_clusters : ctx.num_clusters, + n_chunk, !plain, true, scaling_mode, ctx.alignment()}; const tvm::ffi::Function gemm = get_gemm(config, &layout); GemmScratch scratch = claim_scratch(ws_base, ws_bytes, layout.total_bytes, num_experts, rows, true, wgrad ? wgrad->layout.total_bytes : 0); From b44c021f8c6a6dac87b400689ef9bbe8df29faef Mon Sep 17 00:00:00 2001 From: Phuong Nguyen Date: Tue, 1 Dec 2026 09:31:37 -0800 Subject: [PATCH 23/67] [Common] BF16 FC2 weight gradient waits per tile on the dispatch flags beside the dGLU when cuDNN FE has the wait Signed-off-by: Phuong Nguyen --- .../common/CuTeDSL/ep_gemm/_loader.py | 10 ++++ .../common/CuTeDSL/ep_gemm/wgrad_gemm.py | 55 +++++++++++++++---- transformer_engine/common/ep/ep_gemm_api.cpp | 19 +++++-- 3 files changed, 67 insertions(+), 17 deletions(-) diff --git a/transformer_engine/common/CuTeDSL/ep_gemm/_loader.py b/transformer_engine/common/CuTeDSL/ep_gemm/_loader.py index a74055a5436..bf3f2b21124 100644 --- a/transformer_engine/common/CuTeDSL/ep_gemm/_loader.py +++ b/transformer_engine/common/CuTeDSL/ep_gemm/_loader.py @@ -196,6 +196,16 @@ def dglu_skips_column_outputs() -> bool: return False +@functools.lru_cache(maxsize=None) +def bf16_wgrad_waits_on_signal() -> bool: + """Whether the SM 10.x BF16 weight gradient can wait per tile on a readiness signal (older + cuDNN frontends lack it).""" + try: + return getattr(importlib.import_module(_PKG), "BF16_WGRAD_STREAMING_SIGNAL", False) + except ImportError: + return False + + def unsupported_device_reason(what): """Why ``what`` cannot run on the current device, or None.""" if device_compute_capability() in GEMM_ARCHS: diff --git a/transformer_engine/common/CuTeDSL/ep_gemm/wgrad_gemm.py b/transformer_engine/common/CuTeDSL/ep_gemm/wgrad_gemm.py index 392ee77a0e9..8d0c1b67207 100644 --- a/transformer_engine/common/CuTeDSL/ep_gemm/wgrad_gemm.py +++ b/transformer_engine/common/CuTeDSL/ep_gemm/wgrad_gemm.py @@ -27,6 +27,7 @@ CLUSTER_MN, MMA_TILER_MN, SF_VEC_SIZE, + bf16_wgrad_waits_on_signal, fake_tensor, fp8_fake, import_gemm_modules, @@ -51,6 +52,7 @@ class WgradConfig: wait_primary_at_start: bool = False # wait for the kernel before it ahead of any load token_alignment: int = 0 # rows per expert slab are a multiple of it routed_tokens: int = 0 # rows a rank receives on average + signal_unit_tokens: int = 0 # rows per dispatch flag the launch takes, 0: none # Kernels, workspace layouts and compiled functions are specific to the device architecture. capability: tuple = field(default_factory=device_compute_capability) @@ -59,6 +61,12 @@ def mxfp8(self) -> bool: """Whether the operands are MXFP8 rather than BF16.""" return self.scaling_mode == MXFP8_1D_SCALING + @property + def waits_on_signal(self) -> bool: + """Whether each tile waits for the dispatch flags of its rows instead of the kernel before + it: BF16 with a cuDNN frontend that has the wait.""" + return self.signal_unit_tokens > 0 and not self.mxfp8 and bf16_wgrad_waits_on_signal() + def _mxfp8_kernels(): """(stock, global-descriptor, A-reuse) MXFP8 weight-gradient kernel classes of the device and @@ -127,10 +135,10 @@ def build_kernel(cfg: WgradConfig): A launch with ``wait_primary_at_start`` waits for the kernel before it, then lets the kernel behind it start. Another launch follows one that did and reads nothing the kernel before it writes: the global-descriptor kernels let the kernel behind them start at entry and wait at - exit; the others, which launch a helper kernel first, wait at start.""" - # TODO(phuonguyen): restore the wait on the dispatch readiness signal, a BF16 launch with no - # helper kernel in front and the 256 x 512 wide BF16 kernel on a shared counter once cuDNN FE - # adds them; correctness holds without them. + exit; the others, which launch a helper kernel first, wait at start. A BF16 launch that waits + on the dispatch flags instead starts beside the kernel before it and waits for it at exit.""" + # TODO(phuonguyen): use the 256 x 512 wide BF16 kernel on a shared counter once cuDNN FE adds + # it; correctness holds without it. common = dict( acc_dtype=cutlass.Float32, use_2cta_instrs=True, @@ -161,10 +169,14 @@ def build_kernel(cfg: WgradConfig): **common, ) module, moe_utils = import_gemm_modules("moe_grouped_gemm_wgrad") + if cfg.waits_on_signal: + common["pdl_mode"] = "trigger_then_wait_at_exit" + common["streaming_signal_rows"] = cfg.signal_unit_tokens + else: + common["launch_pdl_dependents_at_entry"] = cfg.wait_primary_at_start return module.MoEGroupedGemmWgradBF16Kernel( weight_mode=moe_utils.MoEWeightMode.DENSE, input_order=moe_utils.WGradInputOrder.Tensor2D, - launch_pdl_dependents_at_entry=cfg.wait_primary_at_start, **common, ) @@ -244,20 +256,41 @@ def launch(grad, x, weight_grad, expert_row_ends, workspace, counter, stream): a, b, out, expert_row_ends, workspace, num_clusters, stream, scheduler_counter=counter ) - return compile_launch(launch, *fakes) + if not cfg.signal_unit_tokens: + return compile_launch(launch, *fakes) + waits_on_signal = cfg.waits_on_signal + + @cute.jit + def launch_signal(grad, x, weight_grad, expert_row_ends, workspace, counter, signal, stream): + a, b, out = views(grad, x, weight_grad) + if cutlass.const_expr(waits_on_signal): + kernel( + a, b, out, expert_row_ends, workspace, num_clusters, stream, + scheduler_counter=counter, streaming_signal=signal, + ) # fmt: skip + else: + # A cuDNN frontend without the wait: the flags go unread. + kernel( + a, b, out, expert_row_ends, workspace, num_clusters, stream, + scheduler_counter=counter, + ) # fmt: skip + + signal_fake = fake_tensor(cutlass.Int32, (rows // cfg.signal_unit_tokens,), (0,), 4) + return compile_launch(launch_signal, *fakes, signal_fake) def _config( rows, m, n, num_experts, num_clusters, fp32_out, accumulate, wait_primary_at_start, signal_unit_tokens, scaling_mode, descriptors_only, token_alignment, routed_tokens, ): # fmt: skip - """Build a WgradConfig from the entry-point arguments. signal_unit_tokens and - descriptors_only select cuDNN FE kernels that do not exist (see build_kernel); they are - accepted for ABI stability and ignored.""" - del signal_unit_tokens, descriptors_only + """Build a WgradConfig from the entry-point arguments. descriptors_only selects a cuDNN FE + kernel that does not exist (see build_kernel); it is accepted for ABI stability and ignored. + A launch with signal_unit_tokens takes the dispatch flags, which it reads where the kernel + waits on them and ignores elsewhere (it then waits as wait_primary_at_start says).""" + del descriptors_only return WgradConfig( rows, m, n, num_experts, num_clusters, bool(fp32_out), bool(accumulate), int(scaling_mode), - bool(wait_primary_at_start), token_alignment, routed_tokens, + bool(wait_primary_at_start), token_alignment, routed_tokens, int(signal_unit_tokens), ) # fmt: skip diff --git a/transformer_engine/common/ep/ep_gemm_api.cpp b/transformer_engine/common/ep/ep_gemm_api.cpp index f6b94499d79..67d592a85d9 100644 --- a/transformer_engine/common/ep/ep_gemm_api.cpp +++ b/transformer_engine/common/ep/ep_gemm_api.cpp @@ -371,9 +371,11 @@ bool needs_descriptors(const Wgrad& wgrad) { // One launch of a weight gradient on num_clusters clusters (none: no launch), a programmatic // dependent of the kernel before it. Launches sharing the call's workspace split the tiles. -// wait_primary_at_start: no load before that kernel completes. signal_unit_tokens: no load before -// every dispatch flag of the expert rows is set. descriptors_only (MXFP8): a plain launch that -// writes the per-expert descriptors the other launches read; it follows the scratch reset. +// wait_primary_at_start: no load before that kernel completes. signal_unit_tokens (BF16): the +// launch takes the dispatch flags of that many rows each; where the kernel waits on them, no load +// before every flag of the expert rows is set, in place of wait_primary_at_start. +// descriptors_only (MXFP8): a plain launch that writes the per-expert descriptors the other +// launches read; it follows the scratch reset. void launch_wgrad(const Wgrad& wgrad, const GemmScratch& scratch, int num_clusters, bool wait_primary_at_start, size_t signal_unit_tokens, cudaStream_t stream, bool descriptors_only) { @@ -410,6 +412,11 @@ void launch_wgrad(const Wgrad& wgrad, const GemmScratch& scratch, int num_cluste } auto grad = wrap_rowwise(wgrad.grad, true); auto x = wrap_rowwise(wgrad.x, true); + if (signal_unit_tokens > 0) { + auto signal = wrap_raw(scratch.signal, kNVTEInt32, config.rows / signal_unit_tokens); + gemm(&grad, &x, &out, &row_ends, &ws, &counter, &signal, static_cast(stream)); + return; + } gemm(&grad, &x, &out, &row_ends, &ws, &counter, static_cast(stream)); } @@ -900,10 +907,10 @@ void nvte_ep_combine_gemm_bwd( } auto b = wrap_rowwise(weight, false); gemm(&a, &b, &c, &d, &dprob, &row_ends, &alpha, &prob, &ws, static_cast(stream)); - // The weight gradient once the GEMM completes, on every SM: a BF16 tail would wait for its base - // to complete, as the BF16 kernel launches a helper kernel in front of it. + // The weight gradient on every SM: beside the GEMM, each tile once the dispatch flags of its rows + // are set, where the kernel waits on them; else once the GEMM completes. if (wgrad) { - launch_wgrad(*wgrad, scratch, ctx.all_clusters, true, 0, stream, false); + launch_wgrad(*wgrad, scratch, ctx.all_clusters, true, ctx.signal_unit_tokens(), stream, false); } } From 2e146b3adbac711986575c42be3e50295da15b31 Mon Sep 17 00:00:00 2001 From: Phuong Nguyen Date: Tue, 1 Dec 2026 09:48:49 -0800 Subject: [PATCH 24/67] [Common] Run BF16 weight gradients that do not wait on the dispatch flags on the cuDNN FE 256 x 512 kernel Signed-off-by: Phuong Nguyen --- .../common/CuTeDSL/ep_gemm/_loader.py | 20 +++++++++++++++++ .../common/CuTeDSL/ep_gemm/wgrad_gemm.py | 22 ++++++++++++++++--- transformer_engine/common/ep/ep_gemm_api.cpp | 16 +++++++++----- 3 files changed, 49 insertions(+), 9 deletions(-) diff --git a/transformer_engine/common/CuTeDSL/ep_gemm/_loader.py b/transformer_engine/common/CuTeDSL/ep_gemm/_loader.py index bf3f2b21124..239d0349bd9 100644 --- a/transformer_engine/common/CuTeDSL/ep_gemm/_loader.py +++ b/transformer_engine/common/CuTeDSL/ep_gemm/_loader.py @@ -10,6 +10,7 @@ import functools import importlib +import inspect import logging from dataclasses import dataclass from typing import Optional @@ -54,6 +55,7 @@ "wgrad.moe_blockscaled_grouped_gemm_wgrad_reuse_rubin" ), "moe_grouped_gemm_wgrad": "wgrad.moe_grouped_gemm_wgrad", + "moe_grouped_gemm_wgrad_wide": "wgrad.moe_grouped_gemm_wgrad_wide", } @@ -206,6 +208,24 @@ def bf16_wgrad_waits_on_signal() -> bool: return False +@functools.lru_cache(maxsize=None) +def wide_bf16_wgrad_kernel(): + """The SM 10.x 256 x 512 BF16 weight-gradient kernel class when it claims from a caller's tile + counter and checks its shapes, else None (older cuDNN frontends).""" + try: + kernel_class = import_gemm_modules("moe_grouped_gemm_wgrad_wide")[0] + kernel_class = kernel_class.MoEGroupedGemmWgradWideBF16Kernel + except (ImportError, AttributeError): + return None + try: + params = inspect.signature(kernel_class.__call__).parameters + except (TypeError, ValueError): + return None + if "scheduler_counter" not in params or not hasattr(kernel_class, "can_implement"): + return None + return kernel_class + + def unsupported_device_reason(what): """Why ``what`` cannot run on the current device, or None.""" if device_compute_capability() in GEMM_ARCHS: diff --git a/transformer_engine/common/CuTeDSL/ep_gemm/wgrad_gemm.py b/transformer_engine/common/CuTeDSL/ep_gemm/wgrad_gemm.py index 8d0c1b67207..f36b5dbdb1e 100644 --- a/transformer_engine/common/CuTeDSL/ep_gemm/wgrad_gemm.py +++ b/transformer_engine/common/CuTeDSL/ep_gemm/wgrad_gemm.py @@ -34,6 +34,7 @@ is_sm107, register_function, scale_fake, + wide_bf16_wgrad_kernel, ) @@ -67,6 +68,15 @@ def waits_on_signal(self) -> bool: it: BF16 with a cuDNN frontend that has the wait.""" return self.signal_unit_tokens > 0 and not self.mxfp8 and bf16_wgrad_waits_on_signal() + @property + def wide(self) -> bool: + """Whether the launch runs the 256 x 512 BF16 kernel: a written BF16 weight gradient on + whose shape it implements, with no wait on the dispatch flags.""" + if self.mxfp8 or self.accumulate or self.fp32_out or self.waits_on_signal: + return False + kernel_class = wide_bf16_wgrad_kernel() + return kernel_class is not None and kernel_class.can_implement(self.m, self.n) + def _mxfp8_kernels(): """(stock, global-descriptor, A-reuse) MXFP8 weight-gradient kernel classes of the device and @@ -130,15 +140,14 @@ def reads_descriptors(cfg: WgradConfig) -> bool: def build_kernel(cfg: WgradConfig): """Weight-gradient kernel for ``cfg``. Persistent clusters claim output tiles from an atomic counter in the workspace, so launches sharing one workspace split the tiles across SMs. An - MXFP8 weight gradient written in BF16 reads A, B and the scales through global descriptors. + MXFP8 weight gradient written in BF16 reads A, B and the scales through global descriptors; a + BF16 one runs the 256 x 512 kernel where ``cfg.wide`` says. A launch with ``wait_primary_at_start`` waits for the kernel before it, then lets the kernel behind it start. Another launch follows one that did and reads nothing the kernel before it writes: the global-descriptor kernels let the kernel behind them start at entry and wait at exit; the others, which launch a helper kernel first, wait at start. A BF16 launch that waits on the dispatch flags instead starts beside the kernel before it and waits for it at exit.""" - # TODO(phuonguyen): use the 256 x 512 wide BF16 kernel on a shared counter once cuDNN FE adds - # it; correctness holds without it. common = dict( acc_dtype=cutlass.Float32, use_2cta_instrs=True, @@ -168,6 +177,13 @@ def build_kernel(cfg: WgradConfig): input_order=moe_utils.WGradInputOrder.Tensor2D, **common, ) + if cfg.wide: + return wide_bf16_wgrad_kernel()( + expert_cnt=cfg.num_experts, + atomic_counter_claim=True, + use_pdl=True, + launch_pdl_dependents_at_entry=cfg.wait_primary_at_start, + ) module, moe_utils = import_gemm_modules("moe_grouped_gemm_wgrad") if cfg.waits_on_signal: common["pdl_mode"] = "trigger_then_wait_at_exit" diff --git a/transformer_engine/common/ep/ep_gemm_api.cpp b/transformer_engine/common/ep/ep_gemm_api.cpp index 67d592a85d9..b7df333672f 100644 --- a/transformer_engine/common/ep/ep_gemm_api.cpp +++ b/transformer_engine/common/ep/ep_gemm_api.cpp @@ -299,10 +299,12 @@ struct Wgrad { }; // Checks the weight-gradient operands of a backward entry; nullopt without weight_grad. MXFP8 -// reads both operands columnwise. +// reads both operands columnwise. signal_unit_tokens: as its launches pass it, which can select +// another kernel and workspace layout. std::optional make_wgrad(const EpGemmContext& ctx, NVTETensor grad, NVTETensor x, NVTETensor weight_grad, bool accumulate, size_t rows, - size_t num_experts, NVTEScalingMode scaling_mode) { + size_t num_experts, NVTEScalingMode scaling_mode, + size_t signal_unit_tokens = 0) { const bool mxfp8 = transformer_engine::is_mxfp8_scaling(scaling_mode); if (weight_grad == nullptr) { NVTE_CHECK(x == nullptr, "wgrad_input needs weight_grad"); @@ -353,8 +355,8 @@ std::optional make_wgrad(const EpGemmContext& ctx, NVTETensor grad, NVTET Wgrad wgrad{grad, x, weight_grad, - {rows, m, n, num_experts, 1, out_type == kNVTEFloat32, accumulate, false, 0, - scaling_mode, false, ctx.alignment(), routed_tokens}, + {rows, m, n, num_experts, 1, out_type == kNVTEFloat32, accumulate, false, + signal_unit_tokens, scaling_mode, false, ctx.alignment(), routed_tokens}, {}}; const auto layout = wgrad.config.workspace_layout(); NVTE_CHECK(layout.has_value(), "cannot query the weight-gradient workspace layout"); @@ -812,9 +814,11 @@ void nvte_ep_combine_gemm_bwd( mxfp8 && nvte_get_tensor_param(grad_expert_out, kNVTEColumnwiseData).data_ptr != nullptr; NVTE_CHECK(!mxfp8 || weight_grad == nullptr || requant, "the MXFP8 weight gradient needs the columnwise grad_expert_out"); + // The BF16 weight gradient takes the dispatch flags. + const size_t wgrad_signal_tokens = mxfp8 ? 0 : ctx.signal_unit_tokens(); const std::optional wgrad = make_wgrad(ctx, grad_expert_out, wgrad_input, weight_grad, accumulate_weight_grad, rows, - num_experts, scaling_mode); + num_experts, scaling_mode, wgrad_signal_tokens); ep::WorkspaceLayout layout; ep::EpDispatchGemmConfig config{ @@ -910,7 +914,7 @@ void nvte_ep_combine_gemm_bwd( // The weight gradient on every SM: beside the GEMM, each tile once the dispatch flags of its rows // are set, where the kernel waits on them; else once the GEMM completes. if (wgrad) { - launch_wgrad(*wgrad, scratch, ctx.all_clusters, true, ctx.signal_unit_tokens(), stream, false); + launch_wgrad(*wgrad, scratch, ctx.all_clusters, true, wgrad_signal_tokens, stream, false); } } From be21d43b792f33b7a1ee111d7a90fed176af755a Mon Sep 17 00:00:00 2001 From: Phuong Nguyen Date: Tue, 1 Dec 2026 16:03:54 -0800 Subject: [PATCH 25/67] [Common][PyTorch] Take the MoE overlap expert offsets and counts from NCCL EP Signed-off-by: Phuong Nguyen --- tests/cpp_distributed/test_ep.cu | 20 +-- tests/pytorch/distributed/run_ep.py | 49 ++++- tests/pytorch/test_ep_gemm.py | 53 ++++-- .../common/CuTeDSL/ep_gemm/_loader.py | 35 +++- .../common/CuTeDSL/ep_gemm/combine_gemm.py | 25 +-- .../common/CuTeDSL/ep_gemm/dispatch_gemm.py | 21 ++- .../common/CuTeDSL/ep_gemm/wgrad_gemm.py | 14 +- transformer_engine/common/ep/ep_api.cpp | 8 +- transformer_engine/common/ep/ep_backend.cpp | 12 +- transformer_engine/common/ep/ep_backend.h | 4 +- transformer_engine/common/ep/ep_gemm_api.cpp | 167 ++++++++++-------- transformer_engine/common/ep/ep_gemm_config.h | 16 +- transformer_engine/common/ep/ep_gemm_utils.h | 30 +++- .../common/ep/ep_overlap_workspace.cu | 40 ++--- .../common/ep/ep_overlap_workspace.h | 18 +- .../common/include/transformer_engine/ep.h | 8 +- .../include/transformer_engine/ep_gemm.h | 38 ++-- transformer_engine/jax/csrc/extensions/ep.cpp | 2 +- transformer_engine/pytorch/csrc/extensions.h | 3 +- .../pytorch/csrc/extensions/ep.cpp | 89 +++++----- transformer_engine/pytorch/ep.py | 13 -- .../pytorch/ops/fused/moe_overlap.py | 80 +++++---- 22 files changed, 448 insertions(+), 297 deletions(-) diff --git a/tests/cpp_distributed/test_ep.cu b/tests/cpp_distributed/test_ep.cu index e1fddafe137..b94043c02f1 100644 --- a/tests/cpp_distributed/test_ep.cu +++ b/tests/cpp_distributed/test_ep.cu @@ -331,7 +331,7 @@ TYPED_TEST(EPDispatchTest, PrepareAndDispatch) { cudaStream_t stream; NVTE_CHECK_CUDA(cudaStreamCreate(&stream)); - ASSERT_NO_THROW(nvte_ep_prepare(t.handle_mem.data(), t.topk_idx.data(), t.recv_tokens_per_expert.data(), nullptr, &t.layer_cfg_, stream)); + ASSERT_NO_THROW(nvte_ep_prepare(t.handle_mem.data(), t.topk_idx.data(), t.recv_tokens_per_expert.data(), nullptr, nullptr, &t.layer_cfg_, stream)); ASSERT_NO_THROW(nvte_ep_dispatch(t.handle_mem.data(), t.topk_idx.data(), t.tokens.data(), NVTECommWindow{}, t.topk_weights.data(), NVTECommWindow{}, t.recv_tokens.data(), NVTECommWindow{}, @@ -456,7 +456,7 @@ TEST_F(EpOpTestBase, MXFP8DispatchScales) { cudaStream_t stream; NVTE_CHECK_CUDA(cudaStreamCreate(&stream)); ASSERT_NO_THROW(nvte_ep_prepare(t.handle_mem.data(), t.topk_idx.data(), - t.recv_tokens_per_expert.data(), nullptr, &t.layer_cfg_, stream)); + t.recv_tokens_per_expert.data(), nullptr, nullptr, &t.layer_cfg_, stream)); ASSERT_NO_THROW(nvte_ep_dispatch(t.handle_mem.data(), t.topk_idx.data(), tokens.data(), NVTECommWindow{}, t.topk_weights.data(), NVTECommWindow{}, recv_tokens.data(), NVTECommWindow{}, @@ -527,7 +527,7 @@ TYPED_TEST(EPCombineTest, Combine) { cudaStream_t stream; NVTE_CHECK_CUDA(cudaStreamCreate(&stream)); - ASSERT_NO_THROW(nvte_ep_prepare(t.handle_mem.data(), t.topk_idx.data(), t.recv_tokens_per_expert.data(), nullptr, &t.layer_cfg_, stream)); + ASSERT_NO_THROW(nvte_ep_prepare(t.handle_mem.data(), t.topk_idx.data(), t.recv_tokens_per_expert.data(), nullptr, nullptr, &t.layer_cfg_, stream)); ASSERT_NO_THROW(nvte_ep_dispatch(t.handle_mem.data(), t.topk_idx.data(), t.tokens.data(), NVTECommWindow{}, t.topk_weights.data(), NVTECommWindow{}, t.recv_tokens.data(), NVTECommWindow{}, @@ -570,7 +570,7 @@ TYPED_TEST(EPCombineTest, CombineV2) { NVTEEpLayerConfig cfg = t.layer_cfg_; cfg.topk_idx_dtype = kNVTEInt64; - ASSERT_NO_THROW(nvte_ep_prepare(t.handle_mem.data(), t.topk_idx.data(), t.recv_tokens_per_expert.data(), nullptr, &cfg, stream)); + ASSERT_NO_THROW(nvte_ep_prepare(t.handle_mem.data(), t.topk_idx.data(), t.recv_tokens_per_expert.data(), nullptr, nullptr, &cfg, stream)); ASSERT_NO_THROW(nvte_ep_dispatch_v2(t.handle_mem.data(), t.topk_idx.data(), t.tokens.data(), NVTECommWindow{}, t.topk_weights.data(), NVTECommWindow{}, t.recv_tokens.data(), NVTECommWindow{}, @@ -614,7 +614,7 @@ TYPED_TEST(EPCombineBwdTest, CombineBwdCheck) { cudaStream_t stream; NVTE_CHECK_CUDA(cudaStreamCreate(&stream)); - ASSERT_NO_THROW(nvte_ep_prepare(t.handle_mem.data(), t.topk_idx.data(), t.recv_tokens_per_expert.data(), nullptr, &t.layer_cfg_, stream)); + ASSERT_NO_THROW(nvte_ep_prepare(t.handle_mem.data(), t.topk_idx.data(), t.recv_tokens_per_expert.data(), nullptr, nullptr, &t.layer_cfg_, stream)); ASSERT_NO_THROW(nvte_ep_dispatch(t.handle_mem.data(), t.topk_idx.data(), t.tokens.data(), NVTECommWindow{}, t.topk_weights.data(), NVTECommWindow{}, t.recv_tokens.data(), NVTECommWindow{}, @@ -683,7 +683,7 @@ TYPED_TEST(EPDispatchBwdTest, DispatchBwdCheck) { cudaStream_t stream; NVTE_CHECK_CUDA(cudaStreamCreate(&stream)); - ASSERT_NO_THROW(nvte_ep_prepare(t.handle_mem.data(), t.topk_idx.data(), t.recv_tokens_per_expert.data(), nullptr, &t.layer_cfg_, stream)); + ASSERT_NO_THROW(nvte_ep_prepare(t.handle_mem.data(), t.topk_idx.data(), t.recv_tokens_per_expert.data(), nullptr, nullptr, &t.layer_cfg_, stream)); ASSERT_NO_THROW(nvte_ep_dispatch(t.handle_mem.data(), t.topk_idx.data(), t.tokens.data(), NVTECommWindow{}, t.topk_weights.data(), NVTECommWindow{}, t.recv_tokens.data(), NVTECommWindow{}, @@ -751,7 +751,7 @@ TYPED_TEST(EPDispatchBwdGradWeightsTest, RoundTrip) { cudaStream_t stream; NVTE_CHECK_CUDA(cudaStreamCreate(&stream)); - ASSERT_NO_THROW(nvte_ep_prepare(t.handle_mem.data(), t.topk_idx.data(), t.recv_tokens_per_expert.data(), nullptr, &t.layer_cfg_, stream)); + ASSERT_NO_THROW(nvte_ep_prepare(t.handle_mem.data(), t.topk_idx.data(), t.recv_tokens_per_expert.data(), nullptr, nullptr, &t.layer_cfg_, stream)); NVTE_CHECK_CUDA(cudaMemsetAsync(buf.recv_topk_weights.get(), 0, buf.recv_topk_weights.bytes(), stream)); ASSERT_NO_THROW(nvte_ep_dispatch(t.handle_mem.data(), t.topk_idx.data(), @@ -822,7 +822,7 @@ class EPPipelineTest : public EpOpTestBase, public ::testing::WithParamInterface cudaStream_t stream; NVTE_CHECK_CUDA(cudaStreamCreate(&stream)); - ASSERT_NO_THROW(nvte_ep_prepare(t.handle_mem.data(), t.topk_idx.data(), t.recv_tokens_per_expert.data(), nullptr, &t.layer_cfg_, stream)); + ASSERT_NO_THROW(nvte_ep_prepare(t.handle_mem.data(), t.topk_idx.data(), t.recv_tokens_per_expert.data(), nullptr, nullptr, &t.layer_cfg_, stream)); ASSERT_NO_THROW(nvte_ep_dispatch(t.handle_mem.data(), t.topk_idx.data(), t.tokens.data(), NVTECommWindow{}, t.topk_weights.data(), NVTECommWindow{}, t.recv_tokens.data(), NVTECommWindow{}, @@ -948,7 +948,7 @@ TYPED_TEST(EPZeroCopyTest, IdentityAllSymm) { cudaStream_t stream; NVTE_CHECK_CUDA(cudaStreamCreate(&stream)); - ASSERT_NO_THROW(nvte_ep_prepare(ref_t.handle_mem.data(), ref_t.topk_idx.data(), ref_t.recv_tokens_per_expert.data(), nullptr, &ref_t.layer_cfg_, stream)); + ASSERT_NO_THROW(nvte_ep_prepare(ref_t.handle_mem.data(), ref_t.topk_idx.data(), ref_t.recv_tokens_per_expert.data(), nullptr, nullptr, &ref_t.layer_cfg_, stream)); ASSERT_NO_THROW(nvte_ep_dispatch(ref_t.handle_mem.data(), ref_t.topk_idx.data(), ref_t.tokens.data(), NVTECommWindow{}, ref_t.topk_weights.data(), NVTECommWindow{}, ref_t.recv_tokens.data(), NVTECommWindow{}, @@ -986,7 +986,7 @@ TYPED_TEST(EPZeroCopyTest, IdentityAllSymm) { sym_t.recv_tokens = TensorWrapper(sym_recv.ptr, std::vector{sym_buf.recv_capacity, (size_t)hidden_dim_}, kTokDType); - ASSERT_NO_THROW(nvte_ep_prepare(sym_t.handle_mem.data(), sym_t.topk_idx.data(), sym_t.recv_tokens_per_expert.data(), nullptr, &sym_t.layer_cfg_, stream)); + ASSERT_NO_THROW(nvte_ep_prepare(sym_t.handle_mem.data(), sym_t.topk_idx.data(), sym_t.recv_tokens_per_expert.data(), nullptr, nullptr, &sym_t.layer_cfg_, stream)); ASSERT_NO_THROW(nvte_ep_dispatch(sym_t.handle_mem.data(), sym_t.topk_idx.data(), sym_t.tokens.data(), symm_window(sym_tokens), sym_t.topk_weights.data(), NVTECommWindow{}, diff --git a/tests/pytorch/distributed/run_ep.py b/tests/pytorch/distributed/run_ep.py index 2a0d17899d2..101ff06398f 100644 --- a/tests/pytorch/distributed/run_ep.py +++ b/tests/pytorch/distributed/run_ep.py @@ -1971,10 +1971,6 @@ def run(fused): # Each run publishes its own counts: a stale value would show. buffer.tokens_per_expert.fill_(-1) buffer.total_recv_tokens.fill_(-1) - if fused: - # The fused op uses its own counts and recv total, not the reference's. - buffer.tokens_per_expert_i32.fill_(-1) - buffer.total_recv_tokens_i32.fill_(-1) # Paged stashing pages the tensors that carry a token count. stashable = [] num_tokens = [] @@ -2042,7 +2038,7 @@ def pack(tensor): stashed = 4 - (fc1_inputs if 1 in frozen else 0) - (fc2_inputs if 3 in frozen else 0) self.assertEqual(len(out[5]), stashed, "the fused op saves the stashable tensors") # Their token count is the number of received rows kept. - kept = int(buffer.tokens_per_expert_i32.sum()) + kept = int(buffer.tokens_per_expert.sum()) self.assertEqual(out[6], [kept] * stashed, "stashed token counts") # The fused op publishes the buffer counters as the unfused ops do: the kept tokens per # expert and the recv total before any drop, which exceeds the kept total on overflow. @@ -2346,6 +2342,49 @@ def test_moe_overlap_rank_without_tokens(self): if has_tokens: self.assertGreater(int(per_expert[0].count_nonzero()), 0) + @_eager_test_include + @_overflow_test_include + @_mxfp8_align_test + @_overlap_test + def test_moe_overlap_int32_counts(self): + """With int32 per-expert counts and recv total the fused op matches its int64 run, and + the overlapped dispatch refuses counts and expert offsets of different dtypes.""" + from transformer_engine.pytorch.ops.fused import moe_overlap + + self._require_moe_overlap() + config = self._overlap_config() + buffer = self._make_buffer_from_config(config) + ops = self._moe_ops(config, buffer) + tokens, topk_idx, w, grad = self._moe_calls(1)[0] + results = [] + for dtype in (torch.int64, torch.int32): + total = buffer.total_recv_tokens + buffer.tokens_per_expert = buffer.tokens_per_expert.to(dtype) + buffer.total_recv_tokens = torch.empty( + 1, dtype=dtype, device=total.device, pin_memory=total.is_pinned() + ) + for p in ops[1].parameters(): + p.grad = None + for p in ops[3].parameters(): + p.grad = None + model = te_ops.Sequential(*ops) + out = self._moe_call(model, tokens, topk_idx, w, grad) + torch.cuda.synchronize() + self.assertTrue(self._moe_overlap_selected(model)) + results.append((out, self._param_grads(model))) + self._assert_moe_close(results[1], results[0]) + + dispatch_gemm_fwd = moe_overlap.tex.ep_dispatch_gemm_fwd + + def int64_offsets(*args, **kwargs): + offsets = args[8] + mixed = torch.zeros(offsets.numel() + 1, dtype=torch.int64, device=offsets.device) + return dispatch_gemm_fwd(*args[:8], mixed[1:], *args[9:], **kwargs) + + with mock.patch.object(moe_overlap.tex, "ep_dispatch_gemm_fwd", side_effect=int64_offsets): + with self.assertRaisesRegex(RuntimeError, "must share a dtype"): + self._moe_call(te_ops.Sequential(*ops), tokens, topk_idx, w, None) + @_mxfp8_align_test @_overlap_test def test_moe_overlap_cuda_graph(self): diff --git a/tests/pytorch/test_ep_gemm.py b/tests/pytorch/test_ep_gemm.py index a9431938512..3a481c46ad5 100644 --- a/tests/pytorch/test_ep_gemm.py +++ b/tests/pytorch/test_ep_gemm.py @@ -7,6 +7,7 @@ # pylint: disable=wrong-import-position import ctypes +import importlib import os import pytest @@ -20,6 +21,7 @@ import tvm_ffi from transformer_engine.common.CuTeDSL.ep_gemm import ( + _loader, combine_gemm, dispatch_gemm, wgrad_gemm, @@ -43,11 +45,14 @@ def _unit_e8m0(count, device): return torch.full((count,), 127, dtype=torch.uint8, device=device).view(torch.float8_e8m0fnu) -def _run_gemm(rows_per_expert, rows_alignment, mxfp8, tail_clusters, device_layout): +def _run_gemm( + rows_per_expert, rows_alignment, mxfp8, tail_clusters, device_layout, int64_offsets=False +): """Launch the forward GEMM with every row tile ready, and with ``tail_clusters`` a second launch behind it on the same workspace; return (a, b, alpha, prob, c, d, claims) with MXFP8 operands at unit scales in float32, the MXFP8 ``d`` dequantized and the final claim counter. - ``device_layout``: the row ends follow expert 0's offset, as the dispatch writes them.""" + ``device_layout``: the row ends follow expert 0's offset, as the dispatch writes them. + ``int64_offsets``: the row ends are int64.""" device = torch.device("cuda") hidden, n, experts = 1024, 1024, len(rows_per_expert) rows = sum(rows_per_expert) + TILE # spare tile: the capacity exceeds the rows in use @@ -61,6 +66,7 @@ def _run_gemm(rows_per_expert, rows_alignment, mxfp8, tail_clusters, device_layo scaling_mode=scaling_mode, token_alignment=rows_alignment, device_layout=device_layout, + int64_offsets=int64_offsets, ) launches = [] for num_clusters in (cfg.num_clusters, tail_clusters): @@ -68,6 +74,7 @@ def _run_gemm(rows_per_expert, rows_alignment, mxfp8, tail_clusters, device_layo continue name = ( f"test_ep_gemm_{rows}_{rows_alignment}_{int(mxfp8)}_{num_clusters}_{int(device_layout)}" + f"_{int(int64_offsets)}" ) assert dispatch_gemm.get_ep_dispatch_gemm_function( name, @@ -80,6 +87,7 @@ def _run_gemm(rows_per_expert, rows_alignment, mxfp8, tail_clusters, device_layo mxfp8, rows_alignment, device_layout, + int64_offsets=int64_offsets, ) launches.append(tvm_ffi.get_global_func(name)) @@ -90,12 +98,14 @@ def _run_gemm(rows_per_expert, rows_alignment, mxfp8, tail_clusters, device_layo # Powers of two: alpha and prob cost no tolerance. alpha = torch.pow(2.0, (torch.arange(experts, device=device) % 5 - 2).float()) prob = torch.pow(2.0, (torch.arange(rows, device=device) % 3 - 1).float()) - ends = torch.tensor(rows_per_expert, device=device).cumsum(0).to(torch.int32) + offsets_type = torch.int64 if int64_offsets else torch.int32 + ends = torch.tensor(rows_per_expert, device=device).cumsum(0).to(offsets_type) if device_layout: - # Offsets then the total: expert 0's offset is the word before the 16-byte aligned ends. - layout = torch.zeros(4 + experts, dtype=torch.int32, device=device) - layout[4:] = ends - ends = layout[4:] + # Offsets then the total: expert 0's offset is the entry before the 16-byte aligned ends. + pad = 16 // ends.element_size() + layout = torch.zeros(pad + experts, dtype=offsets_type, device=device) + layout[pad:] = ends + ends = layout[pad:] d_cols = n // 2 c = torch.zeros(rows, n, dtype=torch.bfloat16, device=device) d = torch.zeros(rows, d_cols, dtype=dtype, device=device) @@ -143,18 +153,20 @@ def _run_gemm(rows_per_expert, rows_alignment, mxfp8, tail_clusters, device_layo ) @pytest.mark.parametrize("tail_clusters", [0, 4]) @pytest.mark.parametrize("device_layout", [False, True]) +@pytest.mark.parametrize("int64_offsets", [False, True]) def test_dispatch_gemm_matches_reference( - rows_alignment, mxfp8, rows_per_expert, tail_clusters, device_layout + rows_alignment, mxfp8, rows_per_expert, tail_clusters, device_layout, int64_offsets ): """Grouped GEMM over padded slabs matches a float32 reference, also with experts padded to - fewer rows than a tile, with a tail launch sharing the tiles and with the dispatch-written - layout; rows past the last expert stay 0.""" - a, b, alpha, prob, c, d, claims = _run_gemm( - rows_per_expert, rows_alignment, mxfp8, tail_clusters, device_layout - ) + fewer rows than a tile, with a tail launch sharing the tiles, with the dispatch-written + layout and with int64 row ends; rows past the last expert stay 0.""" + if int64_offsets and not _loader.int64_offsets_supported(): + pytest.skip("the cuDNN frontend takes int32 expert offsets only") + args = (rows_per_expert, rows_alignment, mxfp8) + a, b, alpha, prob, c, d, claims = _run_gemm(*args, tail_clusters, device_layout, int64_offsets) if tail_clusters: # The tail's schedulers claimed from the counter they share with the base's. - assert claims > _run_gemm(rows_per_expert, rows_alignment, mxfp8, 0, device_layout)[-1] + assert claims > _run_gemm(*args, 0, device_layout, int64_offsets)[-1] used = sum(rows_per_expert) ref_c = torch.zeros(a.shape[0], b.shape[1], dtype=torch.float32, device=a.device) start = 0 @@ -171,6 +183,19 @@ def test_dispatch_gemm_matches_reference( assert torch.count_nonzero(got[used:]) == 0 +def test_int64_offsets_needs_frontend_support(monkeypatch): + """A cuDNN frontend without INT64_OFFSETS is refused for int64 expert offsets only.""" + monkeypatch.delattr(importlib.import_module(_loader._PKG), "INT64_OFFSETS", raising=False) + _loader._gemm_interface_reason.cache_clear() + try: + assert "INT64_OFFSETS" in (_loader.gemm_interface_reason(int64_offsets=True) or "") + assert "INT64_OFFSETS" not in (_loader.gemm_interface_reason() or "") + with pytest.raises(RuntimeError, match="INT64_OFFSETS"): + _loader.offsets_dtype(True) + finally: + _loader._gemm_interface_reason.cache_clear() + + def _run_combine(rows_per_expert, rows_alignment, mxfp8, backward): """Launch the combine GEMM over padded slabs and return (a, b, alpha, prob, d, used) with MXFP8 operands at unit scales in float32. The forward weight is [E, n, k], backward [E, k, n]; diff --git a/transformer_engine/common/CuTeDSL/ep_gemm/_loader.py b/transformer_engine/common/CuTeDSL/ep_gemm/_loader.py index 239d0349bd9..19d2543ad72 100644 --- a/transformer_engine/common/CuTeDSL/ep_gemm/_loader.py +++ b/transformer_engine/common/CuTeDSL/ep_gemm/_loader.py @@ -155,10 +155,15 @@ def _missing(obj, dotted_names): @functools.lru_cache(maxsize=None) -def _gemm_interface_reason(capability, mxfp8): +def _gemm_interface_reason(capability, mxfp8, int64_offsets): del capability # The cache key: the architecture the checks ran on. problems = [] try: + if int64_offsets and not int64_offsets_supported(): + problems.append( + f"{_PKG} lacks INT64_OFFSETS: install a cuDNN frontend whose grouped GEMMs take" + " int64 expert offsets" + ) for name, attributes in _SHARED_INTERFACE.items(): missing = _missing(import_gemm_modules(name)[0], attributes) if missing: @@ -182,10 +187,19 @@ def _gemm_interface_reason(capability, mxfp8): return None -def gemm_interface_reason(mxfp8=False) -> Optional[str]: +def gemm_interface_reason(mxfp8=False, int64_offsets=False) -> Optional[str]: """Why the installed cuDNN frontend lacks what the EP grouped GEMMs read, or None; ``mxfp8`` - also checks the MXFP8 kernels. Checked once per architecture and recipe.""" - return _gemm_interface_reason(device_compute_capability(), mxfp8) + also checks the MXFP8 kernels, ``int64_offsets`` int64 expert offsets. Checked once per + architecture and setting.""" + return _gemm_interface_reason(device_compute_capability(), mxfp8, int64_offsets) + + +def int64_offsets_supported() -> bool: + """Whether the cuDNN frontend grouped GEMMs take int64 expert offsets (int32 always works).""" + try: + return getattr(importlib.import_module(_PKG), "INT64_OFFSETS", False) + except ImportError: + return False @functools.lru_cache(maxsize=None) @@ -322,12 +336,21 @@ def mxfp8_tail_tile_kwargs(token_alignment): return {} -def tail_fakes(rows, experts, ws_bytes): +def offsets_dtype(int64_offsets): + """CuTe dtype of the expert row ends: Int64 needs a cuDNN frontend with INT64_OFFSETS.""" + import cutlass # pylint: disable=import-outside-toplevel + + if int64_offsets and not int64_offsets_supported(): + raise RuntimeError(f"{_PKG} lacks INT64_OFFSETS: it takes int32 expert offsets only") + return cutlass.Int64 if int64_offsets else cutlass.Int32 + + +def tail_fakes(rows, experts, ws_bytes, int64_offsets=False): """Fake row ends, alpha, prob and workspace operands shared by every launch.""" import cutlass # pylint: disable=import-outside-toplevel return ( - fake_tensor(cutlass.Int32, (experts,), (0,), 16), + fake_tensor(offsets_dtype(int64_offsets), (experts,), (0,), 16), fake_tensor(cutlass.Float32, (experts,), (0,), 16), fake_tensor(cutlass.Float32, (rows,), (0,), 16), fake_tensor(cutlass.Uint8, (ws_bytes,), (0,), 128), diff --git a/transformer_engine/common/CuTeDSL/ep_gemm/combine_gemm.py b/transformer_engine/common/CuTeDSL/ep_gemm/combine_gemm.py index 5fe96eb650a..a0a09d08826 100644 --- a/transformer_engine/common/CuTeDSL/ep_gemm/combine_gemm.py +++ b/transformer_engine/common/CuTeDSL/ep_gemm/combine_gemm.py @@ -10,11 +10,11 @@ backward [rows,k] [E,k,n] (the forward weight) [rows,n] BF16, scaled per row by prob BF16 operands, or E4M3 with GEMM-swizzled E8M0 scales ``sfa`` and ``sfb`` for MXFP8 (the backward -reads the columnwise forward weight). Common operands: ``expert_row_ends`` [E] int32, ``alpha`` -[E] FP32, ``prob`` [rows] FP32, ``workspace`` uint8, stream. ``signal[u] = u`` once columns -``[u * n_chunk, (u + 1) * n_chunk)`` of ``d`` are final; the caller sets ``signal[]`` to -1 before -each launch. With ``n_chunk`` 0 the GEMM publishes nothing and runs in the stock tile order; its -workspace ends in one flag word the caller sets. +reads the columnwise forward weight). Common operands: ``expert_row_ends`` [E] int32 (int64 +with ``int64_offsets``), ``alpha`` [E] FP32, ``prob`` [rows] FP32, ``workspace`` uint8, stream. +``signal[u] = u`` once columns ``[u * n_chunk, (u + 1) * n_chunk)`` of ``d`` are final; the caller +sets ``signal[]`` to -1 before each launch. With ``n_chunk`` 0 the GEMM publishes nothing and runs +in the stock tile order; its workspace ends in one flag word the caller sets. """ import functools @@ -63,6 +63,7 @@ class CombineGemmConfig: scaling_mode: int = DELAYED_TENSOR_SCALING # operand scaling (NVTEScalingMode) token_alignment: int = ROWS_PER_TILE # rows per expert slab are a multiple of it grid_clusters: int = 0 # clusters launched (0: num_clusters), extras stop after the first chunk + int64_offsets: bool = False # int64 instead of int32 expert row ends # Kernels, workspace layouts and compiled functions are specific to the device architecture. capability: tuple = field(default_factory=device_compute_capability) @@ -153,7 +154,7 @@ def launch(a, b, d, expert_row_ends, alpha, prob, workspace, stream): cutlass.BFloat16, (experts, k, n) if backward else (experts, n, k), (2, 1, 0), 16 ), fake_tensor(cutlass.BFloat16, (rows, n), (1, 0), 16), - *tail_fakes(rows, experts, workspace_layout(cfg)[0]), + *tail_fakes(rows, experts, workspace_layout(cfg)[0], cfg.int64_offsets), ) @@ -193,40 +194,42 @@ def launch_rubin(a, b, sfb, sfa, d, expert_row_ends, alpha, prob, workspace, str scale_fake(experts * n, k), scale_fake(rows, k), fake_tensor(cutlass.BFloat16, (rows, n), (1, 0), 16), - *tail_fakes(rows, experts, workspace_layout(cfg)[0]), + *tail_fakes(rows, experts, workspace_layout(cfg)[0], cfg.int64_offsets), ) def _config( rows, k, n, num_experts, num_clusters, n_chunk, dependents_at_entry, backward, scaling_mode, - token_alignment, grid_clusters, + token_alignment, grid_clusters, int64_offsets, ): # fmt: skip """Build a CombineGemmConfig from the entry-point arguments.""" return CombineGemmConfig( rows, k, n, num_experts, num_clusters, n_chunk, bool(dependents_at_entry), bool(backward), - int(scaling_mode), token_alignment, grid_clusters, + int(scaling_mode), token_alignment, grid_clusters, bool(int64_offsets), ) # fmt: skip def get_ep_combine_gemm_workspace_layout( rows, k, n, num_experts, num_clusters, n_chunk, dependents_at_entry, backward, scaling_mode=DELAYED_TENSOR_SCALING, token_alignment=ROWS_PER_TILE, grid_clusters=0, + int64_offsets=False, ): # fmt: skip """[total bytes, signal offset, signal entries] of the workspace of this configuration.""" return list(workspace_layout(_config( rows, k, n, num_experts, num_clusters, n_chunk, dependents_at_entry, backward, scaling_mode, - token_alignment, grid_clusters, + token_alignment, grid_clusters, int64_offsets, ))) # fmt: skip def get_ep_combine_gemm_function( fn_name, rows, k, n, num_experts, num_clusters, n_chunk, dependents_at_entry, backward, scaling_mode=DELAYED_TENSOR_SCALING, token_alignment=ROWS_PER_TILE, grid_clusters=0, + int64_offsets=False, ) -> bool: # fmt: skip """Compile and register the GEMM of this configuration as ``fn_name``; return whether it is.""" cfg = _config( rows, k, n, num_experts, num_clusters, n_chunk, dependents_at_entry, backward, scaling_mode, - token_alignment, grid_clusters, + token_alignment, grid_clusters, int64_offsets, ) # fmt: skip compile_fn = _compile_mxfp8 if cfg.mxfp8 else _compile return register_function(fn_name, lambda: compile_fn(cfg), "EP grouped GEMM combine") diff --git a/transformer_engine/common/CuTeDSL/ep_gemm/dispatch_gemm.py b/transformer_engine/common/CuTeDSL/ep_gemm/dispatch_gemm.py index b1693b58dfd..10e1941804c 100644 --- a/transformer_engine/common/CuTeDSL/ep_gemm/dispatch_gemm.py +++ b/transformer_engine/common/CuTeDSL/ep_gemm/dispatch_gemm.py @@ -14,10 +14,10 @@ Forward is FC1 (gate and up alternate in 32-column blocks of ``c``). Backward is the FC2 data gradient with the SwiGLU backward in the epilogue; its ``c`` is the FC1 output [rows, 2n]. -Common operands: ``expert_row_ends`` [E] int32, ``alpha`` [E] FP32, ``prob`` [rows] FP32, -``workspace`` uint8, stream. With ``device_layout`` the forward also waits for the dispatch to -write ``expert_row_ends`` and the word before it (expert 0's offset), both -1 beforehand. The -kernel waits until they are at least 0. +Common operands: ``expert_row_ends`` [E] int32 (int64 with ``int64_offsets``), ``alpha`` [E] +FP32, ``prob`` [rows] FP32, ``workspace`` uint8, stream. With ``device_layout`` the forward also +waits for the dispatch to write ``expert_row_ends`` and the entry before it (expert 0's offset), +both -1 beforehand. The kernel waits until they are at least 0. MXFP8 scales: ``sfa`` is compact (as the dispatch delivers it) and ``sfb`` swizzled. The forward takes no ``prob`` and a ``norm_const`` [1] FP32 of 1. The backward writes ``sfd_row`` (swizzled), @@ -75,6 +75,7 @@ class DispatchGemmConfig: device_layout: bool = False # forward: the dispatch writes the expert row ends d_col: bool = True # MXFP8 backward: writes the columnwise d and its scales h: bool = True # MXFP8 backward: writes the columnwise h and its scales + int64_offsets: bool = False # int64 instead of int32 expert row ends activation: str = "swiglu" # Kernels, workspace layouts and compiled functions are specific to the device architecture. capability: tuple = field(default_factory=device_compute_capability) @@ -211,7 +212,7 @@ def _prologue(cfg: DispatchGemmConfig): """Kernel, (rows, k, n, experts, num_clusters) and workspace tail fakes shared by a compiler.""" kernel = build_kernel(cfg) dims = (cfg.rows, cfg.k, cfg.n, cfg.num_experts, cfg.num_clusters) - tail = tail_fakes(cfg.rows, cfg.num_experts, workspace_layout(cfg)[0]) + tail = tail_fakes(cfg.rows, cfg.num_experts, workspace_layout(cfg)[0], cfg.int64_offsets) return kernel, dims, tail @@ -369,33 +370,35 @@ def launch( def _config(rows, k, n, num_experts, num_clusters, backward, scaling_mode, token_alignment, - device_layout, d_col, h): # fmt: skip + device_layout, d_col, h, int64_offsets): # fmt: skip """Build a DispatchGemmConfig from the entry-point arguments.""" return DispatchGemmConfig( rows, k, n, num_experts, num_clusters, bool(backward), int(scaling_mode), token_alignment, - bool(device_layout), bool(d_col), bool(h), + bool(device_layout), bool(d_col), bool(h), bool(int64_offsets), ) # fmt: skip def get_ep_dispatch_gemm_workspace_layout( rows, k, n, num_experts, num_clusters, backward, scaling_mode=DELAYED_TENSOR_SCALING, token_alignment=ROWS_PER_TILE, device_layout=False, d_col=True, h=True, + int64_offsets=False, ): # fmt: skip """[total bytes, counter, signal, state] byte offsets of the workspace of this configuration.""" return list(workspace_layout(_config( rows, k, n, num_experts, num_clusters, backward, scaling_mode, token_alignment, device_layout, - d_col, h, + d_col, h, int64_offsets, ))) # fmt: skip def get_ep_dispatch_gemm_function( fn_name, rows, k, n, num_experts, num_clusters, backward, scaling_mode=DELAYED_TENSOR_SCALING, token_alignment=ROWS_PER_TILE, device_layout=False, d_col=True, h=True, + int64_offsets=False, ) -> bool: # fmt: skip """Compile and register the GEMM of this configuration as ``fn_name``; return whether it is.""" cfg = _config( rows, k, n, num_experts, num_clusters, backward, scaling_mode, token_alignment, device_layout, - d_col, h, + d_col, h, int64_offsets, ) # fmt: skip compile_fn = _COMPILERS[cfg.backward, cfg.mxfp8] return register_function(fn_name, lambda: compile_fn(cfg), "EP dispatch grouped GEMM") diff --git a/transformer_engine/common/CuTeDSL/ep_gemm/wgrad_gemm.py b/transformer_engine/common/CuTeDSL/ep_gemm/wgrad_gemm.py index f36b5dbdb1e..6e23c0e7068 100644 --- a/transformer_engine/common/CuTeDSL/ep_gemm/wgrad_gemm.py +++ b/transformer_engine/common/CuTeDSL/ep_gemm/wgrad_gemm.py @@ -7,7 +7,7 @@ ``weight_grad[e] = grad[rows of e]^T x[rows of e]`` per expert: ``grad`` [rows, m] and ``x`` [rows, n] BF16, or MXFP8 columnwise data with their GEMM-swizzled columnwise scales, ``weight_grad`` [experts, m, n] BF16 or FP32, written or added to. Operands: ``expert_row_ends`` -[experts] int32, ``workspace`` uint8, stream. +[experts] int32 (int64 with ``int64_offsets``), ``workspace`` uint8, stream. Each launch is a persistent grid that claims output tiles from an atomic counter in ``workspace``, so launches sharing one workspace split the tiles across SMs. It is a programmatic dependent of the @@ -32,6 +32,7 @@ fp8_fake, import_gemm_modules, is_sm107, + offsets_dtype, register_function, scale_fake, wide_bf16_wgrad_kernel, @@ -54,6 +55,7 @@ class WgradConfig: token_alignment: int = 0 # rows per expert slab are a multiple of it routed_tokens: int = 0 # rows a rank receives on average signal_unit_tokens: int = 0 # rows per dispatch flag the launch takes, 0: none + int64_offsets: bool = False # int64 instead of int32 expert row ends # Kernels, workspace layouts and compiled functions are specific to the device architecture. capability: tuple = field(default_factory=device_compute_capability) @@ -223,7 +225,7 @@ def views(grad, x, weight_grad): cutlass.Float32 if cfg.fp32_out else cutlass.BFloat16, (experts, m, n), (2, 1, 0), 16 ) tail = ( - fake_tensor(cutlass.Int32, (experts,), (0,), 16), + fake_tensor(offsets_dtype(cfg.int64_offsets), (experts,), (0,), 16), fake_tensor(cutlass.Uint8, (workspace_layout(cfg)[0],), (0,), 128), # Shared tile counter: launches into one workspace split one tile list. fake_tensor(cutlass.Int32, (1,), (0,), 16), @@ -298,6 +300,7 @@ def launch_signal(grad, x, weight_grad, expert_row_ends, workspace, counter, sig def _config( rows, m, n, num_experts, num_clusters, fp32_out, accumulate, wait_primary_at_start, signal_unit_tokens, scaling_mode, descriptors_only, token_alignment, routed_tokens, + int64_offsets=False, ): # fmt: skip """Build a WgradConfig from the entry-point arguments. descriptors_only selects a cuDNN FE kernel that does not exist (see build_kernel); it is accepted for ABI stability and ignored. @@ -307,40 +310,47 @@ def _config( return WgradConfig( rows, m, n, num_experts, num_clusters, bool(fp32_out), bool(accumulate), int(scaling_mode), bool(wait_primary_at_start), token_alignment, routed_tokens, int(signal_unit_tokens), + bool(int64_offsets), ) # fmt: skip def get_ep_wgrad_workspace_layout( rows, m, n, num_experts, num_clusters, fp32_out, accumulate, wait_primary_at_start, signal_unit_tokens, scaling_mode, descriptors_only, token_alignment, routed_tokens, + int64_offsets=False, ): # fmt: skip """[total bytes, counter offset] of the workspace of this configuration.""" return list(workspace_layout(_config( rows, m, n, num_experts, num_clusters, fp32_out, accumulate, wait_primary_at_start, signal_unit_tokens, scaling_mode, descriptors_only, token_alignment, routed_tokens, + int64_offsets, ))) # fmt: skip def get_ep_wgrad_reads_descriptors( rows, m, n, num_experts, num_clusters, fp32_out, accumulate, wait_primary_at_start, signal_unit_tokens, scaling_mode, descriptors_only, token_alignment, routed_tokens, + int64_offsets=False, ) -> bool: # fmt: skip """Whether the launches of this configuration read the per-expert descriptors of a ``descriptors_only`` launch.""" return reads_descriptors(_config( rows, m, n, num_experts, num_clusters, fp32_out, accumulate, wait_primary_at_start, signal_unit_tokens, scaling_mode, descriptors_only, token_alignment, routed_tokens, + int64_offsets, )) # fmt: skip def get_ep_wgrad_function( fn_name, rows, m, n, num_experts, num_clusters, fp32_out, accumulate, wait_primary_at_start, signal_unit_tokens, scaling_mode, descriptors_only, token_alignment, routed_tokens, + int64_offsets=False, ) -> bool: # fmt: skip """Compile and register the weight gradient of this configuration as ``fn_name``; return whether it is.""" cfg = _config( rows, m, n, num_experts, num_clusters, fp32_out, accumulate, wait_primary_at_start, signal_unit_tokens, scaling_mode, descriptors_only, token_alignment, routed_tokens, + int64_offsets, ) # fmt: skip return register_function(fn_name, lambda: _compile(cfg), "EP weight-gradient grouped GEMM") diff --git a/transformer_engine/common/ep/ep_api.cpp b/transformer_engine/common/ep/ep_api.cpp index d1b204c4aa3..8f98e28d287 100644 --- a/transformer_engine/common/ep/ep_api.cpp +++ b/transformer_engine/common/ep/ep_api.cpp @@ -76,12 +76,12 @@ size_t nvte_ep_handle_mem_size(const NVTEEpLayerConfig* layer_cfg) { } void nvte_ep_prepare(NVTETensor handle_mem, NVTETensor topk_idx, NVTETensor recv_tokens_per_expert, - NVTETensor total_recv_tokens_per_rank, const NVTEEpLayerConfig* layer_cfg, - cudaStream_t stream) { + NVTETensor total_recv_tokens_per_rank, NVTETensor expert_offsets, + const NVTEEpLayerConfig* layer_cfg, cudaStream_t stream) { NVTE_API_CALL(nvte_ep_prepare); NVTEEpLayerConfig cfg = normalize_ep_config(layer_cfg, kLayerConfigMinSize, "layer_cfg"); EPBackend::get().prepare(handle_mem, topk_idx, recv_tokens_per_expert, total_recv_tokens_per_rank, - cfg, stream); + expert_offsets, cfg, stream); } void nvte_ep_dispatch(NVTETensor handle_mem, NVTETensor topk_idx, NVTETensor tokens, @@ -198,7 +198,7 @@ size_t nvte_ep_handle_mem_size(const NVTEEpLayerConfig* /*layer_cfg*/) { ep_not_ void nvte_ep_prepare(NVTETensor /*handle_mem*/, NVTETensor /*topk_idx*/, NVTETensor /*recv_tokens_per_expert*/, - NVTETensor /*total_recv_tokens_per_rank*/, + NVTETensor /*total_recv_tokens_per_rank*/, NVTETensor /*expert_offsets*/, const NVTEEpLayerConfig* /*layer_cfg*/, cudaStream_t /*stream*/) { ep_not_built(); } diff --git a/transformer_engine/common/ep/ep_backend.cpp b/transformer_engine/common/ep/ep_backend.cpp index 0d0f1893fce..5e1e7e9f780 100644 --- a/transformer_engine/common/ep/ep_backend.cpp +++ b/transformer_engine/common/ep/ep_backend.cpp @@ -490,7 +490,8 @@ size_t EPBackend::handle_mem_size(NVTEEpLayerConfig layer_cfg) { void EPBackend::prepare(NVTETensor handle_mem, const NVTETensor topk_idx, NVTETensor recv_tokens_per_expert, NVTETensor total_recv_tokens_per_rank, - NVTEEpLayerConfig layer_cfg, cudaStream_t stream) { + NVTETensor expert_offsets, NVTEEpLayerConfig layer_cfg, + cudaStream_t stream) { void* hm_ptr = handle_mem_ptr(handle_mem); NVTE_CHECK(layer_cfg.top_k > 0, "top_k must be > 0, got ", layer_cfg.top_k); NVTE_CHECK(nvte_tensor_shape(topk_idx).ndim == 2, "topk_idx must be 2D [T, top_k]"); @@ -499,7 +500,8 @@ void EPBackend::prepare(NVTETensor handle_mem, const NVTETensor topk_idx, ncclEpTensor_t nccl_topk_idx = make_nccl_ep_tensor(topk_idx, topk_idx_shape); // ncclEpUpdateHandle writes per-expert counts via expert_counters and, when - // provided, the scalar padded recv-slot total via recv_total_counter. + // provided, the scalar padded recv-slot total via recv_total_counter and the + // per-expert start rows via expert_offsets. NVTEShape recv_tokens_per_expert_shape; ncclEpTensor_t recv_tokens_per_expert_desc; if (recv_tokens_per_expert != nullptr) { @@ -511,11 +513,17 @@ void EPBackend::prepare(NVTETensor handle_mem, const NVTETensor topk_idx, if (total_recv_tokens_per_rank != nullptr) { total_recv_desc = make_nccl_ep_tensor(total_recv_tokens_per_rank, total_recv_shape); } + NVTEShape expert_offsets_shape; + ncclEpTensor_t expert_offsets_desc; + if (expert_offsets != nullptr) { + expert_offsets_desc = make_nccl_ep_tensor(expert_offsets, expert_offsets_shape); + } ncclEpLayoutInfo_t layout_info = NCCL_EP_LAYOUT_INFO_INIT; layout_info.expert_counters = (recv_tokens_per_expert != nullptr) ? &recv_tokens_per_expert_desc : nullptr; layout_info.recv_total_counter = (total_recv_tokens_per_rank != nullptr) ? &total_recv_desc : nullptr; + layout_info.expert_offsets = (expert_offsets != nullptr) ? &expert_offsets_desc : nullptr; std::lock_guard lock(mutex_); NVTE_CHECK(initialized_, "EPBackend not initialized"); diff --git a/transformer_engine/common/ep/ep_backend.h b/transformer_engine/common/ep/ep_backend.h index dce53315ddb..7449bfbe2be 100644 --- a/transformer_engine/common/ep/ep_backend.h +++ b/transformer_engine/common/ep/ep_backend.h @@ -57,8 +57,8 @@ class EPBackend { // Updates handle_mem with this step's routing and writes the recv counts. NCCL EP uses count // mode; the scan path is used only when the transport is IB. void prepare(NVTETensor handle_mem, const NVTETensor topk_idx, NVTETensor recv_tokens_per_expert, - NVTETensor total_recv_tokens_per_rank, NVTEEpLayerConfig layer_cfg, - cudaStream_t stream); + NVTETensor total_recv_tokens_per_rank, NVTETensor expert_offsets, + NVTEEpLayerConfig layer_cfg, cudaStream_t stream); // Per-step ops below require a prior prepare(); layer_cfg rebinds the handle from handle_mem. // A non-null dispatch_signal publishes one flag per signal granularity rows of recv_tokens. diff --git a/transformer_engine/common/ep/ep_gemm_api.cpp b/transformer_engine/common/ep/ep_gemm_api.cpp index b7df333672f..35a19175e71 100644 --- a/transformer_engine/common/ep/ep_gemm_api.cpp +++ b/transformer_engine/common/ep/ep_gemm_api.cpp @@ -41,6 +41,7 @@ using ep::kRowsPerTile; using ep::kTileN; using transformer_engine::check_mxfp8; using transformer_engine::check_vector; +using transformer_engine::DLTensorWrapper; using transformer_engine::is_mxfp8; using transformer_engine::wrap_columnwise; using transformer_engine::wrap_raw; @@ -137,7 +138,8 @@ bool dispatch_writes_layout(const EpGemmContext& ctx, size_t num_local_experts) // The forward combine_gemm GEMM of [rows, k] inputs and n output columns. ep::EpCombineGemmConfig combine_fwd_config(const EpGemmContext& ctx, size_t rows, size_t k, size_t n, size_t num_experts, - NVTEScalingMode scaling_mode) { + NVTEScalingMode scaling_mode, + bool int64_offsets = false) { return ep::EpCombineGemmConfig{rows, k, n, @@ -148,14 +150,14 @@ ep::EpCombineGemmConfig combine_fwd_config(const EpGemmContext& ctx, size_t rows false, scaling_mode, ctx.alignment(), - ctx.all_clusters}; + ctx.all_clusters, + int64_offsets}; } // Per-call scratch for the GEMM's readiness flags and state, sliced from the caller's workspace. // ScratchLayout is the byte layout; nvte_ep_overlap_prepare uses it to size the workspace // without a buffer, and claim_scratch uses it to resolve the pointers in GemmScratch. struct ScratchLayout { - size_t row_ends; // [num_experts] int32 per-expert row ends, the grouped GEMM layout operand size_t alpha; // [num_experts] float32 per-expert output scale, set to 1 (reused as norm_const) size_t ones; // [rows] float32 of 1, the probability operand when the GEMM is unweighted size_t offsets; // [num_experts + 1] int64 element offsets of the MXFP8 requant grouped tensor @@ -166,8 +168,7 @@ struct ScratchLayout { ScratchLayout scratch_layout(size_t gemm_bytes, size_t num_experts, size_t rows, bool unit_probs, size_t wgrad_bytes) { ScratchLayout l; - l.row_ends = align_up(gemm_bytes + sizeof(int32_t)); - l.alpha = l.row_ends + align_up(sizeof(int32_t) * num_experts); + l.alpha = align_up(gemm_bytes); l.ones = l.alpha + align_up(sizeof(float) * num_experts); l.offsets = l.ones + (unit_probs ? align_up(sizeof(float) * rows) : 0); l.wgrad = l.offsets + align_up(sizeof(int64_t) * (num_experts + 1)); @@ -175,16 +176,17 @@ ScratchLayout scratch_layout(size_t gemm_bytes, size_t num_experts, size_t rows, return l; } -// Resolved pointers into the workspace slices, plus the words each launch resets. row_ends usually -// addresses the layout slice, but dispatch_fwd re-points it to the caller's expert_token_offsets. +// Resolved pointers into the workspace slices, plus the words each launch resets. layout is the +// caller's expert_token_offsets, whose row ends the GEMMs read. struct GemmScratch { uint8_t* base; uint8_t* wgrad = nullptr; - int32_t* row_ends = nullptr; // [num_experts] - float* alpha = nullptr; // [num_experts] - float* ones = nullptr; // [rows] - int64_t* offsets = nullptr; // [num_experts + 1] requant grouped-tensor element offsets - int32_t* signal = nullptr; // [signal_capacity] readiness flags + void* layout = nullptr; // [num_experts + 1] int32 or int64 + bool int64_offsets = false; // layout dtype + float* alpha = nullptr; // [num_experts] + float* ones = nullptr; // [rows] + int64_t* offsets = nullptr; // [num_experts + 1] requant grouped-tensor element offsets + int32_t* signal = nullptr; // [signal_capacity] readiness flags int signal_capacity = 0; int num_experts = 0; ep::WorkspaceReset reset; @@ -199,7 +201,6 @@ GemmScratch claim_scratch(uint8_t* base, size_t workspace_bytes, size_t gemm_byt if (wgrad_bytes > 0) { scratch.wgrad = base + l.wgrad; } - scratch.row_ends = reinterpret_cast(base + l.row_ends); scratch.alpha = reinterpret_cast(base + l.alpha); scratch.offsets = reinterpret_cast(base + l.offsets); scratch.num_experts = static_cast(num_experts); @@ -223,7 +224,7 @@ std::pair workspace_span(const NVTETensor workspace) { } // Stage a GemmScratch's reset words once the GEMM's WorkspaceLayout is known: the readiness flags, -// scheduler state and row ends each launch reinitializes. +// scheduler state and layout entries each launch reinitializes. // Words of a GEMM that waits on the dispatch tile flags: its tile counter, flags and scheduler // state. @@ -246,20 +247,24 @@ void set_chunk_words(GemmScratch& scratch, const ep::WorkspaceLayout& layout, si scratch.reset.fill(scratch.signal, scratch.signal_capacity, ep::kFillMinusOne); } -// Row ends the dispatch writes: unset until it does, together with the reserved word before them. -void unset_row_ends(GemmScratch& scratch) { - scratch.reset.fill(scratch.row_ends - 1, scratch.num_experts + 1, ep::kFillMinusOne); +// The caller's expert layout the GEMMs read, checked by check_ep_expert_token_offsets. +void set_layout(GemmScratch& scratch, NVTETensor expert_token_offsets, bool int64_offsets) { + scratch.layout = nvte_tensor_data(expert_token_offsets); + scratch.int64_offsets = int64_offsets; + scratch.reset.layout = scratch.layout; + scratch.reset.layout_int64 = int64_offsets; + scratch.reset.num_experts = scratch.num_experts; } -// Row ends computed by the reset from the padded int32 counts per local expert; write_layout_base -// also writes the reserved word before them, expert 0's start, as 0. -void set_row_ends(GemmScratch& scratch, NVTETensor counts, bool write_layout_base = false) { - scratch.reset.counts = static_cast(nvte_tensor_data(counts)); - scratch.reset.row_ends = scratch.row_ends; - scratch.reset.num_experts = scratch.num_experts; - if (write_layout_base) { - scratch.reset.fill(scratch.row_ends - 1, 1, ep::kFillZero); - } +// Bytes of one layout entry. +size_t layout_entry_bytes(const GemmScratch& scratch) { + return scratch.int64_offsets ? sizeof(int64_t) : sizeof(int32_t); +} + +// The per-expert row ends operand: the layout past expert 0's start. +DLTensorWrapper wrap_row_ends(const GemmScratch& scratch) { + return wrap_raw(static_cast(scratch.layout) + layout_entry_bytes(scratch), + scratch.int64_offsets ? kNVTEInt64 : kNVTEInt32, scratch.num_experts); } // Compiled GEMM and workspace layout of a configuration. @@ -304,7 +309,7 @@ struct Wgrad { std::optional make_wgrad(const EpGemmContext& ctx, NVTETensor grad, NVTETensor x, NVTETensor weight_grad, bool accumulate, size_t rows, size_t num_experts, NVTEScalingMode scaling_mode, - size_t signal_unit_tokens = 0) { + bool int64_offsets, size_t signal_unit_tokens = 0) { const bool mxfp8 = transformer_engine::is_mxfp8_scaling(scaling_mode); if (weight_grad == nullptr) { NVTE_CHECK(x == nullptr, "wgrad_input needs weight_grad"); @@ -352,12 +357,13 @@ std::optional make_wgrad(const EpGemmContext& ctx, NVTETensor grad, NVTET "weight_grad must be bfloat16 or float32"); const size_t routed_tokens = static_cast(ctx.group.max_tokens_per_rank) * ctx.layer_cfg.top_k; - Wgrad wgrad{grad, - x, - weight_grad, - {rows, m, n, num_experts, 1, out_type == kNVTEFloat32, accumulate, false, - signal_unit_tokens, scaling_mode, false, ctx.alignment(), routed_tokens}, - {}}; + Wgrad wgrad{ + grad, + x, + weight_grad, + {rows, m, n, num_experts, 1, out_type == kNVTEFloat32, accumulate, false, signal_unit_tokens, + scaling_mode, false, ctx.alignment(), routed_tokens, int64_offsets}, + {}}; const auto layout = wgrad.config.workspace_layout(); NVTE_CHECK(layout.has_value(), "cannot query the weight-gradient workspace layout"); wgrad.layout = *layout; @@ -398,7 +404,7 @@ void launch_wgrad(const Wgrad& wgrad, const GemmScratch& scratch, int num_cluste layout.total_bytes <= wgrad.layout.total_bytes && layout.counter == wgrad.layout.counter, "weight-gradient launches must share one workspace and tile counter"); auto out = wrap_rowwise(wgrad.weight_grad, false); - auto row_ends = wrap_raw(scratch.row_ends, kNVTEInt32, config.num_experts); + auto row_ends = wrap_row_ends(scratch); auto ws = wrap_raw(scratch.wgrad, kNVTEByte, layout.total_bytes); // The tile counter the launches share: the caller zeroed it and the kernel does not reset it, so // a base and tail into one workspace split one tile list instead of each draining it. @@ -425,8 +431,8 @@ void launch_wgrad(const Wgrad& wgrad, const GemmScratch& scratch, int num_cluste // The columnwise MXFP8 copy of t's received rows, requantized from its rowwise data and compact // scales into GEMM-swizzled columnwise scales per expert slab. The shared grouped MXFP8 requant // runs as a programmatic dependent (PDL): it overlaps the producing GEMM on the SMs the reverse -// dispatch frees. The expert slabs are given by the element offsets reset_workspace scans from the -// row ends. +// dispatch frees. The expert slabs are given by the element offsets reset_workspace writes from the +// expert layout. void launch_requant(NVTETensor t, const GemmScratch& scratch, size_t rows, size_t cols, size_t num_experts, cudaStream_t stream) { using namespace transformer_engine; @@ -575,11 +581,13 @@ void nvte_ep_dispatch_gemm_fwd(NVTETensor handle_mem, const NVTETensor topk_idx, ctx.group.num_experts / ctx.group.ep_size); NVTE_CHECK(nvte_tensor_shape(act_out).data[1] * 2 == n, "weight rows (", n, ") must be 2 * the act_out columns: SwiGLU"); - check_vector(recv_tokens_per_expert, num_experts, kNVTEInt32, "recv_tokens_per_expert"); + const bool int64_offsets = + check_ep_expert_token_offsets(expert_token_offsets, num_experts, recv_tokens_per_expert); + const NVTEDType offsets_type = int64_offsets ? kNVTEInt64 : kNVTEInt32; check_vector(recv_topk_weights, rows, kNVTEFloat32, "recv_topk_weights"); NVTE_CHECK(total_recv_tokens == nullptr || (nvte_tensor_numel(total_recv_tokens) == 1 && - nvte_tensor_type(total_recv_tokens) == kNVTEInt32), - "total_recv_tokens must be an int32 tensor of 1 element"); + nvte_tensor_type(total_recv_tokens) == offsets_type), + "total_recv_tokens must be a tensor of 1 element of the expert_token_offsets dtype"); const NVTEScalingMode scaling_mode = ep_overlap_scaling_mode(tokens); const bool mxfp8 = scaling_mode == NVTE_MXFP8_1D_SCALING; if (mxfp8) { @@ -601,9 +609,10 @@ void nvte_ep_dispatch_gemm_fwd(NVTETensor handle_mem, const NVTETensor topk_idx, // The GEMM runs beside the dispatch, and its tail on the SMs the dispatch frees. Both launches // claim tiles from one workspace. ep::WorkspaceLayout layout; - const ep::EpDispatchGemmConfig config{rows, hidden, n, - num_experts, ctx.num_clusters, false, - scaling_mode, ctx.alignment(), device_layout}; + ep::EpDispatchGemmConfig config{rows, hidden, n, + num_experts, ctx.num_clusters, false, + scaling_mode, ctx.alignment(), device_layout}; + config.int64_offsets = int64_offsets; std::vector gemms{get_gemm(config, &layout)}; const int tail_clusters = ctx.all_clusters - ctx.num_clusters; if (tail_clusters > 0) { @@ -612,11 +621,11 @@ void nvte_ep_dispatch_gemm_fwd(NVTETensor handle_mem, const NVTETensor topk_idx, GemmScratch scratch = claim_scratch(ws_base, ws_bytes, layout.total_bytes, num_experts, rows, false, 0); set_signal_words(scratch, layout, rows / ctx.signal_unit_tokens()); - // The GEMM reads the expert row ends from the caller's [num_experts + 1] int32 - // expert_token_offsets (expert 0's start, then the per-expert ends); the dispatch writes them in - // capacity mode. - check_ep_expert_token_offsets(expert_token_offsets, num_experts); - scratch.row_ends = static_cast(nvte_tensor_data(expert_token_offsets)) + 1; + // NCCL EP writes the expert starts, layout[0, num_experts), and the padded counts. + set_layout(scratch, expert_token_offsets, int64_offsets); + const size_t entry_bytes = layout_entry_bytes(scratch); + TensorWrapper offsets(scratch.layout, std::vector{num_experts}, + static_cast(offsets_type)); // The dispatch publishes one flag per slot of rows; the GEMM behind it consumes ready tiles. TensorWrapper signal(scratch.signal, @@ -625,14 +634,14 @@ void nvte_ep_dispatch_gemm_fwd(NVTETensor handle_mem, const NVTETensor topk_idx, const ep::EpSignal dispatch_signal{signal.data(), ctx.signal_unit_tokens()}; NVTECommWindow no_window{}; if (device_layout) { - // Flags, scheduler state and unset layout words, before the dispatch that sets them. The fused - // dispatch writes the GEMM's expert layout and the padded counts in one scan. - unset_row_ends(scratch); + // Flags, scheduler state and unset layout entries, before the dispatch that sets them. The + // fused dispatch writes the starts and the padded counts in one scan, and the num total recv + // tokens after them, final as it does not run with drops. + scratch.reset.fill(scratch.layout, static_cast((num_experts + 1) * entry_bytes / 4), + ep::kFillMinusOne); // in int32 words ep::reset_workspace(scratch.reset, stream); - // Expert offsets, then the row total: the expert row ends sit one word in. - int32_t* const expert_layout = scratch.row_ends - 1; - TensorWrapper offsets(expert_layout, std::vector{num_experts}, DType::kInt32); - TensorWrapper total(expert_layout + num_experts, std::vector{1}, DType::kInt32); + TensorWrapper total(static_cast(scratch.layout) + num_experts * entry_bytes, + std::vector{1}, static_cast(offsets_type)); ctx.backend.prepare_and_dispatch(handle_mem, topk_idx, tokens, tokens_win, topk_weights, no_window, recv_tokens, no_window, recv_topk_weights, no_window, recv_tokens_per_expert, total.data(), @@ -641,12 +650,11 @@ void nvte_ep_dispatch_gemm_fwd(NVTETensor handle_mem, const NVTETensor topk_idx, // Capacity mode runs the routing prepare; eager mode ran nvte_ep_prepare already. if (!ctx.eager) { ctx.backend.prepare(handle_mem, topk_idx, recv_tokens_per_expert, total_recv_tokens, - ctx.layer_cfg, stream); + offsets.data(), ctx.layer_cfg, stream); } - // Flags, scheduler state and expert row ends, before the dispatch that sets the flags. The - // reset also writes the caller offsets' leading 0 (expert 0's start), which the dispatch - // layout scan does not touch here. - set_row_ends(scratch, recv_tokens_per_expert, /*write_layout_base=*/true); + // Flags, scheduler state and the final post-drop num total recv tokens, from NCCL EP's + // post-drop starts and counts, before the dispatch that sets the flags. + scratch.reset.counts = nvte_tensor_data(recv_tokens_per_expert); ep::reset_workspace(scratch.reset, stream); ctx.backend.dispatch(handle_mem, topk_idx, tokens, tokens_win, topk_weights, no_window, recv_tokens, no_window, recv_topk_weights, no_window, &dispatch_signal, @@ -659,7 +667,7 @@ void nvte_ep_dispatch_gemm_fwd(NVTETensor handle_mem, const NVTETensor topk_idx, auto b = wrap_rowwise(weight, false); auto c = wrap_rowwise(gemm_out, true); auto d = wrap_rowwise(act_out, true); - auto row_ends = wrap_raw(scratch.row_ends, kNVTEInt32, num_experts); + auto row_ends = wrap_row_ends(scratch); auto alpha = wrap_raw(scratch.alpha, kNVTEFloat32, num_experts); auto ws = wrap_raw(scratch.base, kNVTEByte, layout.total_bytes); if (mxfp8) { @@ -680,9 +688,10 @@ void nvte_ep_dispatch_gemm_fwd(NVTETensor handle_mem, const NVTETensor topk_idx, // The layout the dispatch wrote ends in the recv total; no row drops in this mode. It follows // the GEMM launches so that it does not sit between the dispatch and its programmatic dependent. if (device_layout && total_recv_tokens != nullptr) { - NVTE_CHECK_CUDA(cudaMemcpyAsync(nvte_tensor_data(total_recv_tokens), - scratch.row_ends + (num_experts - 1), sizeof(int32_t), - cudaMemcpyDefault, stream)); + NVTE_CHECK_CUDA( + cudaMemcpyAsync(nvte_tensor_data(total_recv_tokens), + static_cast(scratch.layout) + num_experts * entry_bytes, + entry_bytes, cudaMemcpyDefault, stream)); } } @@ -714,7 +723,7 @@ void nvte_ep_combine_gemm_fwd(NVTETensor handle_mem, const NVTETensor gemm_in, nvte_tensor_type(gemm_in) == kNVTEBFloat16 && nvte_tensor_type(weight) == kNVTEBFloat16, "gemm_in and weight must be bfloat16 or MXFP8"); } - check_ep_expert_token_offsets(expert_token_offsets, num_experts); + const bool int64_offsets = check_ep_expert_token_offsets(expert_token_offsets, num_experts); const bool weighted = recv_topk_weights != nullptr; NVTE_CHECK(!weighted || (nvte_tensor_type(recv_topk_weights) == kNVTEFloat32 && nvte_tensor_numel(recv_topk_weights) == rows), @@ -724,7 +733,7 @@ void nvte_ep_combine_gemm_fwd(NVTETensor handle_mem, const NVTETensor gemm_in, // first chunk and leave their SMs to the combine. ep::WorkspaceLayout layout; const ep::EpCombineGemmConfig config = - combine_fwd_config(ctx, rows, k, n, num_experts, scaling_mode); + combine_fwd_config(ctx, rows, k, n, num_experts, scaling_mode, int64_offsets); const size_t n_chunk = config.n_chunk; const tvm::ffi::Function gemm = get_gemm(config, &layout); // Own workspace for the signal, scheduler and alpha words; the expert layout is the caller's @@ -732,14 +741,14 @@ void nvte_ep_combine_gemm_fwd(NVTETensor handle_mem, const NVTETensor gemm_in, GemmScratch scratch = claim_scratch(ws_base, ws_bytes, layout.total_bytes, num_experts, rows, !weighted, 0); set_chunk_words(scratch, layout, DIVUP(n, n_chunk), layout.signal); + set_layout(scratch, expert_token_offsets, int64_offsets); ep::reset_workspace(scratch.reset, stream); // The GEMM fills the flags; the combine is its programmatic dependent. auto a = wrap_rowwise(gemm_in, true); auto b = wrap_rowwise(weight, false); auto d = wrap_rowwise(expert_out, true); - auto row_ends = wrap_raw(static_cast(nvte_tensor_data(expert_token_offsets)) + 1, - kNVTEInt32, num_experts); + auto row_ends = wrap_row_ends(scratch); auto alpha = wrap_raw(scratch.alpha, kNVTEFloat32, num_experts); auto prob = weighted ? wrap_rowwise(recv_topk_weights, false) : wrap_raw(scratch.ones, kNVTEFloat32, rows); @@ -763,7 +772,7 @@ void nvte_ep_combine_gemm_fwd(NVTETensor handle_mem, const NVTETensor gemm_in, void nvte_ep_combine_gemm_bwd( NVTETensor handle_mem, const NVTETensor grad_result, NVTECommWindow grad_result_win, const NVTETensor gemm_out, const NVTETensor recv_topk_weights, - const NVTETensor recv_tokens_per_expert, const NVTETensor weight, const NVTETensor wgrad_input, + const NVTETensor expert_token_offsets, const NVTETensor weight, const NVTETensor wgrad_input, NVTETensor grad_expert_out, NVTETensor grad_gemm_out, NVTETensor grad_recv_topk_weights, NVTETensor act_out, NVTETensor weight_grad, int accumulate_weight_grad, NVTETensor workspace, NVTE_Activation_Type activation, const NVTEEpLayerConfig* layer_cfg, cudaStream_t stream) { @@ -805,7 +814,7 @@ void nvte_ep_combine_gemm_bwd( "grad_result and weight must be bfloat16 or MXFP8"); NVTE_CHECK(act_out == nullptr, "act_out is written for MXFP8 only"); } - check_vector(recv_tokens_per_expert, num_experts, kNVTEInt32, "recv_tokens_per_expert"); + const bool int64_offsets = check_ep_expert_token_offsets(expert_token_offsets, num_experts); check_vector(recv_topk_weights, rows, kNVTEFloat32, "recv_topk_weights"); check_vector(grad_recv_topk_weights, rows, kNVTEFloat32, "grad_recv_topk_weights"); @@ -818,7 +827,7 @@ void nvte_ep_combine_gemm_bwd( const size_t wgrad_signal_tokens = mxfp8 ? 0 : ctx.signal_unit_tokens(); const std::optional wgrad = make_wgrad(ctx, grad_expert_out, wgrad_input, weight_grad, accumulate_weight_grad, rows, - num_experts, scaling_mode, wgrad_signal_tokens); + num_experts, scaling_mode, int64_offsets, wgrad_signal_tokens); ep::WorkspaceLayout layout; ep::EpDispatchGemmConfig config{ @@ -827,6 +836,7 @@ void nvte_ep_combine_gemm_bwd( config.d_col = mxfp8 && nvte_get_tensor_param(grad_gemm_out, kNVTEColumnwiseData).data_ptr != nullptr; config.h = act_out != nullptr; + config.int64_offsets = int64_offsets; const tvm::ffi::Function gemm = get_gemm(config, &layout); GemmScratch scratch = claim_scratch(ws_base, ws_bytes, layout.total_bytes, num_experts, rows, false, wgrad ? wgrad->layout.total_bytes : 0); @@ -837,7 +847,7 @@ void nvte_ep_combine_gemm_bwd( // The GEMM adds each row's routing-weight gradient into grad_recv_topk_weights. scratch.reset.fill(nvte_tensor_data(grad_recv_topk_weights), static_cast(rows), ep::kFillZero); - set_row_ends(scratch, recv_tokens_per_expert); + set_layout(scratch, expert_token_offsets, int64_offsets); if (requant) { scratch.reset.offsets = scratch.offsets; scratch.reset.offsets_cols = static_cast(hidden); @@ -861,7 +871,7 @@ void nvte_ep_combine_gemm_bwd( auto c = wrap_rowwise(gemm_out, true); auto d = wrap_rowwise(grad_gemm_out, true); auto dprob = wrap_rowwise(grad_recv_topk_weights, false); - auto row_ends = wrap_raw(scratch.row_ends, kNVTEInt32, num_experts); + auto row_ends = wrap_row_ends(scratch); auto alpha = wrap_raw(scratch.alpha, kNVTEFloat32, num_experts); auto prob = wrap_rowwise(recv_topk_weights, false); auto ws = wrap_raw(scratch.base, kNVTEByte, layout.total_bytes); @@ -920,7 +930,7 @@ void nvte_ep_combine_gemm_bwd( void nvte_ep_dispatch_gemm_bwd(NVTETensor handle_mem, const NVTETensor grad_gemm_out, const NVTETensor grad_recv_topk_weights, - const NVTETensor recv_tokens_per_expert, const NVTETensor weight, + const NVTETensor expert_token_offsets, const NVTETensor weight, const NVTETensor wgrad_input, NVTETensor grad_recv_tokens, NVTETensor grad_tokens, NVTETensor grad_topk_weights, NVTETensor weight_grad, int accumulate_weight_grad, @@ -939,7 +949,7 @@ void nvte_ep_dispatch_gemm_bwd(NVTETensor handle_mem, const NVTETensor grad_gemm check_rows(ctx, rows, "grad_gemm_out"); NVTE_CHECK(nvte_tensor_shape(weight).data[1] == k && nvte_tensor_shape(weight).data[2] == hidden, "weight must be [experts, 2 * ffn, hidden]"); - check_vector(recv_tokens_per_expert, num_experts, kNVTEInt32, "recv_tokens_per_expert"); + const bool int64_offsets = check_ep_expert_token_offsets(expert_token_offsets, num_experts); check_vector(grad_recv_topk_weights, rows, kNVTEFloat32, "grad_recv_topk_weights"); const NVTEScalingMode scaling_mode = ep_overlap_scaling_mode(grad_gemm_out); const bool mxfp8 = scaling_mode == NVTE_MXFP8_1D_SCALING; @@ -956,7 +966,7 @@ void nvte_ep_dispatch_gemm_bwd(NVTETensor handle_mem, const NVTETensor grad_gemm } const std::optional wgrad = make_wgrad(ctx, grad_gemm_out, wgrad_input, weight_grad, accumulate_weight_grad, rows, - num_experts, scaling_mode); + num_experts, scaling_mode, int64_offsets); // MXFP8: the call writes the columnwise wgrad_input from its rowwise data when that is set. const bool requant = wgrad && mxfp8 && nvte_get_tensor_param(wgrad_input, kNVTERowwiseData).data_ptr != nullptr; @@ -970,9 +980,10 @@ void nvte_ep_dispatch_gemm_bwd(NVTETensor handle_mem, const NVTETensor grad_gemm // With the weight gradient the GEMM runs alone on every SM, and the weight gradient beside the // dispatch backward. ep::WorkspaceLayout layout; - const ep::EpCombineGemmConfig config{ + ep::EpCombineGemmConfig config{ rows, k, hidden, num_experts, wgrad ? ctx.all_clusters : ctx.num_clusters, n_chunk, !plain, true, scaling_mode, ctx.alignment()}; + config.int64_offsets = int64_offsets; const tvm::ffi::Function gemm = get_gemm(config, &layout); GemmScratch scratch = claim_scratch(ws_base, ws_bytes, layout.total_bytes, num_experts, rows, true, wgrad ? wgrad->layout.total_bytes : 0); @@ -981,7 +992,7 @@ void nvte_ep_dispatch_gemm_bwd(NVTETensor handle_mem, const NVTETensor grad_gemm if (wgrad) { scratch.reset.fill(scratch.wgrad + wgrad->layout.counter, 1, ep::kFillZero); } - set_row_ends(scratch, recv_tokens_per_expert); + set_layout(scratch, expert_token_offsets, int64_offsets); if (requant) { scratch.reset.offsets = scratch.offsets; scratch.reset.offsets_cols = static_cast(hidden); @@ -998,7 +1009,7 @@ void nvte_ep_dispatch_gemm_bwd(NVTETensor handle_mem, const NVTETensor grad_gemm // The GEMM fills the flags; the dispatch backward is its programmatic dependent. auto a = wrap_rowwise(grad_gemm_out, true); auto d = wrap_rowwise(grad_recv_tokens, true); - auto row_ends = wrap_raw(scratch.row_ends, kNVTEInt32, num_experts); + auto row_ends = wrap_row_ends(scratch); auto alpha = wrap_raw(scratch.alpha, kNVTEFloat32, num_experts); auto prob = wrap_raw(scratch.ones, kNVTEFloat32, rows); auto ws = wrap_raw(scratch.base, kNVTEByte, layout.total_bytes); diff --git a/transformer_engine/common/ep/ep_gemm_config.h b/transformer_engine/common/ep/ep_gemm_config.h index 85949409ea9..68f115c0f5e 100644 --- a/transformer_engine/common/ep/ep_gemm_config.h +++ b/transformer_engine/common/ep/ep_gemm_config.h @@ -171,13 +171,14 @@ struct EpDispatchGemmConfig { bool backward; // the second GEMM's data gradient and SwiGLU backward instead of the first GEMM NVTEScalingMode scaling_mode; // operand scaling: delayed for BF16, MXFP8 1D for MXFP8 size_t token_alignment; // rows per expert slab are a multiple of it - // Forward: the dispatch writes the expert offsets and the row total, the word before the row + // Forward: the dispatch writes the expert offsets and the row total, the entry before the row // ends and the row ends, after the caller set them to -1. bool device_layout = false; // MXFP8 backward: writes the columnwise d and h, the weight gradient operands of the first and // second GEMM. bool d_col = true; bool h = true; + bool int64_offsets = false; // the row ends are int64 instead of int32 bool is_mxfp8() const { return scaling_mode == NVTE_MXFP8_1D_SCALING; } @@ -186,7 +187,8 @@ struct EpDispatchGemmConfig { return std::make_tuple(static_cast(rows), static_cast(k), static_cast(n), static_cast(num_experts), num_clusters, backward, static_cast(scaling_mode), - static_cast(token_alignment), device_layout, d_col, h); + static_cast(token_alignment), device_layout, d_col, h, + int64_offsets); } std::string to_key() const { return config_key("ep_dispatch_gemm", args()); } @@ -217,6 +219,7 @@ struct EpCombineGemmConfig { size_t token_alignment; // rows per expert slab are a multiple of it // Clusters launched, 0: num_clusters. Those past num_clusters stop after the first chunk. int grid_clusters = 0; + bool int64_offsets = false; // the row ends are int64 instead of int32 bool is_mxfp8() const { return scaling_mode == NVTE_MXFP8_1D_SCALING; } @@ -226,7 +229,7 @@ struct EpCombineGemmConfig { static_cast(n), static_cast(num_experts), num_clusters, static_cast(n_chunk), dependents_at_entry, backward, static_cast(scaling_mode), - static_cast(token_alignment), grid_clusters); + static_cast(token_alignment), grid_clusters, int64_offsets); } std::string to_key() const { return config_key("ep_combine_gemm", args()); } @@ -262,8 +265,9 @@ struct EpWgradConfig { // descriptors_only writes into the workspace first. NVTEScalingMode scaling_mode; bool descriptors_only; - size_t token_alignment; // rows per expert slab are a multiple of it - size_t routed_tokens; // rows a rank receives at capacity under uniform routing, unpadded + size_t token_alignment; // rows per expert slab are a multiple of it + size_t routed_tokens; // rows a rank receives at capacity under uniform routing, unpadded + bool int64_offsets = false; // the row ends are int64 instead of int32 bool is_mxfp8() const { return scaling_mode == NVTE_MXFP8_1D_SCALING; } @@ -274,7 +278,7 @@ struct EpWgradConfig { static_cast(num_experts), num_clusters, fp32_out, accumulate, wait_primary_at_start, static_cast(signal_unit_tokens), static_cast(scaling_mode), descriptors_only, static_cast(token_alignment), - static_cast(routed_tokens)); + static_cast(routed_tokens), int64_offsets); } std::string to_key() const { return config_key("ep_wgrad", args()); } diff --git a/transformer_engine/common/ep/ep_gemm_utils.h b/transformer_engine/common/ep/ep_gemm_utils.h index af34b9591b2..92b79b6b3ed 100644 --- a/transformer_engine/common/ep/ep_gemm_utils.h +++ b/transformer_engine/common/ep/ep_gemm_utils.h @@ -38,17 +38,29 @@ inline void check_ep_mxfp8_dims(size_t hidden, size_t ffn, size_t alignment) { kMxfp8MinAlignment, " or ", kRowsPerTile); } -// The GEMM reads the per-expert row ends from expert_token_offsets[1:] and requires them 16-byte -// aligned; callers front-pad the [num_experts + 1] int32 layout by 3 elements to achieve that. -inline void check_ep_expert_token_offsets(const NVTETensor expert_token_offsets, - size_t num_experts) { +// The expert layout the GEMMs read: [num_experts + 1] int32 or int64, expert 0's start (0), then +// the row ends from expert_token_offsets[1:], which must start 16-byte aligned. Returns whether +// it is int64. counts, when given, must share its dtype. +inline bool check_ep_expert_token_offsets(const NVTETensor expert_token_offsets, size_t num_experts, + const NVTETensor counts = nullptr) { + NVTE_CHECK(expert_token_offsets != nullptr, "expert_token_offsets must not be null"); + const NVTEDType dtype = nvte_tensor_type(expert_token_offsets); NVTE_CHECK(nvte_tensor_numel(expert_token_offsets) == num_experts + 1 && - nvte_tensor_type(expert_token_offsets) == kNVTEInt32, - "expert_token_offsets must be an int32 tensor of num_experts + 1 elements"); - const int32_t *row_ends = static_cast(nvte_tensor_data(expert_token_offsets)) + 1; + (dtype == kNVTEInt32 || dtype == kNVTEInt64), + "expert_token_offsets must be an int32 or int64 tensor of num_experts + 1 elements"); + const size_t elem = dtype == kNVTEInt64 ? sizeof(int64_t) : sizeof(int32_t); + const auto *row_ends = + static_cast(nvte_tensor_data(expert_token_offsets)) + elem; NVTE_CHECK(reinterpret_cast(row_ends) % 16 == 0, - "expert_token_offsets[1:] (the per-expert row ends) must start 16-byte aligned; " - "front-pad the num_experts + 1 int32 layout by 3 elements"); + "expert_token_offsets[1:] (the per-expert row ends) must start 16-byte aligned"); + if (counts != nullptr) { + NVTE_CHECK(nvte_tensor_shape(counts).ndim == 1 && nvte_tensor_numel(counts) == num_experts, + "recv_tokens_per_expert must be a 1-D tensor of num_experts elements"); + NVTE_CHECK(nvte_tensor_type(counts) == dtype, + "recv_tokens_per_expert and expert_token_offsets must share a dtype, int32 or " + "int64"); + } + return dtype == kNVTEInt64; } } // namespace ep diff --git a/transformer_engine/common/ep/ep_overlap_workspace.cu b/transformer_engine/common/ep/ep_overlap_workspace.cu index 4d78c6b662a..06f52d0d748 100644 --- a/transformer_engine/common/ep/ep_overlap_workspace.cu +++ b/transformer_engine/common/ep/ep_overlap_workspace.cu @@ -5,7 +5,6 @@ ************************************************************************/ #include -#include #include "../util/logging.h" #include "ep_overlap_workspace.h" @@ -29,30 +28,29 @@ __global__ void reset_workspace_kernel(WorkspaceReset reset) { } } } - if (blockIdx.x != 0 || reset.counts == nullptr) { + if (blockIdx.x != 0 || reset.layout == nullptr) { return; } - // Inclusive prefix sum, kThreads experts per step. - if (reset.offsets != nullptr && tid == 0) { - reset.offsets[0] = 0; - } - using BlockScan = cub::BlockScan; - __shared__ typename BlockScan::TempStorage scan_storage; - int32_t running = 0; - for (int first = 0; first < reset.num_experts; first += kThreads) { - const int e = first + tid; - const int32_t count = e < reset.num_experts ? reset.counts[e] : 0; - int32_t row_end = 0; - int32_t step_total = 0; - BlockScan(scan_storage).InclusiveSum(count, row_end, step_total); - if (e < reset.num_experts) { - reset.row_ends[e] = running + row_end; - if (reset.offsets != nullptr) { - reset.offsets[e + 1] = static_cast(running + row_end) * reset.offsets_cols; - } + const int64_t num_experts = reset.num_experts; + const auto load = [&](const void* p, int64_t i) -> int64_t { + return reset.layout_int64 ? static_cast(p)[i] + : static_cast(p)[i]; + }; + // TODO(phuonguyen): drop offsets + counts once NCCL EP outputs the final post-drop num total + // recv tokens, and read the row ends straight from NCCL EP. + if (reset.counts != nullptr && tid == 0) { + const int64_t end = load(reset.layout, num_experts - 1) + load(reset.counts, num_experts - 1); + if (reset.layout_int64) { + static_cast(reset.layout)[num_experts] = end; + } else { + static_cast(reset.layout)[num_experts] = static_cast(end); } - running += step_total; + } + if (reset.offsets != nullptr) { __syncthreads(); + for (int64_t e = tid; e <= num_experts; e += kThreads) { + reset.offsets[e] = load(reset.layout, e) * reset.offsets_cols; + } } } diff --git a/transformer_engine/common/ep/ep_overlap_workspace.h b/transformer_engine/common/ep/ep_overlap_workspace.h index c5cdd047d63..e333197b4e4 100644 --- a/transformer_engine/common/ep/ep_overlap_workspace.h +++ b/transformer_engine/common/ep/ep_overlap_workspace.h @@ -19,8 +19,8 @@ constexpr int32_t kFillZero = 0; constexpr int32_t kFillMinusOne = -1; constexpr int32_t kFillOne = 0x3F800000; -// The words one launch writes before a call: constant fills and, optionally, the expert row ends -// as the inclusive prefix sums of the padded int32 counts. +// The words one launch writes before a call: constant fills and, optionally, the final post-drop +// num total recv tokens of an expert layout and the requant element offsets read from it. struct WorkspaceReset { static constexpr int kMaxFills = 8; struct Fill { @@ -30,11 +30,15 @@ struct WorkspaceReset { }; Fill fills[kMaxFills]; int num_fills = 0; - const int32_t* counts = nullptr; // [num_experts] padded counts; null: no row ends - int32_t* row_ends = nullptr; // [num_experts] row ends + // Expert layout [num_experts + 1] of int32 or int64: expert 0's start (0), then the row ends. + void* layout = nullptr; + bool layout_int64 = false; int num_experts = 0; - // Optional [num_experts + 1] element offsets of the requant grouped tensor: [0, row_ends * cols]. - // Written alongside the row ends when offsets is non-null. + // Optional [num_experts] padded counts of the layout's dtype. The reset writes the final + // post-drop num total recv tokens, layout[num_experts] = layout[num_experts - 1] + + // counts[num_experts - 1]. + const void* counts = nullptr; + // Optional [num_experts + 1] int64 element offsets of the requant grouped tensor: layout * cols. int64_t* offsets = nullptr; int64_t offsets_cols = 0; @@ -42,7 +46,7 @@ struct WorkspaceReset { void fill(void* words, int count, int32_t value); }; -// One launch performing every fill and the row-ends scan of reset. +// One launch performing every fill and the layout writes of reset. void reset_workspace(const WorkspaceReset& reset, cudaStream_t stream); } // namespace ep diff --git a/transformer_engine/common/include/transformer_engine/ep.h b/transformer_engine/common/include/transformer_engine/ep.h index 6d7099c5104..c03bedd3420 100644 --- a/transformer_engine/common/include/transformer_engine/ep.h +++ b/transformer_engine/common/include/transformer_engine/ep.h @@ -162,12 +162,16 @@ size_t nvte_ep_handle_mem_size(const NVTEEpLayerConfig* layer_cfg); * \param[out] recv_tokens_per_expert [num_local_experts] int32/int64 counts. * \param[out] total_recv_tokens_per_rank Optional [1] int32/int64 scalar: padded * recv-slot total for this rank. May be null. + * \param[out] expert_offsets Optional [num_local_experts] int32/int64 padded + * start row of each expert. May be null. * \param[in] layer_cfg Per-call layer configuration (struct_size set). * \param[in] stream CUDA stream. + * + * The int outputs share one dtype. */ void nvte_ep_prepare(NVTETensor handle_mem, NVTETensor topk_idx, NVTETensor recv_tokens_per_expert, - NVTETensor total_recv_tokens_per_rank, const NVTEEpLayerConfig* layer_cfg, - cudaStream_t stream); + NVTETensor total_recv_tokens_per_rank, NVTETensor expert_offsets, + const NVTEEpLayerConfig* layer_cfg, cudaStream_t stream); /*! \brief Dispatch tokens (and routing weights) to expert ranks. * diff --git a/transformer_engine/common/include/transformer_engine/ep_gemm.h b/transformer_engine/common/include/transformer_engine/ep_gemm.h index 526b0cad580..4bf19cce3f2 100644 --- a/transformer_engine/common/include/transformer_engine/ep_gemm.h +++ b/transformer_engine/common/include/transformer_engine/ep_gemm.h @@ -77,18 +77,20 @@ extern "C" { * \param[out] recv_topk_weights [recv_capacity] float32 per-row routing weights. * \param[out] gemm_out [recv_capacity, 2 * ffn_dim] GEMM output. * \param[out] act_out [recv_capacity, ffn_dim] SwiGLU output. - * \param[in,out] recv_tokens_per_expert [num_local_experts] int32 padded counts. Eager mode - * provides them to build the expert layout; capacity mode - * writes them, from the dispatch when there are no drops and - * at most 2048 local experts, else from the routing prepare. - * \param[out] expert_token_offsets [num_local_experts + 1] int32 expert layout in tokens - * (rows): expert 0's start (0), then each expert's padded - * row end, the GEMM operand. expert_token_offsets[1:] must - * start 16-byte aligned, so front-pad the allocation by 3 - * int32 elements. Capacity mode writes it; eager mode builds - * it from recv_tokens_per_expert. The last element is the - * recv total; the per-expert counts are its diffs. - * \param[out] total_recv_tokens [1] int32 recv total before any overflow drop, or null. + * \param[in,out] recv_tokens_per_expert [num_local_experts] int32 or int64 padded counts, the + * dtype of expert_token_offsets. Eager mode passes the ones + * nvte_ep_prepare wrote; capacity mode writes them, from the + * dispatch when there are no drops and at most 2048 local + * experts, else from the routing prepare. + * \param[in,out] expert_token_offsets [num_local_experts + 1] int32 or int64 expert layout in + * tokens (rows): expert 0's start (0), then each expert's + * padded row end, the GEMM operand. expert_token_offsets[1:] + * must start 16-byte aligned. NCCL EP writes the starts + * (eager mode: nvte_ep_prepare); the last entry, the final + * post-drop num total recv tokens, is the dispatch's total + * or the last start plus the last count. + * \param[out] total_recv_tokens [1] recv total before any overflow drop, of the + * expert_token_offsets dtype, or null. * The routing prepare writes it; when the dispatch writes * expert_token_offsets instead (no drops), it is * expert_token_offsets[-1], the padded total of the kept @@ -125,7 +127,7 @@ void nvte_ep_dispatch_gemm_fwd(NVTETensor handle_mem, const NVTETensor topk_idx, * nvte_ep_dispatch_gemm_fwd, bfloat16 or MXFP8. * \param[in] recv_topk_weights [recv_capacity] float32 per-row routing weights; null for * unit weights (bfloat16 act_out carries them). - * \param[in] expert_token_offsets [num_local_experts + 1] int32 expert layout from + * \param[in] expert_token_offsets [num_local_experts + 1] int32 or int64 expert layout from * nvte_ep_dispatch_gemm_fwd (the GEMM reads its row ends); * expert_token_offsets[1:] must start 16-byte aligned. * \param[in] weight [num_local_experts, hidden_dim, ffn_dim] weights. @@ -167,7 +169,8 @@ void nvte_ep_combine_gemm_fwd(NVTETensor handle_mem, const NVTETensor gemm_in, * \param[in] gemm_out [recv_capacity, 2 * ffn_dim] gemm_out of * nvte_ep_dispatch_gemm_fwd. * \param[in] recv_topk_weights [recv_capacity] float32 per-row routing weights. - * \param[in] recv_tokens_per_expert [num_local_experts] int32 padded counts. + * \param[in] expert_token_offsets [num_local_experts + 1] expert layout of + * nvte_ep_dispatch_gemm_fwd. * \param[in] weight [num_local_experts, hidden_dim, ffn_dim] forward weights. * \param[in] wgrad_input [recv_capacity, ffn_dim] bfloat16 act_out of * nvte_ep_dispatch_gemm_fwd, or MXFP8 act_out of this @@ -196,7 +199,7 @@ void nvte_ep_combine_gemm_fwd(NVTETensor handle_mem, const NVTETensor gemm_in, void nvte_ep_combine_gemm_bwd( NVTETensor handle_mem, const NVTETensor grad_result, NVTECommWindow grad_result_win, const NVTETensor gemm_out, const NVTETensor recv_topk_weights, - const NVTETensor recv_tokens_per_expert, const NVTETensor weight, const NVTETensor wgrad_input, + const NVTETensor expert_token_offsets, const NVTETensor weight, const NVTETensor wgrad_input, NVTETensor grad_expert_out, NVTETensor grad_gemm_out, NVTETensor grad_recv_topk_weights, NVTETensor act_out, NVTETensor weight_grad, int accumulate_weight_grad, NVTETensor workspace, NVTE_Activation_Type activation, const NVTEEpLayerConfig* layer_cfg, cudaStream_t stream); @@ -223,7 +226,8 @@ void nvte_ep_combine_gemm_bwd( * nvte_ep_combine_gemm_bwd; MXFP8 with weight_grad: also * columnwise. * \param[in] grad_recv_topk_weights [recv_capacity] float32 from nvte_ep_combine_gemm_bwd. - * \param[in] recv_tokens_per_expert [num_local_experts] int32 padded counts. + * \param[in] expert_token_offsets [num_local_experts + 1] expert layout of + * nvte_ep_dispatch_gemm_fwd. * \param[in] weight [num_local_experts, 2 * ffn_dim, hidden_dim] forward * weights. * \param[in,out] wgrad_input [recv_capacity, hidden_dim] recv_tokens of @@ -243,7 +247,7 @@ void nvte_ep_combine_gemm_bwd( */ void nvte_ep_dispatch_gemm_bwd(NVTETensor handle_mem, const NVTETensor grad_gemm_out, const NVTETensor grad_recv_topk_weights, - const NVTETensor recv_tokens_per_expert, const NVTETensor weight, + const NVTETensor expert_token_offsets, const NVTETensor weight, const NVTETensor wgrad_input, NVTETensor grad_recv_tokens, NVTETensor grad_tokens, NVTETensor grad_topk_weights, NVTETensor weight_grad, int accumulate_weight_grad, diff --git a/transformer_engine/jax/csrc/extensions/ep.cpp b/transformer_engine/jax/csrc/extensions/ep.cpp index 00a248de528..1e41680d5de 100644 --- a/transformer_engine/jax/csrc/extensions/ep.cpp +++ b/transformer_engine/jax/csrc/extensions/ep.cpp @@ -334,7 +334,7 @@ Error_Type EpPrepareFFI(cudaStream_t stream, EpInstanceState* ep_state, Buffer_T .topk_idx_dtype = static_cast(config.topk_idx_dtype)}; return ffi_guard("EP prepare failed: ", [&] { nvte_ep_prepare(handle_mem_.data(), topk_idx_.data(), recv_tokens_per_expert_.data(), - total_recv_tokens_.data(), &layer_cfg, stream); + total_recv_tokens_.data(), nullptr, &layer_cfg, stream); }); } diff --git a/transformer_engine/pytorch/csrc/extensions.h b/transformer_engine/pytorch/csrc/extensions.h index b7e934e091f..f765e2c3da8 100644 --- a/transformer_engine/pytorch/csrc/extensions.h +++ b/transformer_engine/pytorch/csrc/extensions.h @@ -780,7 +780,8 @@ int64_t ep_handle_mem_size(int64_t top_k, int64_t dispatch_output_per_expert_ali void ep_prepare(at::Tensor handle_mem, at::Tensor topk_idx, at::Tensor tokens_per_expert, int64_t top_k, int64_t dispatch_output_per_expert_alignment, - at::Tensor total_recv_tokens); + at::Tensor total_recv_tokens, + std::optional expert_offsets = std::nullopt); void ep_dispatch(at::Tensor handle_mem, at::Tensor topk_idx, at::Tensor tokens, at::Tensor topk_weights, at::Tensor recv_tokens, at::Tensor recv_topk_weights, diff --git a/transformer_engine/pytorch/csrc/extensions/ep.cpp b/transformer_engine/pytorch/csrc/extensions/ep.cpp index 3192d0f633e..8c2fb20b880 100644 --- a/transformer_engine/pytorch/csrc/extensions/ep.cpp +++ b/transformer_engine/pytorch/csrc/extensions/ep.cpp @@ -433,12 +433,11 @@ int64_t ep_handle_mem_size(int64_t top_k, int64_t dispatch_output_per_expert_ali void ep_prepare(at::Tensor handle_mem, at::Tensor topk_idx, at::Tensor tokens_per_expert, int64_t top_k, int64_t dispatch_output_per_expert_alignment, - at::Tensor total_recv_tokens) { + at::Tensor total_recv_tokens, std::optional expert_offsets) { auto stream = at::cuda::getCurrentCUDAStream().stream(); NVTE_CHECK(topk_idx.dim() >= 2, "topk_idx must be at least 2D [..., top_k]"); auto idx_dtype = get_contiguous_topk_idx_te_dtype(topk_idx); - // NCCL EP requires all prepare int output counters to share a dtype: int64, or int32 for the - // overlapped GEMMs. + // NCCL EP requires all prepare int outputs to share a dtype, int32 or int64. NVTE_CHECK( tokens_per_expert.scalar_type() == at::kLong || tokens_per_expert.scalar_type() == at::kInt, "tokens_per_expert must be int64 or int32"); @@ -460,10 +459,23 @@ void ep_prepare(at::Tensor handle_mem, at::Tensor topk_idx, at::Tensor tokens_pe auto total_recv_tokens_te = makeTransformerEngineTensor( total_recv_tokens.data_ptr(), Shape{static_cast(total_recv_tokens.numel())}, count_dtype); + // [num_local_experts] padded start row of each expert, for the overlapped GEMMs' layout. + TensorWrapper expert_offsets_te; + if (expert_offsets.has_value()) { + NVTE_CHECK(expert_offsets->scalar_type() == tokens_per_expert.scalar_type() && + expert_offsets->numel() == tokens_per_expert.numel() && + expert_offsets->is_contiguous(), + "expert_offsets must be contiguous with the dtype and size of tokens_per_expert"); + expert_offsets_te = makeTransformerEngineTensor( + expert_offsets->data_ptr(), Shape{static_cast(expert_offsets->numel())}, + count_dtype); + } auto layer_cfg = make_layer_cfg(top_k, dispatch_output_per_expert_alignment, idx_dtype); nvte_ep_prepare(handle_mem_te.data(), topk_idx_te.data(), tokens_per_expert_te.data(), - total_recv_tokens_te.data(), &layer_cfg, stream); + total_recv_tokens_te.data(), + expert_offsets.has_value() ? expert_offsets_te.data() : nullptr, &layer_cfg, + stream); } // tokens_scale_inv / recv_scale_inv are set only for block-scaled dispatch (for @@ -907,17 +919,18 @@ at::Tensor overlap_workspace(int64_t hidden_dim, int64_t ffn_dim, int64_t num_lo // MXFP8 operands are MXFP8 tensors (their data, scales and scale layout travel with them), BF16 // ones torch tensors; every operand of a call is of the one kind. The weights are // [experts, out_features, in_features]. -at::Tensor ep_dispatch_gemm_fwd(at::Tensor handle_mem, at::Tensor topk_idx, py::object tokens, - at::Tensor topk_weights, py::object weight, py::object recv_tokens, - at::Tensor recv_topk_weights, at::Tensor tokens_per_expert, - at::Tensor gemm_out, py::object act_out, int64_t top_k, - int64_t dispatch_output_per_expert_alignment, - std::optional total_recv_tokens, bool symm_input) { +void ep_dispatch_gemm_fwd(at::Tensor handle_mem, at::Tensor topk_idx, py::object tokens, + at::Tensor topk_weights, py::object weight, py::object recv_tokens, + at::Tensor recv_topk_weights, at::Tensor tokens_per_expert, + at::Tensor expert_token_offsets, at::Tensor gemm_out, py::object act_out, + int64_t top_k, int64_t dispatch_output_per_expert_alignment, + std::optional total_recv_tokens, bool symm_input) { check_cuda_operands({{"handle_mem", operand(handle_mem)}, {"topk_idx", operand(topk_idx)}, {"topk_weights", operand(topk_weights)}, {"recv_topk_weights", operand(recv_topk_weights)}, {"tokens_per_expert", operand(tokens_per_expert)}, + {"expert_token_offsets", operand(expert_token_offsets)}, {"gemm_out", operand(gemm_out)}}); check_cuda_object("tokens", tokens); check_cuda_object("weight", weight); @@ -928,8 +941,6 @@ at::Tensor ep_dispatch_gemm_fwd(at::Tensor handle_mem, at::Tensor topk_idx, py:: NVTE_CHECK(is_mxfp8_object(weight) == mxfp8 && is_mxfp8_object(recv_tokens) == mxfp8 && is_mxfp8_object(act_out) == mxfp8, "pass all of tokens, weight, recv_tokens and act_out as MXFP8 tensors, or none"); - NVTE_CHECK(!total_recv_tokens.has_value() || total_recv_tokens->scalar_type() == at::kInt, - "total_recv_tokens must be int32"); NVTE_CHECK(!total_recv_tokens.has_value() || total_recv_tokens->is_pinned() || (total_recv_tokens->is_cuda() && total_recv_tokens->device().index() == c10::cuda::current_device()), @@ -958,12 +969,8 @@ at::Tensor ep_dispatch_gemm_fwd(at::Tensor handle_mem, at::Tensor topk_idx, py:: "recv_tokens, recv_topk_weights, gemm_out and act_out must have the rows of the " "recv buffer and the hidden, 2 * ffn and ffn columns of the operands"); check_dense_cuda(tokens_per_expert, "tokens_per_expert"); + check_dense_cuda(expert_token_offsets, "expert_token_offsets"); check_dense_cuda(recv_topk_weights, "recv_topk_weights"); - // The expert layout the GEMMs read: expert 0's start (0), then each expert's padded row end. - // Front-pad by 3 so the row ends (expert_token_offsets[1:]) start 16-byte aligned, as the GEMM - // needs. - auto expert_token_offsets = - at::empty({num_experts + 4}, tokens_per_expert.options().dtype(at::kInt)).slice(0, 3); auto handle_mem_te = makeTransformerEngineTensor(handle_mem); auto topk_idx_te = makeTransformerEngineTensor(topk_idx); auto topk_weights_te = makeTransformerEngineTensor(topk_weights); @@ -971,7 +978,7 @@ at::Tensor ep_dispatch_gemm_fwd(at::Tensor handle_mem, at::Tensor topk_idx, py:: auto tokens_per_expert_te = makeTransformerEngineTensor(tokens_per_expert); auto gemm_out_te = makeTransformerEngineTensor(gemm_out); auto expert_token_offsets_te = makeTransformerEngineTensor(expert_token_offsets); - // Eager: the prepare before this call wrote the total. + // Eager: the prepare before this call wrote the total and the expert starts. TensorWrapper total_recv_tokens_te; if (total_recv_tokens.has_value()) { total_recv_tokens_te = makeTransformerEngineTensor(*total_recv_tokens); @@ -993,7 +1000,6 @@ at::Tensor ep_dispatch_gemm_fwd(at::Tensor handle_mem, at::Tensor topk_idx, py:: total_recv_tokens.has_value() ? total_recv_tokens_te.data() : nullptr, workspace_te.data(), NVTE_Activation_Type::SWIGLU, &layer_cfg, stream); } - return expert_token_offsets; } void ep_combine_gemm_fwd(at::Tensor handle_mem, py::object gemm_in, at::Tensor expert_token_offsets, @@ -1053,7 +1059,7 @@ void ep_combine_gemm_fwd(at::Tensor handle_mem, py::object gemm_in, at::Tensor e // gradient is computed, and grad_gemm_out rowwise with swizzled scales. The columnwise // grad_gemm_out and act_out, the weight gradient operands, are written when given. void ep_combine_gemm_bwd(at::Tensor handle_mem, py::object grad_result, at::Tensor gemm_out, - at::Tensor recv_topk_weights, at::Tensor tokens_per_expert, + at::Tensor recv_topk_weights, at::Tensor expert_token_offsets, py::object weight, py::object grad_expert_out, py::object grad_gemm_out, at::Tensor grad_recv_topk_weights, int64_t top_k, int64_t dispatch_output_per_expert_alignment, @@ -1064,7 +1070,7 @@ void ep_combine_gemm_bwd(at::Tensor handle_mem, py::object grad_result, at::Tens check_cuda_operands({{"handle_mem", operand(handle_mem)}, {"gemm_out", operand(gemm_out)}, {"recv_topk_weights", operand(recv_topk_weights)}, - {"tokens_per_expert", operand(tokens_per_expert)}, + {"expert_token_offsets", operand(expert_token_offsets)}, {"grad_recv_topk_weights", operand(grad_recv_topk_weights)}, {"weight_grad", operand(weight_grad)}}); check_cuda_object("grad_result", grad_result); @@ -1075,7 +1081,7 @@ void ep_combine_gemm_bwd(at::Tensor handle_mem, py::object grad_result, at::Tens check_cuda_object("wgrad_input", wgrad_input); auto stream = at::cuda::getCurrentCUDAStream().stream(); NVTE_CHECK(gemm_out.is_contiguous(), "gemm_out must be contiguous"); - check_dense_cuda(tokens_per_expert, "tokens_per_expert"); + check_dense_cuda(expert_token_offsets, "expert_token_offsets"); check_dense_cuda(grad_recv_topk_weights, "grad_recv_topk_weights"); const bool mxfp8 = is_mxfp8_object(grad_result); NVTE_CHECK(is_mxfp8_object(weight) == mxfp8 && is_mxfp8_object(grad_expert_out) == mxfp8 && @@ -1087,7 +1093,7 @@ void ep_combine_gemm_bwd(at::Tensor handle_mem, py::object grad_result, at::Tens auto grad_result_te = compact_scales_operand(grad_result); auto gemm_out_te = makeTransformerEngineTensor(gemm_out); auto recv_topk_weights_te = makeTransformerEngineTensor(recv_topk_weights); - auto tokens_per_expert_te = makeTransformerEngineTensor(tokens_per_expert); + auto expert_token_offsets_te = makeTransformerEngineTensor(expert_token_offsets); auto grad_expert_out_te = operand_tensor(grad_expert_out); auto grad_gemm_out_te = operand_tensor(grad_gemm_out); auto grad_recv_topk_weights_te = makeTransformerEngineTensor(grad_recv_topk_weights); @@ -1096,7 +1102,7 @@ void ep_combine_gemm_bwd(at::Tensor handle_mem, py::object grad_result, at::Tens act_out_te = operand_tensor(*act_out); } // The weight is [experts, hidden, ffn], and grad_gemm_out is [rows, 2 * ffn]. - auto weight_te = weight_operand(weight, tokens_per_expert.numel(), + auto weight_te = weight_operand(weight, expert_token_offsets.numel() - 1, mxfp8 ? grad_gemm_out_te.shape().data[1] / 2 : 0); WeightGradTensors wgrad(wgrad_input, weight_grad); const NVTECommWindow grad_result_win = symm_input ? make_input_window(grad_result) : kNoWindow; @@ -1107,12 +1113,12 @@ void ep_combine_gemm_bwd(at::Tensor handle_mem, py::object grad_result, at::Tens auto workspace_t = overlap_workspace(weight_shape.data[1], weight_shape.data[2], weight_shape.data[0], grad_expert_out_te.shape().data[0], weight_grad.has_value(), mxfp8, - layer_cfg, tokens_per_expert); + layer_cfg, expert_token_offsets); auto workspace_te = makeTransformerEngineTensor(workspace_t); py::gil_scoped_release release; nvte_ep_combine_gemm_bwd( handle_mem_te.data(), grad_result_te.data(), grad_result_win, gemm_out_te.data(), - recv_topk_weights_te.data(), tokens_per_expert_te.data(), weight_te.data(), wgrad.input(), + recv_topk_weights_te.data(), expert_token_offsets_te.data(), weight_te.data(), wgrad.input(), grad_expert_out_te.data(), grad_gemm_out_te.data(), grad_recv_topk_weights_te.data(), act_out.has_value() ? act_out_te.data() : nullptr, wgrad.output(), accumulate_weight_grad, workspace_te.data(), NVTE_Activation_Type::SWIGLU, &layer_cfg, stream); @@ -1123,7 +1129,7 @@ void ep_combine_gemm_bwd(at::Tensor handle_mem, py::object grad_result, at::Tens // of the weight gradient; when it also holds the rowwise data (compact scales), the call writes the // columnwise data from there. void ep_dispatch_gemm_bwd(at::Tensor handle_mem, py::object grad_gemm_out, - at::Tensor grad_recv_topk_weights, at::Tensor tokens_per_expert, + at::Tensor grad_recv_topk_weights, at::Tensor expert_token_offsets, py::object weight, at::Tensor grad_recv_tokens, at::Tensor grad_tokens, at::Tensor grad_topk_weights, int64_t top_k, int64_t dispatch_output_per_expert_alignment, @@ -1131,7 +1137,7 @@ void ep_dispatch_gemm_bwd(at::Tensor handle_mem, py::object grad_gemm_out, std::optional weight_grad, bool accumulate_weight_grad) { check_cuda_operands({{"handle_mem", operand(handle_mem)}, {"grad_recv_topk_weights", operand(grad_recv_topk_weights)}, - {"tokens_per_expert", operand(tokens_per_expert)}, + {"expert_token_offsets", operand(expert_token_offsets)}, {"grad_recv_tokens", operand(grad_recv_tokens)}, {"grad_tokens", operand(grad_tokens)}, {"grad_topk_weights", operand(grad_topk_weights)}, @@ -1141,7 +1147,7 @@ void ep_dispatch_gemm_bwd(at::Tensor handle_mem, py::object grad_gemm_out, check_cuda_object("wgrad_input", wgrad_input); auto stream = at::cuda::getCurrentCUDAStream().stream(); NVTE_CHECK(grad_recv_tokens.is_contiguous(), "grad_recv_tokens must be contiguous"); - check_dense_cuda(tokens_per_expert, "tokens_per_expert"); + check_dense_cuda(expert_token_offsets, "expert_token_offsets"); check_dense_cuda(grad_recv_topk_weights, "grad_recv_topk_weights"); const bool mxfp8 = is_mxfp8_object(grad_gemm_out); NVTE_CHECK(is_mxfp8_object(weight) == mxfp8 && @@ -1150,8 +1156,9 @@ void ep_dispatch_gemm_bwd(at::Tensor handle_mem, py::object grad_gemm_out, auto handle_mem_te = makeTransformerEngineTensor(handle_mem); auto grad_gemm_out_te = operand_tensor(grad_gemm_out); auto grad_recv_topk_weights_te = makeTransformerEngineTensor(grad_recv_topk_weights); - auto tokens_per_expert_te = makeTransformerEngineTensor(tokens_per_expert); - auto weight_te = weight_operand(weight, tokens_per_expert.numel(), grad_recv_tokens.size(1)); + auto expert_token_offsets_te = makeTransformerEngineTensor(expert_token_offsets); + auto weight_te = + weight_operand(weight, expert_token_offsets.numel() - 1, grad_recv_tokens.size(1)); auto grad_recv_tokens_te = makeTransformerEngineTensor(grad_recv_tokens); auto grad_tokens_te = makeTransformerEngineTensor(grad_tokens); auto grad_topk_weights_te = makeTransformerEngineTensor(grad_topk_weights); @@ -1164,11 +1171,11 @@ void ep_dispatch_gemm_bwd(at::Tensor handle_mem, py::object grad_gemm_out, auto workspace_t = overlap_workspace(weight_shape.data[2], weight_shape.data[1] / 2, weight_shape.data[0], grad_gemm_out_te.shape().data[0], weight_grad.has_value(), mxfp8, layer_cfg, - tokens_per_expert); + expert_token_offsets); auto workspace_te = makeTransformerEngineTensor(workspace_t); py::gil_scoped_release release; nvte_ep_dispatch_gemm_bwd(handle_mem_te.data(), grad_gemm_out_te.data(), - grad_recv_topk_weights_te.data(), tokens_per_expert_te.data(), + grad_recv_topk_weights_te.data(), expert_token_offsets_te.data(), weight_te.data(), wgrad.input(), grad_recv_tokens_te.data(), grad_tokens_te.data(), grad_topk_weights_te.data(), wgrad.output(), accumulate_weight_grad, workspace_te.data(), &layer_cfg, stream); @@ -1195,7 +1202,7 @@ void register_ep_bindings(pybind11::module_& m) { m.def("ep_prepare", &ep_prepare, "EP prepare", py::arg("handle_mem"), py::arg("topk_idx"), py::arg("tokens_per_expert"), py::arg("top_k"), py::arg("dispatch_output_per_expert_alignment"), py::arg("total_recv_tokens"), - py::call_guard()); + py::arg("expert_offsets") = std::nullopt, py::call_guard()); m.def("ep_dispatch", &ep_dispatch, "EP dispatch", py::arg("handle_mem"), py::arg("topk_idx"), py::arg("tokens"), py::arg("topk_weights"), py::arg("recv_tokens"), py::arg("recv_topk_weights"), py::arg("top_k"), @@ -1211,11 +1218,11 @@ void register_ep_bindings(pybind11::module_& m) { py::arg("result"), py::arg("top_k"), py::arg("dispatch_output_per_expert_alignment"), py::arg("topk_idx_dtype"), py::call_guard()); m.def("ep_dispatch_gemm_fwd", &ep_dispatch_gemm_fwd, - "EP dispatch overlapped with the first GEMM; returns expert_token_offsets", + "EP dispatch overlapped with the first GEMM; writes the expert layout expert_token_offsets", py::arg("handle_mem"), py::arg("topk_idx"), py::arg("tokens"), py::arg("topk_weights"), py::arg("weight"), py::arg("recv_tokens"), py::arg("recv_topk_weights"), - py::arg("tokens_per_expert"), py::arg("gemm_out"), py::arg("act_out"), py::arg("top_k"), - py::arg("dispatch_output_per_expert_alignment"), + py::arg("tokens_per_expert"), py::arg("expert_token_offsets"), py::arg("gemm_out"), + py::arg("act_out"), py::arg("top_k"), py::arg("dispatch_output_per_expert_alignment"), py::arg("total_recv_tokens") = std::nullopt, py::arg("symm_input") = false); m.def("ep_combine_gemm_fwd", &ep_combine_gemm_fwd, "EP second GEMM overlapped with the combine", py::arg("handle_mem"), py::arg("gemm_in"), py::arg("expert_token_offsets"), @@ -1225,7 +1232,7 @@ void register_ep_bindings(pybind11::module_& m) { m.def("ep_combine_gemm_bwd", &ep_combine_gemm_bwd, "Backward of the second GEMM and the combine, with the activation backward", py::arg("handle_mem"), py::arg("grad_result"), py::arg("gemm_out"), - py::arg("recv_topk_weights"), py::arg("tokens_per_expert"), py::arg("weight"), + py::arg("recv_topk_weights"), py::arg("expert_token_offsets"), py::arg("weight"), py::arg("grad_expert_out"), py::arg("grad_gemm_out"), py::arg("grad_recv_topk_weights"), py::arg("top_k"), py::arg("dispatch_output_per_expert_alignment"), py::arg("topk_idx_dtype"), py::arg("act_out") = std::nullopt, @@ -1233,9 +1240,9 @@ void register_ep_bindings(pybind11::module_& m) { py::arg("accumulate_weight_grad") = false, py::arg("symm_input") = false); m.def("ep_dispatch_gemm_bwd", &ep_dispatch_gemm_bwd, "Backward of the first GEMM and the dispatch", py::arg("handle_mem"), - py::arg("grad_gemm_out"), py::arg("grad_recv_topk_weights"), py::arg("tokens_per_expert"), - py::arg("weight"), py::arg("grad_recv_tokens"), py::arg("grad_tokens"), - py::arg("grad_topk_weights"), py::arg("top_k"), + py::arg("grad_gemm_out"), py::arg("grad_recv_topk_weights"), + py::arg("expert_token_offsets"), py::arg("weight"), py::arg("grad_recv_tokens"), + py::arg("grad_tokens"), py::arg("grad_topk_weights"), py::arg("top_k"), py::arg("dispatch_output_per_expert_alignment"), py::arg("topk_idx_dtype"), py::arg("wgrad_input") = std::nullopt, py::arg("weight_grad") = std::nullopt, py::arg("accumulate_weight_grad") = false); diff --git a/transformer_engine/pytorch/ep.py b/transformer_engine/pytorch/ep.py index b98b9d9d46d..1b770dff99d 100644 --- a/transformer_engine/pytorch/ep.py +++ b/transformer_engine/pytorch/ep.py @@ -374,8 +374,6 @@ class EpBuffer: "zero_copy", "eager", "total_recv_tokens", - "tokens_per_expert_i32", - "total_recv_tokens_i32", "dispatch_fwd_quant_recipe", "combine_bwd_quant_recipe", ) @@ -440,17 +438,6 @@ def __init__( else: self.total_recv_tokens = torch.empty(1, dtype=torch.int64, device=device) mark_not_offload(self.total_recv_tokens) - # Int32 per-expert counts and recv total for the fused MoE overlap, placed as above. - # TODO(phuonguyen): drop these int32 mirrors of tokens_per_expert and total_recv_tokens, - # and write those directly, once the CuTeDSL signal GEMMs accept int64 counts/offsets. - self.tokens_per_expert_i32 = torch.empty( - self.num_local_experts, dtype=torch.int32, device=device - ) - if self.eager: - self.total_recv_tokens_i32 = torch.empty(1, dtype=torch.int32, pin_memory=True) - else: - self.total_recv_tokens_i32 = torch.empty(1, dtype=torch.int32, device=device) - mark_not_offload(self.total_recv_tokens_i32) # torch.library custom ops (so they don't graph-break under torch.compile) diff --git a/transformer_engine/pytorch/ops/fused/moe_overlap.py b/transformer_engine/pytorch/ops/fused/moe_overlap.py index 54c10c9d925..50a9608cfc8 100644 --- a/transformer_engine/pytorch/ops/fused/moe_overlap.py +++ b/transformer_engine/pytorch/ops/fused/moe_overlap.py @@ -178,14 +178,21 @@ def fuser_forward( self._check_runtime_support(backward) topk_idx = _require_contiguous(topk_idx, "topk_idx") topk_weights = _require_contiguous(topk_weights, "topk_weights") - tokens_per_expert = buffer.tokens_per_expert_i32 + tokens_per_expert = buffer.tokens_per_expert + # The expert layout the GEMMs read, in the counts' dtype: expert 0's start (0), then each + # expert's padded row end. Front-pad so the row ends (expert_token_offsets[1:]) start + # 16-byte aligned. + pad = 16 // tokens_per_expert.element_size() - 1 + expert_token_offsets = torch.empty( + buffer.num_local_experts + 1 + pad, dtype=tokens_per_expert.dtype, device=device + )[pad:] if buffer.eager: - # The prepare writes the recv total to pinned host memory. Launch it first and mark its - # completion with an event, so the weight and input preparation below overlaps it; - # only the total read waits. + # The prepare writes the recv total to pinned host memory, and the expert starts. + # Launch it first and mark its completion with an event, so the weight and input + # preparation below overlaps it; only the total read waits. tex.ep_prepare( buffer.handle_mem, topk_idx, tokens_per_expert, buffer.top_k, buffer.alignment, - buffer.total_recv_tokens_i32, + buffer.total_recv_tokens, expert_token_offsets[:-1], ) # fmt: skip prepared = torch.cuda.Event() prepared.record() @@ -195,24 +202,19 @@ def fuser_forward( if buffer.eager: # Size the recv rows in whole buckets, so the number of compiled GEMMs stays bounded. prepared.synchronize() - total = int(buffer.total_recv_tokens_i32.item()) + total = int(buffer.total_recv_tokens.item()) rows = max(-(-total // _EAGER_ROW_BUCKET), 1) * _EAGER_ROW_BUCKET total_recv_tokens = None else: rows = buffer.recv_capacity_per_rank - total_recv_tokens = buffer.total_recv_tokens_i32 + total_recv_tokens = buffer.total_recv_tokens recv_tokens, gemm_out, act_out = operands.recv_buffers(rows, hidden, ffn, device) recv_weights = torch.empty(rows, dtype=torch.float32, device=device) - # The dispatch writes the expert layout the GEMMs read. - expert_token_offsets = tex.ep_dispatch_gemm_fwd( + tex.ep_dispatch_gemm_fwd( buffer.handle_mem, topk_idx, tokens, topk_weights, operands.forward_weight(w1), - recv_tokens, recv_weights, tokens_per_expert, gemm_out, act_out, buffer.top_k, - buffer.alignment, total_recv_tokens, symm_input=symm_input, + recv_tokens, recv_weights, tokens_per_expert, expert_token_offsets, gemm_out, act_out, + buffer.top_k, buffer.alignment, total_recv_tokens, symm_input=symm_input, ) # fmt: skip - # Publish the public counters as the unfused prepare does: the kept tokens per expert and - # the recv total before any drop. - buffer.tokens_per_expert.copy_(tokens_per_expert) - buffer.total_recv_tokens.copy_(buffer.total_recv_tokens_i32) expert_out = torch.empty(rows, hidden, dtype=torch.bfloat16, device=device) result = torch.empty(buffer.num_local_tokens, hidden, dtype=torch.bfloat16, device=device) tex.ep_combine_gemm_fwd( @@ -224,7 +226,9 @@ def fuser_forward( row_tensors, other_tensors = operands.saved_tensors( recv_tokens, recv_weights, gemm_out, act_out, w1, w2, backward ) - self._save_for_backward(basic_op_ctxs, buffer, row_tensors, other_tensors, topk_weights) + self._save_for_backward( + basic_op_ctxs, buffer, row_tensors, other_tensors, topk_weights, expert_token_offsets + ) return result, [(tokens_per_expert, recv_weights), (), (), (), ()] def _check_runtime_support(self, backward: bool) -> None: @@ -263,7 +267,9 @@ def _check_runtime_support(self, backward: bool) -> None: if reason is not None: raise RuntimeError(f"FusedMoE is not supported: {reason}.") - def _save_for_backward(self, basic_op_ctxs, buffer, row_tensors, other_tensors, topk_weights): + def _save_for_backward( + self, basic_op_ctxs, buffer, row_tensors, other_tensors, topk_weights, expert_token_offsets + ): """Save the tensors the backward reads, when any output needs a gradient. The operands of the weight gradient of a frozen weight are not saved.""" _, fc1_op, _, fc2_op, _ = self.basic_ops @@ -284,7 +290,7 @@ def _save_for_backward(self, basic_op_ctxs, buffer, row_tensors, other_tensors, # Paged stashing keeps only the received rows of each row-sized tensor. saved_rows = [t for t in row_tensors if t is not None] mark_grouped_tensor(*saved_rows) - num_tokens = buffer.tokens_per_expert_i32.sum(0, keepdim=True, dtype=torch.int32) + num_tokens = expert_token_offsets[-1:] for tensor in saved_rows: tensor.grouped_tensor_num_tokens = num_tokens # CPU offload takes the activations, as the unfused ops do, not the routing weights. @@ -300,6 +306,8 @@ def _save_for_backward(self, basic_op_ctxs, buffer, row_tensors, other_tensors, fc1_ctx.save_for_backward(*row_tensors, *other_tensors) fc1_ctx.buffer = buffer fc1_ctx.topk_weights_shape = topk_weights.shape + # The backward GEMMs read the forward's expert layout. + fc1_ctx.expert_token_offsets = expert_token_offsets def _weight_operands(self, idx, columnwise): """GEMM operands of the weight of the GroupedLinear at ``idx``, as ``_MxFp8WeightOperands`` @@ -331,13 +339,13 @@ def fuser_backward( hidden = buffer.hidden_dim ffn = fc2_op.in_features rows = gemm_out.shape[0] - tokens_per_expert = buffer.tokens_per_expert_i32 + expert_token_offsets = fc1_ctx.expert_token_offsets w1 = _bf16_weight(fc1_op, num_groups) w2 = _bf16_weight(fc2_op, num_groups) grad_result = _bf16_grad_output(grad_output) num_tokens = grad_result.shape[0] grad_params = functools.partial( - self._grad_params, device=device, tokens_per_expert=tokens_per_expert + self._grad_params, device=device, expert_token_offsets=expert_token_offsets ) grad_expert_out = torch.empty(rows, hidden, dtype=torch.bfloat16, device=device) @@ -348,7 +356,7 @@ def fuser_backward( if fc2_ctx.weight_requires_grad: fc2_grads = grad_params(fc2_op, fc2_ctx, act_out, None, "FC2", fc2_wgrad) tex.ep_combine_gemm_bwd( - buffer.handle_mem, grad_result, gemm_out, recv_weights, tokens_per_expert, w2, + buffer.handle_mem, grad_result, gemm_out, recv_weights, expert_token_offsets, w2, grad_expert_out, grad_gemm, grad_recv_weights, buffer.top_k, buffer.alignment, buffer.topk_idx_dtype, **fc2_wgrad, ) # fmt: skip @@ -367,7 +375,7 @@ def fuser_backward( grad_tokens = torch.empty(num_tokens, hidden, dtype=torch.bfloat16, device=device) grad_topk = torch.empty(fc1_ctx.topk_weights_shape, dtype=torch.float32, device=device) tex.ep_dispatch_gemm_bwd( - buffer.handle_mem, grad_gemm, grad_recv_weights, tokens_per_expert, w1, + buffer.handle_mem, grad_gemm, grad_recv_weights, expert_token_offsets, w1, grad_recv, grad_tokens, grad_topk, buffer.top_k, buffer.alignment, buffer.topk_idx_dtype, **fc1_wgrad, ) # fmt: skip @@ -380,7 +388,7 @@ def fuser_backward( def _grad_params( self, fc_op, ctx, grouped_x, grouped_dy, label, wgrad_args=None, *, device, - tokens_per_expert, + expert_token_offsets, ): # fmt: skip """Parameter gradients of ``fc_op``, in registration order. With ``wgrad_args`` the weight gradient is computed by the backward call, and ``grouped_x`` is its input, recorded there; @@ -396,7 +404,7 @@ def _grad_params( if wgrad_args is not None: factory = wgrad_args.gemm_fn_factory(num_groups, shape) else: - offsets = tokens_per_expert.cumsum(0, dtype=torch.int32) + offsets = expert_token_offsets[1:] if not mxfp8: factory = _bf16_wgrad_fn_factory( weight_shape=shape, offsets=offsets, wgrad_kernel_fn=wgrad_kernel_fn, @@ -444,9 +452,8 @@ def _backward_mxfp8(self, basic_op_ctxs, grad_output, grad_recv_weights_extra=No hidden = buffer.hidden_dim ffn = fc2_op.in_features rows = gemm_out.shape[0] - tokens_per_expert = buffer.tokens_per_expert_i32 - # Grouped tensor group sizes are int64. - first_dims = tokens_per_expert.long() + first_dims = buffer.tokens_per_expert + expert_token_offsets = fc1_ctx.expert_token_offsets grad_result = _bf16_grad_output(grad_output) num_tokens = grad_result.shape[0] grad_result, symm_input = operands.dispatch_input(grad_result, device) @@ -470,7 +477,7 @@ def empty(quantizer, cols): grad_recv_weights = torch.empty(rows, dtype=torch.float32, device=device) grad_params = functools.partial( - self._grad_params, device=device, tokens_per_expert=tokens_per_expert + self._grad_params, device=device, expert_token_offsets=expert_token_offsets ) def grouped(cols, data, scale, col_data, col_scale): @@ -479,8 +486,7 @@ def grouped(cols, data, scale, col_data, col_scale): shape=(rows, cols), dtype=torch.bfloat16, num_tensors=num_groups, quantizer=operands.transport, data=data, columnwise_data=col_data.view(-1), scale_inv=scale, columnwise_scale_inv=col_scale, first_dims=first_dims, - tensor_offsets=tex.splits_to_offsets(first_dims, cols), - with_gemm_swizzled_scales=True, + tensor_offsets=expert_token_offsets.long() * cols, with_gemm_swizzled_scales=True, ) # fmt: skip def fc1_grad_params(wgrad_args=None): @@ -502,7 +508,8 @@ def fc1_grad_params(wgrad_args=None): grad_gemm._columnwise_data, grad_gemm._columnwise_scale_inv.view(-1), ) # fmt: skip return grad_params( - fc1_op, fc1_ctx, _with_columnwise_data(recv_tokens, first_dims, operands), + fc1_op, fc1_ctx, + _with_columnwise_data(recv_tokens, first_dims, expert_token_offsets, operands), grad_gemm_cols, "FC1", ) # fmt: skip @@ -512,7 +519,7 @@ def fc1_grad_params(wgrad_args=None): else: fc2_grads = grad_params(fc2_op, fc2_ctx, None, None, "FC2") tex.ep_combine_gemm_bwd( - buffer.handle_mem, grad_result, gemm_out, recv_weights, tokens_per_expert, w2, + buffer.handle_mem, grad_result, gemm_out, recv_weights, expert_token_offsets, w2, grad_expert_out, grad_gemm, grad_recv_weights, buffer.top_k, buffer.alignment, buffer.topk_idx_dtype, act_out=act_col, symm_input=symm_input, **fc2_wgrad, ) # fmt: skip @@ -530,7 +537,7 @@ def fc1_grad_params(wgrad_args=None): # The columnwise grad_gemm_out is read only by the in-call weight gradient. tex.ep_dispatch_gemm_bwd( buffer.handle_mem, grad_gemm if fc1_wgrad else _rowwise_only(grad_gemm), - grad_recv_weights, tokens_per_expert, w1, grad_recv, grad_tokens, grad_topk, + grad_recv_weights, expert_token_offsets, w1, grad_recv, grad_tokens, grad_topk, buffer.top_k, buffer.alignment, buffer.topk_idx_dtype, **fc1_wgrad, ) # fmt: skip @@ -704,7 +711,8 @@ def _gemm_interface_reason(mxfp8: bool = False) -> Optional[str]: ) except ImportError as err: return f"the CuTeDSL EP grouped GEMMs cannot be imported: {err}" - return gemm_interface_reason(mxfp8) + # PyTorch passes int64 expert counts and offsets. + return gemm_interface_reason(mxfp8, int64_offsets=True) def _dglu_skips_column_outputs() -> bool: @@ -747,7 +755,7 @@ def _rowwise_only(tensor: MXFP8TensorStorage) -> MXFP8TensorStorage: ) # fmt: skip -def _with_columnwise_data(recv_tokens, first_dims, operands): +def _with_columnwise_data(recv_tokens, first_dims, expert_token_offsets, operands): """Expert slabs of received MXFP8 rows with compact scales, given the columnwise data and GEMM-swizzled scales of the weight gradient.""" rows, hidden = recv_tokens._rowwise_data.shape @@ -755,7 +763,7 @@ def _with_columnwise_data(recv_tokens, first_dims, operands): shape=(rows, hidden), dtype=torch.bfloat16, num_tensors=first_dims.numel(), quantizer=operands.transport, data=recv_tokens._rowwise_data.view(-1), scale_inv=recv_tokens._rowwise_scale_inv.view(-1), first_dims=first_dims, - tensor_offsets=tex.splits_to_offsets(first_dims, hidden), + tensor_offsets=expert_token_offsets.long() * hidden, ) # fmt: skip tex.group_requantize_inplace( grouped, operands.gemm_both, first_dims.numel(), first_dims, DType.kBFloat16, From 1462cf7fc9f5c08f5d45e94ba98d4658c2f7a929 Mon Sep 17 00:00:00 2001 From: Phuong Nguyen Date: Tue, 1 Dec 2026 21:32:46 -0800 Subject: [PATCH 26/67] Bump nccl-extensions to the restacked NCCL EP integ branch Signed-off-by: Phuong Nguyen --- 3rdparty/nccl-extensions | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/3rdparty/nccl-extensions b/3rdparty/nccl-extensions index 26ee9375f11..58aa61d4193 160000 --- a/3rdparty/nccl-extensions +++ b/3rdparty/nccl-extensions @@ -1 +1 @@ -Subproject commit 26ee9375f112606cde0b8e31d3d1927aabb101d9 +Subproject commit 58aa61d4193c333042613d956b9f2da60a57d6ee From 62a0d2a089daf0936c0fadef6c0cf97702339828 Mon Sep 17 00:00:00 2001 From: Phuong Nguyen Date: Wed, 2 Dec 2026 09:44:59 -0800 Subject: [PATCH 27/67] [Common][PyTorch] Add EP SM config with per-direction budgets and last-chunk push and reduce SMs for the signaled combine Signed-off-by: Phuong Nguyen --- docs/api/pytorch.rst | 2 + .../pytorch/ep/bench/bench_moe_overlap.py | 7 +-- tests/pytorch/distributed/run_ep.py | 6 +-- transformer_engine/common/ep/ep_backend.cpp | 47 +++++++++++------- transformer_engine/common/ep/ep_gemm_api.cpp | 25 +++++----- .../common/include/transformer_engine/ep.h | 43 +++++++++++------ transformer_engine/pytorch/csrc/extensions.h | 3 +- .../pytorch/csrc/extensions/ep.cpp | 14 +++--- transformer_engine/pytorch/ep.py | 48 +++++++++++++------ 9 files changed, 121 insertions(+), 74 deletions(-) diff --git a/docs/api/pytorch.rst b/docs/api/pytorch.rst index 4e32113711c..29e8fdda050 100644 --- a/docs/api/pytorch.rst +++ b/docs/api/pytorch.rst @@ -160,6 +160,8 @@ fuses into one op. If its settings are unsupported, an error names the reason. .. autoapiclass:: transformer_engine.pytorch.ep.EpConfig +.. autoapiclass:: transformer_engine.pytorch.ep.EpSmConfig + .. autoapifunction:: transformer_engine.pytorch.ep.ep_bootstrap .. autoapifunction:: transformer_engine.pytorch.ep.ep_finalize diff --git a/examples/pytorch/ep/bench/bench_moe_overlap.py b/examples/pytorch/ep/bench/bench_moe_overlap.py index f2b1f10181b..580799f4f9c 100644 --- a/examples/pytorch/ep/bench/bench_moe_overlap.py +++ b/examples/pytorch/ep/bench/bench_moe_overlap.py @@ -23,7 +23,7 @@ import transformer_engine.pytorch as te from transformer_engine.pytorch import ops as te_ops from transformer_engine.common.recipe import MXFP8BlockScaling -from transformer_engine.pytorch.ep import EpBuffer, EpConfig, ep_bootstrap, ep_finalize +from transformer_engine.pytorch.ep import EpBuffer, EpConfig, EpSmConfig, ep_bootstrap, ep_finalize def _parse_args(): @@ -68,10 +68,7 @@ def _build(args): num_topk=args.top_k, recv_capacity_per_rank=args.recv_capacity_per_rank, max_num_sms=max(sms), - dispatch_fwd_num_sms=sms[0], - combine_fwd_num_sms=sms[1], - dispatch_bwd_num_sms=sms[2], - combine_bwd_num_sms=sms[3], + sm_config=EpSmConfig(*sms), ) config = EpConfig( diff --git a/tests/pytorch/distributed/run_ep.py b/tests/pytorch/distributed/run_ep.py index 101ff06398f..d9005de1a64 100644 --- a/tests/pytorch/distributed/run_ep.py +++ b/tests/pytorch/distributed/run_ep.py @@ -24,6 +24,7 @@ from transformer_engine.pytorch.ep import ( EpBuffer, EpConfig, + EpSmConfig, ep_bootstrap, ep_finalize, get_ep_drop_on_overflow, @@ -311,10 +312,7 @@ def setUpClass(cls): zero_copy=ZERO_COPY, drop_on_overflow=OVERFLOW, max_num_sms=OVERLAP_COMM_SMS if OVERLAP else 0, - dispatch_fwd_num_sms=COMM_SMS[0], - combine_fwd_num_sms=COMM_SMS[1], - dispatch_bwd_num_sms=COMM_SMS[2], - combine_bwd_num_sms=COMM_SMS[3], + sm_config=EpSmConfig(*COMM_SMS), ) except RuntimeError as err: # A backward count other than the forward one needs NCCL EP backward budgets. diff --git a/transformer_engine/common/ep/ep_backend.cpp b/transformer_engine/common/ep/ep_backend.cpp index 5e1e7e9f780..f6b86b8cd5c 100644 --- a/transformer_engine/common/ep/ep_backend.cpp +++ b/transformer_engine/common/ep/ep_backend.cpp @@ -20,6 +20,7 @@ #include #include #include +#include #include #include #include @@ -235,11 +236,15 @@ void EPBackend::validate_config(const NVTEEpGroupConfig& config) { ") must be divisible by ep_size (", config.ep_size, ")"); NVTE_CHECK(config.num_comm_sms >= 0, "num_comm_sms must be >= 0 (0 = auto), got ", config.num_comm_sms); - NVTE_CHECK(config.dispatch_fwd_num_sms >= 0 && config.combine_fwd_num_sms >= 0 && - config.dispatch_bwd_num_sms >= 0 && config.combine_bwd_num_sms >= 0, + const NVTEEpSmConfig& sm_cfg = config.sm_config; + NVTE_CHECK(sm_cfg.dispatch_fwd_num_sms >= 0 && sm_cfg.combine_fwd_num_sms >= 0 && + sm_cfg.dispatch_bwd_num_sms >= 0 && sm_cfg.combine_bwd_num_sms >= 0, "dispatch/combine fwd/bwd num_sms must be >= 0 (0 = inherit), got ", - config.dispatch_fwd_num_sms, ", ", config.combine_fwd_num_sms, ", ", - config.dispatch_bwd_num_sms, ", ", config.combine_bwd_num_sms); + sm_cfg.dispatch_fwd_num_sms, ", ", sm_cfg.combine_fwd_num_sms, ", ", + sm_cfg.dispatch_bwd_num_sms, ", ", sm_cfg.combine_bwd_num_sms); + NVTE_CHECK(sm_cfg.combine_push_last_chunk_sms >= 0 && sm_cfg.combine_reduce_last_chunk_sms >= 0, + "combine last-chunk SM counts must be >= 0 (0 = environment), got ", + sm_cfg.combine_push_last_chunk_sms, ", ", sm_cfg.combine_reduce_last_chunk_sms); const int sm = cuda::sm_arch(); NVTE_CHECK(sm >= 90, "NCCL EP requires SM_90+ (Hopper or later), but current device is SM_", sm); @@ -396,19 +401,19 @@ void EPBackend::init(ncclComm_t ep_comm, NVTEEpGroupConfig group_config) { const auto inherit = [](int num_sms, int fallback) { return num_sms > 0 ? num_sms : fallback; }; const int comm_sms = group_config.num_comm_sms > 0 ? group_config.num_comm_sms : std::min(kDefaultCommSms, device_sms); - const int dispatch_fwd = inherit(group_config.dispatch_fwd_num_sms, comm_sms); - const int combine_fwd = inherit(group_config.combine_fwd_num_sms, comm_sms); - const int dispatch_bwd = inherit(group_config.dispatch_bwd_num_sms, dispatch_fwd); - const int combine_bwd = inherit(group_config.combine_bwd_num_sms, combine_fwd); + const int dispatch_fwd = inherit(group_config.sm_config.dispatch_fwd_num_sms, comm_sms); + const int combine_fwd = inherit(group_config.sm_config.combine_fwd_num_sms, comm_sms); + const int dispatch_bwd = inherit(group_config.sm_config.dispatch_bwd_num_sms, dispatch_fwd); + const int combine_bwd = inherit(group_config.sm_config.combine_bwd_num_sms, combine_fwd); NVTE_CHECK(comm_sms <= device_sms && dispatch_fwd <= device_sms && combine_fwd <= device_sms && dispatch_bwd <= device_sms && combine_bwd <= device_sms, "num_comm_sms and dispatch/combine fwd/bwd num_sms must be <= the device SM count (", device_sms, "), got num_comm_sms ", comm_sms, ", dispatch fwd/bwd ", dispatch_fwd, "/", dispatch_bwd, ", combine fwd/bwd ", combine_fwd, "/", combine_bwd); - group_config_.dispatch_fwd_num_sms = dispatch_fwd; - group_config_.combine_fwd_num_sms = combine_fwd; - group_config_.dispatch_bwd_num_sms = dispatch_bwd; - group_config_.combine_bwd_num_sms = combine_bwd; + group_config_.sm_config.dispatch_fwd_num_sms = dispatch_fwd; + group_config_.sm_config.combine_fwd_num_sms = combine_fwd; + group_config_.sm_config.dispatch_bwd_num_sms = dispatch_bwd; + group_config_.sm_config.combine_bwd_num_sms = combine_bwd; cfg.dispatch_num_sms = static_cast(dispatch_fwd); cfg.combine_num_sms = static_cast(combine_fwd); // NCCL EP's backward counts default to its forward ones; set them only where they differ. @@ -444,12 +449,22 @@ void EPBackend::init(ncclComm_t ep_comm, NVTEEpGroupConfig group_config) { std::snprintf(sm_buf, sizeof(sm_buf), "%d", device_sms); setenv("NCCL_EP_SHUFFLE_SMS", sm_buf, /*overwrite=*/0); setenv("NCCL_EP_PREPROCESS_NUM_SMS", sm_buf, /*overwrite=*/0); - // Split the signaled combine so its last chunk pushes on its own SMs; 64 of them saturate - // NVLink. NCCL EP splits only with this set, on every rank of the group. - constexpr char kCombinePushLastChunkSms[] = "64"; - setenv("NCCL_EP_HT_COMBINE_PUSH_LAST_CHUNK_SMS", kCombinePushLastChunkSms, /*overwrite=*/0); }); + // NCCL EP reads the last-chunk SM counts of the signaled combine from the environment at group + // creation, and splits the combine only when the push count is set. + const auto set_last_chunk_sms = [device_sms](const char* name, int sms) { + if (sms > 0) { + NVTE_CHECK(sms <= device_sms, name, " must be <= the device SM count (", device_sms, + "), got ", sms); + setenv(name, std::to_string(sms).c_str(), /*overwrite=*/1); + } + }; + set_last_chunk_sms("NCCL_EP_HT_COMBINE_PUSH_LAST_CHUNK_SMS", + group_config.sm_config.combine_push_last_chunk_sms); + set_last_chunk_sms("NCCL_EP_HT_COMBINE_REDUCE_LAST_CHUNK_SMS", + group_config.sm_config.combine_reduce_last_chunk_sms); + NVTE_CHECK_NCCL(nccl_ep::create_group(&ep_group_, ep_comm, &cfg)); ep_comm_ = ep_comm; diff --git a/transformer_engine/common/ep/ep_gemm_api.cpp b/transformer_engine/common/ep/ep_gemm_api.cpp index 35a19175e71..f78b96be034 100644 --- a/transformer_engine/common/ep/ep_gemm_api.cpp +++ b/transformer_engine/common/ep/ep_gemm_api.cpp @@ -82,7 +82,7 @@ struct EpGemmContext { // comm_sms: the group's SM count of the NCCL EP call that the entry point overlaps; the GEMM runs // on the other SMs. -EpGemmContext make_context(const NVTEEpLayerConfig* layer_cfg, int NVTEEpGroupConfig::*comm_sms) { +EpGemmContext make_context(const NVTEEpLayerConfig* layer_cfg, int NVTEEpSmConfig::*comm_sms) { const NVTEEpLayerConfig cfg = ep::normalize_layer_config(layer_cfg); const size_t alignment = cfg.dispatch_output_per_expert_alignment; NVTE_CHECK(alignment == 64 || alignment == 128 || alignment == kRowsPerTile, @@ -101,8 +101,9 @@ EpGemmContext make_context(const NVTEEpLayerConfig* layer_cfg, int NVTEEpGroupCo name); } const int sm_count = transformer_engine::cuda::sm_count(); - NVTE_CHECK(sm_count - group.*comm_sms >= static_cast(kClusterSize), "fewer than ", - kClusterSize, " SMs left beside the ", group.*comm_sms, " communication SMs"); + const int comm_sms_count = group.sm_config.*comm_sms; + NVTE_CHECK(sm_count - comm_sms_count >= static_cast(kClusterSize), "fewer than ", + kClusterSize, " SMs left beside the ", comm_sms_count, " communication SMs"); // The GEMM tails take the clusters of every SM. const int max_clusters = transformer_engine::cuda::max_active_clusters(static_cast(kClusterSize)); @@ -112,7 +113,7 @@ EpGemmContext make_context(const NVTEEpLayerConfig* layer_cfg, int NVTEEpGroupCo EpGemmContext ctx{backend, group, cfg, - (sm_count - group.*comm_sms) / static_cast(kClusterSize), + (sm_count - comm_sms_count) / static_cast(kClusterSize), sm_count / static_cast(kClusterSize), group.max_recv_tokens_per_rank == 0}; return ctx; @@ -522,19 +523,19 @@ size_t nvte_ep_overlap_prepare(size_t hidden_dim, size_t ffn_dim, size_t num_loc // Forward dispatch: FC1 + SwiGLU, no weight gradient. { - const EpGemmContext ctx = make_context(layer_cfg, &NVTEEpGroupConfig::dispatch_fwd_num_sms); + const EpGemmContext ctx = make_context(layer_cfg, &NVTEEpSmConfig::dispatch_fwd_num_sms); consider(ep::EpDispatchGemmConfig{rows, hidden_dim, 2 * ffn_dim, ne, ctx.num_clusters, false, mx, ctx.alignment(), dispatch_writes_layout(ctx, ne)}, false, 0); } // Forward combine: FC2. Size the unit-probs row buffer, which the MXFP8 path omits. { - const EpGemmContext ctx = make_context(layer_cfg, &NVTEEpGroupConfig::combine_fwd_num_sms); + const EpGemmContext ctx = make_context(layer_cfg, &NVTEEpSmConfig::combine_fwd_num_sms); consider(combine_fwd_config(ctx, rows, ffn_dim, hidden_dim, ne, mx), true, 0); } // Backward combine: FC2 dgrad + SwiGLU backward, with the FC2 weight gradient [hidden, ffn]. { - const EpGemmContext ctx = make_context(layer_cfg, &NVTEEpGroupConfig::dispatch_bwd_num_sms); + const EpGemmContext ctx = make_context(layer_cfg, &NVTEEpSmConfig::dispatch_bwd_num_sms); const size_t wgrad = wg ? wgrad_workspace_bytes(ctx, rows, hidden_dim, ffn_dim, ne, mx) : 0; consider(ep::EpDispatchGemmConfig{rows, hidden_dim, ffn_dim, ne, ctx.num_clusters, true, mx, ctx.alignment()}, @@ -542,7 +543,7 @@ size_t nvte_ep_overlap_prepare(size_t hidden_dim, size_t ffn_dim, size_t num_loc } // Backward dispatch: FC1 dgrad, with the FC1 weight gradient [2 * ffn, hidden]. { - const EpGemmContext ctx = make_context(layer_cfg, &NVTEEpGroupConfig::combine_bwd_num_sms); + const EpGemmContext ctx = make_context(layer_cfg, &NVTEEpSmConfig::combine_bwd_num_sms); const bool plain = wg && ctx.num_clusters > 0; const size_t n_chunk = plain ? 0 : combine_chunk(hidden_dim); const size_t wgrad = wg ? wgrad_workspace_bytes(ctx, rows, 2 * ffn_dim, hidden_dim, ne, mx) : 0; @@ -567,7 +568,7 @@ void nvte_ep_dispatch_gemm_fwd(NVTETensor handle_mem, const NVTETensor topk_idx, using namespace transformer_engine; NVTE_CHECK(activation == NVTE_Activation_Type::SWIGLU, "nvte_ep_dispatch_gemm_fwd supports only the SwiGLU activation"); - const EpGemmContext ctx = make_context(layer_cfg, &NVTEEpGroupConfig::dispatch_fwd_num_sms); + const EpGemmContext ctx = make_context(layer_cfg, &NVTEEpSmConfig::dispatch_fwd_num_sms); checkCuDriverContext(stream); const auto [ws_base, ws_bytes] = workspace_span(workspace); @@ -702,7 +703,7 @@ void nvte_ep_combine_gemm_fwd(NVTETensor handle_mem, const NVTETensor gemm_in, const NVTEEpLayerConfig* layer_cfg, cudaStream_t stream) { NVTE_API_CALL(nvte_ep_combine_gemm_fwd); using namespace transformer_engine; - const EpGemmContext ctx = make_context(layer_cfg, &NVTEEpGroupConfig::combine_fwd_num_sms); + const EpGemmContext ctx = make_context(layer_cfg, &NVTEEpSmConfig::combine_fwd_num_sms); checkCuDriverContext(stream); const auto [ws_base, ws_bytes] = workspace_span(workspace); @@ -780,7 +781,7 @@ void nvte_ep_combine_gemm_bwd( using namespace transformer_engine; NVTE_CHECK(activation == NVTE_Activation_Type::SWIGLU, "nvte_ep_combine_gemm_bwd supports only the SwiGLU activation"); - const EpGemmContext ctx = make_context(layer_cfg, &NVTEEpGroupConfig::dispatch_bwd_num_sms); + const EpGemmContext ctx = make_context(layer_cfg, &NVTEEpSmConfig::dispatch_bwd_num_sms); checkCuDriverContext(stream); const auto [ws_base, ws_bytes] = workspace_span(workspace); @@ -938,7 +939,7 @@ void nvte_ep_dispatch_gemm_bwd(NVTETensor handle_mem, const NVTETensor grad_gemm cudaStream_t stream) { NVTE_API_CALL(nvte_ep_dispatch_gemm_bwd); using namespace transformer_engine; - const EpGemmContext ctx = make_context(layer_cfg, &NVTEEpGroupConfig::combine_bwd_num_sms); + const EpGemmContext ctx = make_context(layer_cfg, &NVTEEpSmConfig::combine_bwd_num_sms); checkCuDriverContext(stream); const auto [ws_base, ws_bytes] = workspace_span(workspace); diff --git a/transformer_engine/common/include/transformer_engine/ep.h b/transformer_engine/common/include/transformer_engine/ep.h index c03bedd3420..77936b20959 100644 --- a/transformer_engine/common/include/transformer_engine/ep.h +++ b/transformer_engine/common/include/transformer_engine/ep.h @@ -37,6 +37,32 @@ extern "C" { * zero-defaults the rest; struct_size 0 means the base layout. Append new * fields at the end only; never reorder, resize, or remove existing ones. */ +/*! \brief SM budgets of the NCCL EP kernels per pass direction, for every EP op of the group. + * 0 (default) inherits: a forward count from num_comm_sms, a backward count from the forward + * count of the same kind. Each ep_gemm.h call runs its GEMM on the SMs its NCCL EP call leaves. + * Embedded as the trailing member of NVTEEpGroupConfig; append new budgets at the end only. */ +typedef struct { + /*! Forward dispatch: nvte_ep_dispatch(_v2), nvte_ep_prepare_and_dispatch, + * nvte_ep_dispatch_gemm_fwd. */ + int dispatch_fwd_num_sms; + /*! Forward combine: nvte_ep_combine(_v2), nvte_ep_combine_gemm_fwd. */ + int combine_fwd_num_sms; + /*! Backward dispatch, which carries the combine's gradient: nvte_ep_combine_bwd(_v2), + * nvte_ep_combine_gemm_bwd. */ + int dispatch_bwd_num_sms; + /*! Backward combine, which carries the dispatch's gradient: nvte_ep_dispatch_bwd(_v2), + * nvte_ep_dispatch_gemm_bwd. */ + int combine_bwd_num_sms; + /*! SMs that push the last chunk of a signaled forward combine (nvte_ep_combine_gemm_fwd), + * beside the reduce of the other chunks; the combine splits only when this is set. 0 leaves + * NCCL_EP_HT_COMBINE_PUSH_LAST_CHUNK_SMS to the environment. Same on every rank. */ + int combine_push_last_chunk_sms; + /*! SMs that reduce the last chunk of a signaled forward combine; 0 leaves + * NCCL_EP_HT_COMBINE_REDUCE_LAST_CHUNK_SMS to the environment, unset the SMs of the other + * chunks' reduce. */ + int combine_reduce_last_chunk_sms; +} NVTEEpSmConfig; + /*! \brief Group-level EP configuration (fixed for the EP group lifetime). */ typedef struct { /*! Struct size in bytes, or 0 for the base layout. Set to @@ -70,21 +96,8 @@ typedef struct { /*! Recv overflow policy. Nonzero drops tokens past max_recv_tokens_per_rank * and continues; 0 (default) traps. Not supported in eager mode. */ int drop_on_overflow; - /* SMs of the NCCL EP dispatch and combine kernels per pass direction, for every EP op of the - * group. 0 (default) inherits: a forward count from num_comm_sms, a backward count from the - * forward count of the same kind. Each ep_gemm.h call runs its GEMM on the SMs its NCCL EP call - * leaves. */ - /*! Forward dispatch: nvte_ep_dispatch(_v2), nvte_ep_prepare_and_dispatch, - * nvte_ep_dispatch_gemm_fwd. */ - int dispatch_fwd_num_sms; - /*! Forward combine: nvte_ep_combine(_v2), nvte_ep_combine_gemm_fwd. */ - int combine_fwd_num_sms; - /*! Backward dispatch, which carries the combine's gradient: nvte_ep_combine_bwd(_v2), - * nvte_ep_combine_gemm_bwd. */ - int dispatch_bwd_num_sms; - /*! Backward combine, which carries the dispatch's gradient: nvte_ep_dispatch_bwd(_v2), - * nvte_ep_dispatch_gemm_bwd. */ - int combine_bwd_num_sms; + /*! Per-kernel SM budgets. All-zero (default) inherits num_comm_sms. */ + NVTEEpSmConfig sm_config; } NVTEEpGroupConfig; /*! \brief Per-layer configuration consumed by nvte_ep_handle_mem_size, diff --git a/transformer_engine/pytorch/csrc/extensions.h b/transformer_engine/pytorch/csrc/extensions.h index f765e2c3da8..c8f03df1e04 100644 --- a/transformer_engine/pytorch/csrc/extensions.h +++ b/transformer_engine/pytorch/csrc/extensions.h @@ -768,7 +768,8 @@ void ep_initialize(uintptr_t comm_ptr, const std::string &group_name, int64_t nu int64_t hidden_dim, int64_t max_num_sms, pybind11::object max_token_dtype, bool zero_copy, int64_t num_topk, bool drop_on_overflow, int64_t dispatch_fwd_num_sms, int64_t combine_fwd_num_sms, - int64_t dispatch_bwd_num_sms, int64_t combine_bwd_num_sms); + int64_t dispatch_bwd_num_sms, int64_t combine_bwd_num_sms, + int64_t combine_push_last_chunk_sms, int64_t combine_reduce_last_chunk_sms); void ep_finalize(); diff --git a/transformer_engine/pytorch/csrc/extensions/ep.cpp b/transformer_engine/pytorch/csrc/extensions/ep.cpp index 8c2fb20b880..e3e7ddb343d 100644 --- a/transformer_engine/pytorch/csrc/extensions/ep.cpp +++ b/transformer_engine/pytorch/csrc/extensions/ep.cpp @@ -362,7 +362,8 @@ void ep_initialize(uintptr_t comm_ptr, const std::string& group_name, int64_t nu int64_t hidden_dim, int64_t max_num_sms, pybind11::object max_token_dtype, bool zero_copy, int64_t num_topk, bool drop_on_overflow, int64_t dispatch_fwd_num_sms, int64_t combine_fwd_num_sms, - int64_t dispatch_bwd_num_sms, int64_t combine_bwd_num_sms) { + int64_t dispatch_bwd_num_sms, int64_t combine_bwd_num_sms, + int64_t combine_push_last_chunk_sms, int64_t combine_reduce_last_chunk_sms) { NVTE_CHECK(!group_name.empty(), "group_name must be non-empty (used for symm-mem lookup)"); NVTE_CHECK(comm_ptr != 0, "comm_ptr must be non-null (torch NCCL host comm pointer)"); NVTE_CHECK(!g_ep_initialized, "ep_initialize called twice without ep_finalize"); @@ -383,10 +384,10 @@ void ep_initialize(uintptr_t comm_ptr, const std::string& group_name, int64_t nu .zero_copy = zero_copy ? 1 : 0, .num_topk = static_cast(num_topk), .drop_on_overflow = drop_on_overflow ? 1 : 0, - .dispatch_fwd_num_sms = static_cast(dispatch_fwd_num_sms), - .combine_fwd_num_sms = static_cast(combine_fwd_num_sms), - .dispatch_bwd_num_sms = static_cast(dispatch_bwd_num_sms), - .combine_bwd_num_sms = static_cast(combine_bwd_num_sms), + .sm_config = {static_cast(dispatch_fwd_num_sms), static_cast(combine_fwd_num_sms), + static_cast(dispatch_bwd_num_sms), static_cast(combine_bwd_num_sms), + static_cast(combine_push_last_chunk_sms), + static_cast(combine_reduce_last_chunk_sms)}, }; // Release the GIL only around the native init. It must stay held while pybind11 casts // the ``max_token_dtype`` object above and destroys the by-value ``pybind11::object`` @@ -1190,7 +1191,8 @@ void register_ep_bindings(pybind11::module_& m) { py::arg("max_num_sms") = 0, py::arg("max_token_dtype"), py::arg("zero_copy") = false, py::arg("num_topk") = 0, py::arg("drop_on_overflow") = false, py::arg("dispatch_fwd_num_sms") = 0, py::arg("combine_fwd_num_sms") = 0, - py::arg("dispatch_bwd_num_sms") = 0, py::arg("combine_bwd_num_sms") = 0); + py::arg("dispatch_bwd_num_sms") = 0, py::arg("combine_bwd_num_sms") = 0, + py::arg("combine_push_last_chunk_sms") = 0, py::arg("combine_reduce_last_chunk_sms") = 0); m.def("ep_finalize", &ep_finalize, "Tear down the EP backend. Idempotent.", py::call_guard()); m.def("ep_get_zero_copy", &ep_get_zero_copy, "Return the current EP zero-copy toggle state."); diff --git a/transformer_engine/pytorch/ep.py b/transformer_engine/pytorch/ep.py index 1b770dff99d..4e2a094e9b7 100644 --- a/transformer_engine/pytorch/ep.py +++ b/transformer_engine/pytorch/ep.py @@ -35,6 +35,7 @@ __all__ = [ "EpConfig", "EpBuffer", + "EpSmConfig", "ep_bootstrap", "get_ep_drop_on_overflow", "get_ep_group", @@ -149,6 +150,25 @@ def _atexit_finalize() -> None: _BOOTSTRAP_SETTINGS = None +@dataclass +class EpSmConfig: + """SM budgets of the NCCL EP kernels of an EP group. + + 0 inherits: a forward budget takes ``max_num_sms`` of ``ep_bootstrap``, a backward budget the + forward one. The last-chunk push takes 64 SMs by default, which saturate NVLink; 0 leaves it + to ``NCCL_EP_HT_COMBINE_PUSH_LAST_CHUNK_SMS`` (unset: the signaled combine does not split), + and a 0 reduce to ``NCCL_EP_HT_COMBINE_REDUCE_LAST_CHUNK_SMS`` (unset: the SMs of the other + chunks' reduce). Use the same values on every rank. + """ + + dispatch_fwd_num_sms: int = 0 + combine_fwd_num_sms: int = 0 + dispatch_bwd_num_sms: int = 0 + combine_bwd_num_sms: int = 0 + combine_push_last_chunk_sms: int = 64 + combine_reduce_last_chunk_sms: int = 0 + + def ep_bootstrap( ep_group: dist.ProcessGroup, num_experts: int, @@ -160,10 +180,7 @@ def ep_bootstrap( zero_copy: bool = False, drop_on_overflow: bool = False, max_token_dtype: torch.dtype = torch.bfloat16, - dispatch_fwd_num_sms: int = 0, - combine_fwd_num_sms: int = 0, - dispatch_bwd_num_sms: int = 0, - combine_bwd_num_sms: int = 0, + sm_config: Optional[EpSmConfig] = None, ) -> None: """Initialize EP by borrowing ep_group's NCCL comm. Call once per process. @@ -189,18 +206,17 @@ def ep_bootstrap( ``max_num_sms`` defaults to 24 when the ``te.ops`` MoE overlap is available (``NVTE_ENABLE_CUTEDSL_BACKEND=1``, ``NVTE_MOE_OVERLAP=1``) and ``zero_copy`` is off. - ``dispatch_fwd_num_sms``, ``combine_fwd_num_sms``, ``dispatch_bwd_num_sms`` and - ``combine_bwd_num_sms`` set the SMs of the NCCL EP kernels of the dispatch and combine of the - layer forward and backward, overlapped or not. The backward of MoeCombine is a dispatch and the - backward of MoeDispatch a combine. 0 inherits: a forward budget takes ``max_num_sms``, a - backward budget the forward one. ``FusedMoE`` runs the GEMMs on the remaining SMs. A backward - budget other than the forward one needs NCCL EP with backward SM budgets. ``NCCL_EP_COMM_SMS`` - and NCCL EP's per-call SM variables override these counts, and ``FusedMoE`` rejects them. + ``sm_config`` (an ``EpSmConfig``) sets the SMs of the NCCL EP kernels of the dispatch and + combine of the layer forward and backward, overlapped or not, and of the last chunk of the + signaled combine. ``FusedMoE`` runs the GEMMs on the remaining SMs. A backward budget other + than the forward one needs NCCL EP with backward SM budgets. ``NCCL_EP_COMM_SMS`` and NCCL + EP's per-call SM variables override these counts, and ``FusedMoE`` rejects them. """ global _BOOTSTRAPPED, _ATEXIT_REGISTERED, _EP_GROUP, _EAGER, _BOOTSTRAP_SETTINGS eager = recv_capacity_per_rank is None if max_num_sms == 0 and _moe_overlap_available() and not zero_copy: max_num_sms = _OVERLAP_COMM_SMS + sm_config = sm_config or EpSmConfig() if _BOOTSTRAPPED: raise RuntimeError("ep_bootstrap was already called in this process") if ep_group.size() < 2: @@ -242,10 +258,12 @@ def ep_bootstrap( bool(zero_copy), int(num_topk), bool(drop_on_overflow), - int(dispatch_fwd_num_sms), - int(combine_fwd_num_sms), - int(dispatch_bwd_num_sms), - int(combine_bwd_num_sms), + int(sm_config.dispatch_fwd_num_sms), + int(sm_config.combine_fwd_num_sms), + int(sm_config.dispatch_bwd_num_sms), + int(sm_config.combine_bwd_num_sms), + int(sm_config.combine_push_last_chunk_sms), + int(sm_config.combine_reduce_last_chunk_sms), ) _BOOTSTRAPPED = True _EP_GROUP = ep_group From 8fa21e050175a42440412ccafff917a400832e34 Mon Sep 17 00:00:00 2001 From: Phuong Nguyen Date: Wed, 2 Dec 2026 10:14:24 -0800 Subject: [PATCH 28/67] [Common] Chunk the signaled combine of rows not divisible by 1024 and scope the last-chunk SMs to the overlap path Signed-off-by: Phuong Nguyen --- transformer_engine/common/ep/ep_gemm_api.cpp | 3 ++- .../common/include/transformer_engine/ep.h | 6 +++--- transformer_engine/pytorch/ep.py | 12 ++++++++---- 3 files changed, 13 insertions(+), 8 deletions(-) diff --git a/transformer_engine/common/ep/ep_gemm_api.cpp b/transformer_engine/common/ep/ep_gemm_api.cpp index f78b96be034..5f925c43a1a 100644 --- a/transformer_engine/common/ep/ep_gemm_api.cpp +++ b/transformer_engine/common/ep/ep_gemm_api.cpp @@ -58,7 +58,8 @@ size_t whole_row_chunk(size_t n) { return transformer_engine::DIVUP_TO_MULTIPLE(n, std::min(n, 1024)); } -// Columns per combine flag: 1024 when it divides n, else one flag over the whole row. +// Columns per combine flag: one NCCL EP push tile, or the row when shorter. The last chunk of a +// row that 1024 does not divide is the shorter remainder. size_t combine_chunk(size_t n) { NVTE_CHECK(n % kTileN == 0, "output columns (", n, ") must be a multiple of ", kTileN); return n % 1024 == 0 ? 1024 : whole_row_chunk(n); diff --git a/transformer_engine/common/include/transformer_engine/ep.h b/transformer_engine/common/include/transformer_engine/ep.h index 77936b20959..6a11e7e3d68 100644 --- a/transformer_engine/common/include/transformer_engine/ep.h +++ b/transformer_engine/common/include/transformer_engine/ep.h @@ -53,11 +53,11 @@ typedef struct { /*! Backward combine, which carries the dispatch's gradient: nvte_ep_dispatch_bwd(_v2), * nvte_ep_dispatch_gemm_bwd. */ int combine_bwd_num_sms; - /*! SMs that push the last chunk of a signaled forward combine (nvte_ep_combine_gemm_fwd), - * beside the reduce of the other chunks; the combine splits only when this is set. 0 leaves + /*! Signaled combine only (nvte_ep_combine_gemm_fwd): SMs that push the last chunk, beside the + * reduce of the other chunks; the combine splits only when this is set. 0 leaves * NCCL_EP_HT_COMBINE_PUSH_LAST_CHUNK_SMS to the environment. Same on every rank. */ int combine_push_last_chunk_sms; - /*! SMs that reduce the last chunk of a signaled forward combine; 0 leaves + /*! Signaled combine only: SMs that reduce the last chunk; 0 leaves * NCCL_EP_HT_COMBINE_REDUCE_LAST_CHUNK_SMS to the environment, unset the SMs of the other * chunks' reduce. */ int combine_reduce_last_chunk_sms; diff --git a/transformer_engine/pytorch/ep.py b/transformer_engine/pytorch/ep.py index 4e2a094e9b7..bd304ace0ef 100644 --- a/transformer_engine/pytorch/ep.py +++ b/transformer_engine/pytorch/ep.py @@ -155,10 +155,14 @@ class EpSmConfig: """SM budgets of the NCCL EP kernels of an EP group. 0 inherits: a forward budget takes ``max_num_sms`` of ``ep_bootstrap``, a backward budget the - forward one. The last-chunk push takes 64 SMs by default, which saturate NVLink; 0 leaves it - to ``NCCL_EP_HT_COMBINE_PUSH_LAST_CHUNK_SMS`` (unset: the signaled combine does not split), - and a 0 reduce to ``NCCL_EP_HT_COMBINE_REDUCE_LAST_CHUNK_SMS`` (unset: the SMs of the other - chunks' reduce). Use the same values on every rank. + forward one. + + ``combine_push_last_chunk_sms`` and ``combine_reduce_last_chunk_sms`` apply only to the + signaled combine of the ``te.ops`` MoE overlap; other EP ops ignore them. The push takes 64 SMs + by default, which saturate NVLink; 0 leaves it to ``NCCL_EP_HT_COMBINE_PUSH_LAST_CHUNK_SMS`` + (unset: the combine does not split). A 0 reduce leaves it to + ``NCCL_EP_HT_COMBINE_REDUCE_LAST_CHUNK_SMS`` (unset: the SMs of the other chunks' reduce). Use + the same values on every rank. """ dispatch_fwd_num_sms: int = 0 From b6e4884497e4fb9537c89a9cdce75d27a6a67db4 Mon Sep 17 00:00:00 2001 From: Phuong Nguyen Date: Wed, 2 Dec 2026 10:53:06 -0800 Subject: [PATCH 29/67] [Common][PyTorch] Group EP overlap tuning into EpOverlapConfig with dispatch/combine chunk sizes and last-chunk SMs Signed-off-by: Phuong Nguyen --- docs/api/pytorch.rst | 2 + tests/pytorch/distributed/run_ep.py | 6 +-- transformer_engine/common/ep/ep_backend.cpp | 12 +++-- transformer_engine/common/ep/ep_gemm_api.cpp | 39 ++++++++++----- .../common/include/transformer_engine/ep.h | 22 ++++++--- transformer_engine/pytorch/csrc/extensions.h | 1 + .../pytorch/csrc/extensions/ep.cpp | 10 ++-- transformer_engine/pytorch/ep.py | 47 ++++++++++++++----- 8 files changed, 98 insertions(+), 41 deletions(-) diff --git a/docs/api/pytorch.rst b/docs/api/pytorch.rst index 29e8fdda050..faeb4bcea19 100644 --- a/docs/api/pytorch.rst +++ b/docs/api/pytorch.rst @@ -162,6 +162,8 @@ fuses into one op. If its settings are unsupported, an error names the reason. .. autoapiclass:: transformer_engine.pytorch.ep.EpSmConfig +.. autoapiclass:: transformer_engine.pytorch.ep.EpOverlapConfig + .. autoapifunction:: transformer_engine.pytorch.ep.ep_bootstrap .. autoapifunction:: transformer_engine.pytorch.ep.ep_finalize diff --git a/tests/pytorch/distributed/run_ep.py b/tests/pytorch/distributed/run_ep.py index d9005de1a64..4fc948ba14f 100644 --- a/tests/pytorch/distributed/run_ep.py +++ b/tests/pytorch/distributed/run_ep.py @@ -2056,11 +2056,9 @@ def pack(tensor): ffn = ops[3].in_features recv_bytes = 0 if 1 in frozen else HIDDEN_DIM + HIDDEN_DIM // 32 self.assertEqual(saved, rows * (recv_bytes + 2 * ffn * 2 + 4), "saved bytes") - # A frozen weight's gradient operand is not written (the columnwise grad_gemm_out only - # where the cuDNN FE dGLU can leave it out). - fc1_columnwise = 1 not in frozen or not moe_overlap._dglu_skips_column_outputs() + # A frozen weight's gradient operand is not written. self.assertEqual( - out[8], (fc1_columnwise, 3 not in frozen), "columnwise grad_gemm_out and act_out" + out[8], (1 not in frozen, 3 not in frozen), "columnwise grad_gemm_out and act_out" ) # Where the unfused ops compute the SwiGLU output in their own kernel, single elements may # round to another value, so those results are compared in norm. The unfused MXFP8 ops also diff --git a/transformer_engine/common/ep/ep_backend.cpp b/transformer_engine/common/ep/ep_backend.cpp index f6b86b8cd5c..410b3dfddb0 100644 --- a/transformer_engine/common/ep/ep_backend.cpp +++ b/transformer_engine/common/ep/ep_backend.cpp @@ -242,9 +242,13 @@ void EPBackend::validate_config(const NVTEEpGroupConfig& config) { "dispatch/combine fwd/bwd num_sms must be >= 0 (0 = inherit), got ", sm_cfg.dispatch_fwd_num_sms, ", ", sm_cfg.combine_fwd_num_sms, ", ", sm_cfg.dispatch_bwd_num_sms, ", ", sm_cfg.combine_bwd_num_sms); - NVTE_CHECK(sm_cfg.combine_push_last_chunk_sms >= 0 && sm_cfg.combine_reduce_last_chunk_sms >= 0, + const NVTEEpOverlapConfig& ov_cfg = config.overlap_config; + NVTE_CHECK(ov_cfg.combine_push_last_chunk_sms >= 0 && ov_cfg.combine_reduce_last_chunk_sms >= 0, "combine last-chunk SM counts must be >= 0 (0 = environment), got ", - sm_cfg.combine_push_last_chunk_sms, ", ", sm_cfg.combine_reduce_last_chunk_sms); + ov_cfg.combine_push_last_chunk_sms, ", ", ov_cfg.combine_reduce_last_chunk_sms); + NVTE_CHECK(ov_cfg.dispatch_chunk_tokens >= 0 && ov_cfg.combine_chunk_hidden >= 0, + "overlap chunk sizes must be >= 0 (0 = auto), got ", ov_cfg.dispatch_chunk_tokens, + ", ", ov_cfg.combine_chunk_hidden); const int sm = cuda::sm_arch(); NVTE_CHECK(sm >= 90, "NCCL EP requires SM_90+ (Hopper or later), but current device is SM_", sm); @@ -461,9 +465,9 @@ void EPBackend::init(ncclComm_t ep_comm, NVTEEpGroupConfig group_config) { } }; set_last_chunk_sms("NCCL_EP_HT_COMBINE_PUSH_LAST_CHUNK_SMS", - group_config.sm_config.combine_push_last_chunk_sms); + group_config.overlap_config.combine_push_last_chunk_sms); set_last_chunk_sms("NCCL_EP_HT_COMBINE_REDUCE_LAST_CHUNK_SMS", - group_config.sm_config.combine_reduce_last_chunk_sms); + group_config.overlap_config.combine_reduce_last_chunk_sms); NVTE_CHECK_NCCL(nccl_ep::create_group(&ep_group_, ep_comm, &cfg)); diff --git a/transformer_engine/common/ep/ep_gemm_api.cpp b/transformer_engine/common/ep/ep_gemm_api.cpp index 5f925c43a1a..2b72d151284 100644 --- a/transformer_engine/common/ep/ep_gemm_api.cpp +++ b/transformer_engine/common/ep/ep_gemm_api.cpp @@ -58,11 +58,18 @@ size_t whole_row_chunk(size_t n) { return transformer_engine::DIVUP_TO_MULTIPLE(n, std::min(n, 1024)); } -// Columns per combine flag: one NCCL EP push tile, or the row when shorter. The last chunk of a -// row that 1024 does not divide is the shorter remainder. -size_t combine_chunk(size_t n) { +// Hidden columns per combine flag. configured overrides the default of one NCCL EP push tile +// (1024 bfloat16 elements, or the row when shorter); the last chunk of a row the width does not +// divide is the shorter remainder. +size_t combine_chunk(size_t n, int configured) { NVTE_CHECK(n % kTileN == 0, "output columns (", n, ") must be a multiple of ", kTileN); - return n % 1024 == 0 ? 1024 : whole_row_chunk(n); + if (configured <= 0) return std::min(n, 1024); + const size_t chunk = static_cast(configured); + NVTE_CHECK(chunk >= kTileN && chunk % kTileN == 0, "combine_chunk_hidden (", chunk, + ") must be a multiple of ", kTileN, " and at least ", kTileN); + NVTE_CHECK(chunk <= n, "combine_chunk_hidden (", chunk, + ") must not exceed the hidden dimension (", n, ")"); + return chunk; } // Group and layer state checked by every entry point. @@ -74,11 +81,11 @@ struct EpGemmContext { int all_clusters; // clusters of every SM // max_recv_tokens_per_rank == 0: the caller sized the recv buffers with nvte_ep_prepare. bool eager; + // Rows the dispatch writes per readiness flag and the GEMM waits on, resolved in make_context. + size_t dispatch_signal_unit; size_t alignment() const { return layer_cfg.dispatch_output_per_expert_alignment; } - // Rows per dispatch readiness flag: the alignment. A GEMM M tile (kRowsPerTile rows) is a whole - // multiple of every allowed alignment, so each tile spans a whole number of readiness slots. - size_t signal_unit_tokens() const { return alignment(); } + size_t signal_unit_tokens() const { return dispatch_signal_unit; } }; // comm_sms: the group's SM count of the NCCL EP call that the entry point overlaps; the GEMM runs @@ -111,12 +118,20 @@ EpGemmContext make_context(const NVTEEpLayerConfig* layer_cfg, int NVTEEpSmConfi NVTE_CHECK(max_clusters == sm_count / static_cast(kClusterSize), "the device runs ", max_clusters, " clusters of ", kClusterSize, " SMs at once, not ", sm_count, " / ", kClusterSize); + // The dispatch writes one flag per alignment rows and the GEMM waits on it. dispatch_chunk_tokens + // is a placeholder: the kernel honors only the alignment until it supports coarser granularity. + const int dispatch_chunk = group.overlap_config.dispatch_chunk_tokens; + NVTE_CHECK(dispatch_chunk == 0 || static_cast(dispatch_chunk) == alignment, + "dispatch_chunk_tokens (", dispatch_chunk, + ") is not supported yet: set it to the alignment (", alignment, + ") or leave it 0 until the dispatch kernel supports coarser granularity"); EpGemmContext ctx{backend, group, cfg, (sm_count - comm_sms_count) / static_cast(kClusterSize), sm_count / static_cast(kClusterSize), - group.max_recv_tokens_per_rank == 0}; + group.max_recv_tokens_per_rank == 0, + alignment}; return ctx; } @@ -147,7 +162,7 @@ ep::EpCombineGemmConfig combine_fwd_config(const EpGemmContext& ctx, size_t rows n, num_experts, ctx.num_clusters, - combine_chunk(n), + combine_chunk(n, ctx.group.overlap_config.combine_chunk_hidden), true, false, scaling_mode, @@ -546,7 +561,8 @@ size_t nvte_ep_overlap_prepare(size_t hidden_dim, size_t ffn_dim, size_t num_loc { const EpGemmContext ctx = make_context(layer_cfg, &NVTEEpSmConfig::combine_bwd_num_sms); const bool plain = wg && ctx.num_clusters > 0; - const size_t n_chunk = plain ? 0 : combine_chunk(hidden_dim); + const size_t n_chunk = + plain ? 0 : combine_chunk(hidden_dim, ctx.group.overlap_config.combine_chunk_hidden); const size_t wgrad = wg ? wgrad_workspace_bytes(ctx, rows, 2 * ffn_dim, hidden_dim, ne, mx) : 0; consider(ep::EpCombineGemmConfig{rows, 2 * ffn_dim, hidden_dim, ne, wg ? ctx.all_clusters : ctx.num_clusters, n_chunk, !plain, @@ -976,7 +992,8 @@ void nvte_ep_dispatch_gemm_bwd(NVTETensor handle_mem, const NVTETensor grad_gemm // waits for the GEMM to complete: the GEMM publishes nothing and runs in the stock tile order, // and the one flag of the whole row is reset to 0, published. const bool plain = wgrad && ctx.num_clusters > 0; - const size_t n_chunk = plain ? 0 : combine_chunk(hidden); + const size_t n_chunk = + plain ? 0 : combine_chunk(hidden, ctx.group.overlap_config.combine_chunk_hidden); const size_t chunk = plain ? whole_row_chunk(hidden) : n_chunk; // With the weight gradient the GEMM runs alone on every SM, and the weight gradient beside the diff --git a/transformer_engine/common/include/transformer_engine/ep.h b/transformer_engine/common/include/transformer_engine/ep.h index 6a11e7e3d68..98267dc861a 100644 --- a/transformer_engine/common/include/transformer_engine/ep.h +++ b/transformer_engine/common/include/transformer_engine/ep.h @@ -53,15 +53,23 @@ typedef struct { /*! Backward combine, which carries the dispatch's gradient: nvte_ep_dispatch_bwd(_v2), * nvte_ep_dispatch_gemm_bwd. */ int combine_bwd_num_sms; - /*! Signaled combine only (nvte_ep_combine_gemm_fwd): SMs that push the last chunk, beside the - * reduce of the other chunks; the combine splits only when this is set. 0 leaves +} NVTEEpSmConfig; + +/*! \brief Tuning for the signaled overlap ops (ep_gemm.h); the plain EP ops ignore it. 0 (default) + * takes the backend default. Trailing member of NVTEEpGroupConfig; append new fields only. */ +typedef struct { + /*! Recv rows per dispatch flag. 0 takes the alignment; must equal the alignment for now. */ + int dispatch_chunk_tokens; + /*! Hidden columns per combine flag. 0 takes one push tile (<= 1024); else a multiple of 256 + * within the hidden dimension. */ + int combine_chunk_hidden; + /*! SMs that push the combine's last chunk; the combine splits only when set. 0 leaves * NCCL_EP_HT_COMBINE_PUSH_LAST_CHUNK_SMS to the environment. Same on every rank. */ int combine_push_last_chunk_sms; - /*! Signaled combine only: SMs that reduce the last chunk; 0 leaves - * NCCL_EP_HT_COMBINE_REDUCE_LAST_CHUNK_SMS to the environment, unset the SMs of the other - * chunks' reduce. */ + /*! SMs that reduce the combine's last chunk. 0 leaves NCCL_EP_HT_COMBINE_REDUCE_LAST_CHUNK_SMS + * to the environment. */ int combine_reduce_last_chunk_sms; -} NVTEEpSmConfig; +} NVTEEpOverlapConfig; /*! \brief Group-level EP configuration (fixed for the EP group lifetime). */ typedef struct { @@ -98,6 +106,8 @@ typedef struct { int drop_on_overflow; /*! Per-kernel SM budgets. All-zero (default) inherits num_comm_sms. */ NVTEEpSmConfig sm_config; + /*! Signaled overlap-op tuning. All-zero (default) takes the backend defaults. */ + NVTEEpOverlapConfig overlap_config; } NVTEEpGroupConfig; /*! \brief Per-layer configuration consumed by nvte_ep_handle_mem_size, diff --git a/transformer_engine/pytorch/csrc/extensions.h b/transformer_engine/pytorch/csrc/extensions.h index c8f03df1e04..79fde88b0ae 100644 --- a/transformer_engine/pytorch/csrc/extensions.h +++ b/transformer_engine/pytorch/csrc/extensions.h @@ -769,6 +769,7 @@ void ep_initialize(uintptr_t comm_ptr, const std::string &group_name, int64_t nu bool zero_copy, int64_t num_topk, bool drop_on_overflow, int64_t dispatch_fwd_num_sms, int64_t combine_fwd_num_sms, int64_t dispatch_bwd_num_sms, int64_t combine_bwd_num_sms, + int64_t dispatch_chunk_tokens, int64_t combine_chunk_hidden, int64_t combine_push_last_chunk_sms, int64_t combine_reduce_last_chunk_sms); void ep_finalize(); diff --git a/transformer_engine/pytorch/csrc/extensions/ep.cpp b/transformer_engine/pytorch/csrc/extensions/ep.cpp index e3e7ddb343d..653b0eacd9d 100644 --- a/transformer_engine/pytorch/csrc/extensions/ep.cpp +++ b/transformer_engine/pytorch/csrc/extensions/ep.cpp @@ -363,6 +363,7 @@ void ep_initialize(uintptr_t comm_ptr, const std::string& group_name, int64_t nu bool zero_copy, int64_t num_topk, bool drop_on_overflow, int64_t dispatch_fwd_num_sms, int64_t combine_fwd_num_sms, int64_t dispatch_bwd_num_sms, int64_t combine_bwd_num_sms, + int64_t dispatch_chunk_tokens, int64_t combine_chunk_hidden, int64_t combine_push_last_chunk_sms, int64_t combine_reduce_last_chunk_sms) { NVTE_CHECK(!group_name.empty(), "group_name must be non-empty (used for symm-mem lookup)"); NVTE_CHECK(comm_ptr != 0, "comm_ptr must be non-null (torch NCCL host comm pointer)"); @@ -385,9 +386,11 @@ void ep_initialize(uintptr_t comm_ptr, const std::string& group_name, int64_t nu .num_topk = static_cast(num_topk), .drop_on_overflow = drop_on_overflow ? 1 : 0, .sm_config = {static_cast(dispatch_fwd_num_sms), static_cast(combine_fwd_num_sms), - static_cast(dispatch_bwd_num_sms), static_cast(combine_bwd_num_sms), - static_cast(combine_push_last_chunk_sms), - static_cast(combine_reduce_last_chunk_sms)}, + static_cast(dispatch_bwd_num_sms), static_cast(combine_bwd_num_sms)}, + .overlap_config = {static_cast(dispatch_chunk_tokens), + static_cast(combine_chunk_hidden), + static_cast(combine_push_last_chunk_sms), + static_cast(combine_reduce_last_chunk_sms)}, }; // Release the GIL only around the native init. It must stay held while pybind11 casts // the ``max_token_dtype`` object above and destroys the by-value ``pybind11::object`` @@ -1192,6 +1195,7 @@ void register_ep_bindings(pybind11::module_& m) { py::arg("num_topk") = 0, py::arg("drop_on_overflow") = false, py::arg("dispatch_fwd_num_sms") = 0, py::arg("combine_fwd_num_sms") = 0, py::arg("dispatch_bwd_num_sms") = 0, py::arg("combine_bwd_num_sms") = 0, + py::arg("dispatch_chunk_tokens") = 0, py::arg("combine_chunk_hidden") = 0, py::arg("combine_push_last_chunk_sms") = 0, py::arg("combine_reduce_last_chunk_sms") = 0); m.def("ep_finalize", &ep_finalize, "Tear down the EP backend. Idempotent.", py::call_guard()); diff --git a/transformer_engine/pytorch/ep.py b/transformer_engine/pytorch/ep.py index bd304ace0ef..2b2830bd023 100644 --- a/transformer_engine/pytorch/ep.py +++ b/transformer_engine/pytorch/ep.py @@ -36,6 +36,7 @@ "EpConfig", "EpBuffer", "EpSmConfig", + "EpOverlapConfig", "ep_bootstrap", "get_ep_drop_on_overflow", "get_ep_group", @@ -156,19 +157,31 @@ class EpSmConfig: 0 inherits: a forward budget takes ``max_num_sms`` of ``ep_bootstrap``, a backward budget the forward one. - - ``combine_push_last_chunk_sms`` and ``combine_reduce_last_chunk_sms`` apply only to the - signaled combine of the ``te.ops`` MoE overlap; other EP ops ignore them. The push takes 64 SMs - by default, which saturate NVLink; 0 leaves it to ``NCCL_EP_HT_COMBINE_PUSH_LAST_CHUNK_SMS`` - (unset: the combine does not split). A 0 reduce leaves it to - ``NCCL_EP_HT_COMBINE_REDUCE_LAST_CHUNK_SMS`` (unset: the SMs of the other chunks' reduce). Use - the same values on every rank. """ dispatch_fwd_num_sms: int = 0 combine_fwd_num_sms: int = 0 dispatch_bwd_num_sms: int = 0 combine_bwd_num_sms: int = 0 + + +@dataclass +class EpOverlapConfig: + """Tuning for the signaled ``te.ops`` MoE overlap ops; the plain EP ops ignore it. Use the same + values on every rank. + + - ``dispatch_chunk_tokens``: recv rows per dispatch flag. 0 takes the EP alignment; only the + alignment is allowed for now. + - ``combine_chunk_hidden``: hidden columns per combine flag. 0 takes one push tile (<= 1024), + else a multiple of 256 within the hidden dimension. + - ``combine_push_last_chunk_sms``: SMs that push the combine's last chunk; the combine splits + only when set (64 by default). 0 leaves ``NCCL_EP_HT_COMBINE_PUSH_LAST_CHUNK_SMS``. + - ``combine_reduce_last_chunk_sms``: SMs that reduce the combine's last chunk. 0 leaves + ``NCCL_EP_HT_COMBINE_REDUCE_LAST_CHUNK_SMS``. + """ + + dispatch_chunk_tokens: int = 0 + combine_chunk_hidden: int = 0 combine_push_last_chunk_sms: int = 64 combine_reduce_last_chunk_sms: int = 0 @@ -185,6 +198,7 @@ def ep_bootstrap( drop_on_overflow: bool = False, max_token_dtype: torch.dtype = torch.bfloat16, sm_config: Optional[EpSmConfig] = None, + overlap_config: Optional[EpOverlapConfig] = None, ) -> None: """Initialize EP by borrowing ep_group's NCCL comm. Call once per process. @@ -211,16 +225,21 @@ def ep_bootstrap( (``NVTE_ENABLE_CUTEDSL_BACKEND=1``, ``NVTE_MOE_OVERLAP=1``) and ``zero_copy`` is off. ``sm_config`` (an ``EpSmConfig``) sets the SMs of the NCCL EP kernels of the dispatch and - combine of the layer forward and backward, overlapped or not, and of the last chunk of the - signaled combine. ``FusedMoE`` runs the GEMMs on the remaining SMs. A backward budget other - than the forward one needs NCCL EP with backward SM budgets. ``NCCL_EP_COMM_SMS`` and NCCL - EP's per-call SM variables override these counts, and ``FusedMoE`` rejects them. + combine of the layer forward and backward, overlapped or not. ``FusedMoE`` runs the GEMMs on + the remaining SMs. A backward budget other than the forward one needs NCCL EP with backward SM + budgets. ``NCCL_EP_COMM_SMS`` and NCCL EP's per-call SM variables override these counts, and + ``FusedMoE`` rejects them. + + ``overlap_config`` (an ``EpOverlapConfig``) tunes the signaled ``te.ops`` MoE overlap ops: the + last-chunk push and reduce SMs and the dispatch and combine signaling chunk sizes. The plain EP + ops ignore it. """ global _BOOTSTRAPPED, _ATEXIT_REGISTERED, _EP_GROUP, _EAGER, _BOOTSTRAP_SETTINGS eager = recv_capacity_per_rank is None if max_num_sms == 0 and _moe_overlap_available() and not zero_copy: max_num_sms = _OVERLAP_COMM_SMS sm_config = sm_config or EpSmConfig() + overlap_config = overlap_config or EpOverlapConfig() if _BOOTSTRAPPED: raise RuntimeError("ep_bootstrap was already called in this process") if ep_group.size() < 2: @@ -266,8 +285,10 @@ def ep_bootstrap( int(sm_config.combine_fwd_num_sms), int(sm_config.dispatch_bwd_num_sms), int(sm_config.combine_bwd_num_sms), - int(sm_config.combine_push_last_chunk_sms), - int(sm_config.combine_reduce_last_chunk_sms), + int(overlap_config.dispatch_chunk_tokens), + int(overlap_config.combine_chunk_hidden), + int(overlap_config.combine_push_last_chunk_sms), + int(overlap_config.combine_reduce_last_chunk_sms), ) _BOOTSTRAPPED = True _EP_GROUP = ep_group From 26476fc22788df00827f243216364fc905d77846 Mon Sep 17 00:00:00 2001 From: Phuong Nguyen Date: Wed, 2 Dec 2026 15:17:35 -0800 Subject: [PATCH 30/67] Drop the cuDNN FE capability probe and descriptors-only MXFP8 wgrad fallback now that the required kernels are assumed present Signed-off-by: Phuong Nguyen --- tests/pytorch/distributed/run_test_ep.sh | 2 - tests/pytorch/test_ep_gemm.py | 43 +---- transformer_engine/common/CuTeDSL/__init__.py | 1 - .../common/CuTeDSL/ep_gemm/_loader.py | 156 +----------------- .../common/CuTeDSL/ep_gemm/combine_gemm.py | 4 - .../common/CuTeDSL/ep_gemm/dispatch_gemm.py | 4 - .../common/CuTeDSL/ep_gemm/wgrad_gemm.py | 63 ++----- transformer_engine/common/ep/ep_gemm_api.cpp | 77 ++++----- transformer_engine/common/ep/ep_gemm_config.h | 38 ++--- .../include/transformer_engine/ep_gemm.h | 2 +- .../pytorch/ops/fused/moe_overlap.py | 63 +------ 11 files changed, 81 insertions(+), 372 deletions(-) diff --git a/tests/pytorch/distributed/run_test_ep.sh b/tests/pytorch/distributed/run_test_ep.sh index 3c48bf907bf..1bc17c7d669 100755 --- a/tests/pytorch/distributed/run_test_ep.sh +++ b/tests/pytorch/distributed/run_test_ep.sh @@ -175,8 +175,6 @@ else NVTE_EP_COMM_SMS=12,20,24,16 run_pass "overlap_split_bwd" 0 0 0 1 0 1 # A hidden size that 1024 does not divide: the combine waits on whole rows. NVTE_EP_HIDDEN_DIM=1536 run_pass "overlap_h1536" 0 0 0 1 0 1 - # TODO(phuonguyen): FusedMoE takes only expert alignment 256 until the cuDNN FE grouped GEMMs - # have tail-tile kernels; add the alignment 128 and 64 passes back then. fi finish diff --git a/tests/pytorch/test_ep_gemm.py b/tests/pytorch/test_ep_gemm.py index 3a481c46ad5..cc9b6183b4a 100644 --- a/tests/pytorch/test_ep_gemm.py +++ b/tests/pytorch/test_ep_gemm.py @@ -7,7 +7,6 @@ # pylint: disable=wrong-import-position import ctypes -import importlib import os import pytest @@ -21,7 +20,6 @@ import tvm_ffi from transformer_engine.common.CuTeDSL.ep_gemm import ( - _loader, combine_gemm, dispatch_gemm, wgrad_gemm, @@ -148,7 +146,6 @@ def _run_gemm( [ (TILE, False, [2 * TILE, TILE, 0, 3 * TILE]), (TILE, True, [2 * TILE, TILE, 0, 3 * TILE]), - # TODO(phuonguyen): add the 64/128 alignment cases once cuDNN FE has tail-tile kernels. ], ) @pytest.mark.parametrize("tail_clusters", [0, 4]) @@ -160,8 +157,6 @@ def test_dispatch_gemm_matches_reference( """Grouped GEMM over padded slabs matches a float32 reference, also with experts padded to fewer rows than a tile, with a tail launch sharing the tiles, with the dispatch-written layout and with int64 row ends; rows past the last expert stay 0.""" - if int64_offsets and not _loader.int64_offsets_supported(): - pytest.skip("the cuDNN frontend takes int32 expert offsets only") args = (rows_per_expert, rows_alignment, mxfp8) a, b, alpha, prob, c, d, claims = _run_gemm(*args, tail_clusters, device_layout, int64_offsets) if tail_clusters: @@ -183,19 +178,6 @@ def test_dispatch_gemm_matches_reference( assert torch.count_nonzero(got[used:]) == 0 -def test_int64_offsets_needs_frontend_support(monkeypatch): - """A cuDNN frontend without INT64_OFFSETS is refused for int64 expert offsets only.""" - monkeypatch.delattr(importlib.import_module(_loader._PKG), "INT64_OFFSETS", raising=False) - _loader._gemm_interface_reason.cache_clear() - try: - assert "INT64_OFFSETS" in (_loader.gemm_interface_reason(int64_offsets=True) or "") - assert "INT64_OFFSETS" not in (_loader.gemm_interface_reason() or "") - with pytest.raises(RuntimeError, match="INT64_OFFSETS"): - _loader.offsets_dtype(True) - finally: - _loader._gemm_interface_reason.cache_clear() - - def _run_combine(rows_per_expert, rows_alignment, mxfp8, backward): """Launch the combine GEMM over padded slabs and return (a, b, alpha, prob, d, used) with MXFP8 operands at unit scales in float32. The forward weight is [E, n, k], backward [E, k, n]; @@ -242,7 +224,6 @@ def _run_combine(rows_per_expert, rows_alignment, mxfp8, backward): (False, True, TILE, [2 * TILE, TILE, 0, 3 * TILE]), (True, False, TILE, [2 * TILE, TILE, 0, 3 * TILE]), (True, True, TILE, [2 * TILE, TILE, 0, 3 * TILE]), - # TODO(phuonguyen): add the 128 alignment case once cuDNN FE has tail-tile kernels. ], ) def test_combine_gemm_matches_reference(backward, mxfp8, rows_alignment, rows_per_expert): @@ -270,17 +251,12 @@ def _run_wgrad(rows_per_expert, mxfp8, fp32_out, accumulate, n=512, kernel_class m, experts = 256, len(rows_per_expert) rows = sum(rows_per_expert) + TILE # spare tile: the capacity exceeds the rows in use routed = sum(rows_per_expert) - args = (rows, m, n, experts, 8, fp32_out, accumulate, False, 0, mxfp8, False, TILE, routed) + args = (rows, m, n, experts, 8, fp32_out, accumulate, False, 0, mxfp8, TILE, routed) if kernel_class is not None: assert isinstance(wgrad_gemm.build_kernel(wgrad_gemm._config(*args)), kernel_class) name = f"test_ep_wgrad_{rows}_{n}_{int(mxfp8)}_{int(fp32_out)}_{int(accumulate)}" assert wgrad_gemm.get_ep_wgrad_function(name, *args) - launches = [tvm_ffi.get_global_func(name)] - if mxfp8 and wgrad_gemm.get_ep_wgrad_reads_descriptors(*args): - # A descriptors-only launch writes the per-expert descriptors the GEMM launch reads. - desc = (rows, m, n, experts, 1, fp32_out, accumulate, False, 0, mxfp8, True, TILE, routed) - assert wgrad_gemm.get_ep_wgrad_function(name + "_desc", *desc) - launches.insert(0, tvm_ffi.get_global_func(name + "_desc")) + launch = tvm_ffi.get_global_func(name) gen = torch.Generator(device=device).manual_seed(7) dtype = torch.float8_e4m3fn if mxfp8 else torch.bfloat16 @@ -304,14 +280,13 @@ def _run_wgrad(rows_per_expert, mxfp8, fp32_out, accumulate, n=512, kernel_class # Shared tile counter the launches claim from; the kernel does not reset it. counter = torch.zeros(1, dtype=torch.int32, device=device) stream = ctypes.c_void_p(torch.cuda.current_stream().cuda_stream) - for gemm in launches: - if mxfp8: - gemm( - grad, x, _unit_e8m0(rows * m // 32, device), _unit_e8m0(rows * n // 32, device), - weight_grad, ends, workspace, counter, stream, - ) # fmt: skip - else: - gemm(grad, x, weight_grad, ends, workspace, counter, stream) + if mxfp8: + launch( + grad, x, _unit_e8m0(rows * m // 32, device), _unit_e8m0(rows * n // 32, device), + weight_grad, ends, workspace, counter, stream, + ) # fmt: skip + else: + launch(grad, x, weight_grad, ends, workspace, counter, stream) torch.cuda.synchronize() base = init if accumulate else torch.zeros_like(init) return grad.float(), x.float(), base, weight_grad.float() diff --git a/transformer_engine/common/CuTeDSL/__init__.py b/transformer_engine/common/CuTeDSL/__init__.py index ab845848858..58af43ab352 100644 --- a/transformer_engine/common/CuTeDSL/__init__.py +++ b/transformer_engine/common/CuTeDSL/__init__.py @@ -42,7 +42,6 @@ def _register_ep_backends(): combine_gemm.get_ep_combine_gemm_workspace_layout, wgrad_gemm.get_ep_wgrad_function, wgrad_gemm.get_ep_wgrad_workspace_layout, - wgrad_gemm.get_ep_wgrad_reads_descriptors, ): tvm_ffi.register_global_func(function.__name__, function, override=True) except Exception as e: # pylint: disable=broad-exception-caught diff --git a/transformer_engine/common/CuTeDSL/ep_gemm/_loader.py b/transformer_engine/common/CuTeDSL/ep_gemm/_loader.py index 19d2543ad72..d175c560557 100644 --- a/transformer_engine/common/CuTeDSL/ep_gemm/_loader.py +++ b/transformer_engine/common/CuTeDSL/ep_gemm/_loader.py @@ -8,12 +8,9 @@ compiled once per configuration and registered under a name chosen by C++. """ -import functools import importlib -import inspect import logging from dataclasses import dataclass -from typing import Optional import tvm_ffi @@ -29,7 +26,7 @@ SF_VEC_SIZE = 32 # cuDNN frontend package holding the EP grouped GEMM kernels. -# TODO(phuonguyen): gate on a cuDNN FE minimum version once the kernels ship versioned. +# TODO(phuonguyen): gate on a cuDNN FE minimum version once the kernels are upstreamed. _PKG = "cudnn.gemm.cutedsl.grouped" # Dotted path within _PKG for each module name the kernels load. @@ -66,38 +63,18 @@ class GemmArch: dispatch_fwd: str # FC1 + SwiGLU dispatch_bwd: str # FC2 data gradient + SwiGLU backward combine: str # FC2, FC1 data gradient - # MXFP8 kernel module names, loaded on demand by the MXFP8 paths. - mxfp8_modules: tuple _SM100 = GemmArch( dispatch_fwd="glu.moe_grouped_gemm_glu_bias.MoEGroupedGemmGluBiasBf16Kernel", dispatch_bwd="dglu.moe_grouped_gemm_dglu_dbias.MoEGroupedGemmDgluDbiasBf16Kernel", combine="unfused.moe_grouped_gemm.MoEGroupedGemmBf16Kernel", - mxfp8_modules=( - "moe_blockscaled_grouped_gemm_quant_sm100", - "moe_blockscaled_grouped_gemm_glu_bias", - "moe_blockscaled_grouped_gemm_dglu_dbias", - "moe_blockscaled_grouped_gemm_wgrad", - "moe_blockscaled_grouped_gemm_wgrad_dense", - "moe_blockscaled_grouped_gemm_wgrad_reuse", - ), ) -# SM 10.7 (Rubin) has no BF16 kernels in cuDNN FE yet, so the BF16 roles reuse the SM 10.0 ones. -# TODO(phuonguyen): point these at real Rubin BF16 kernels when cuDNN FE adds them; validate on -# Rubin hardware. +# SM 10.7 (Rubin) runs the SM 10.0 BF16 kernels, which cuDNN FE sizes to the device's shared memory. _SM107 = GemmArch( dispatch_fwd=_SM100.dispatch_fwd, dispatch_bwd=_SM100.dispatch_bwd, combine=_SM100.combine, - mxfp8_modules=( - "moe_blockscaled_grouped_gemm_quant_rubin", - "moe_blockscaled_grouped_gemm_glu_rubin", - "moe_blockscaled_grouped_gemm_dglu_rubin", - "moe_blockscaled_grouped_gemm_wgrad_rubin", - "moe_blockscaled_grouped_gemm_wgrad_dense_rubin", - "moe_blockscaled_grouped_gemm_wgrad_reuse_rubin", - ), ) # Kernels by compute capability; other architectures run the unfused ops. GEMM_ARCHS = {(10, 0): _SM100, (10, 3): _SM100, (10, 7): _SM107} @@ -129,115 +106,9 @@ def import_bf16_kernel(role): return getattr(module, class_name), importlib.import_module(f"{_PKG}.moe_utils") -# What TE reads from the kernel package, module by module (dotted names are nested attributes). -_SHARED_INTERFACE = { - "moe_utils": ("MoEWeightMode.DENSE", "WGradInputOrder.Tensor2D"), - "moe_kernel_helpers": ("streaming_signal_workspace_offsets",), - "moe_streaming_output_chunk_tile_scheduler": ( - "StreamingOutputNotifyConfig", - "StreamingOutputNotifyMode.N_CHUNK", - "streaming_output_notify_capacity", - "streaming_output_notify_offsets", - ), -} - - -def _missing(obj, dotted_names): - """The names of ``dotted_names`` that ``obj`` lacks.""" - missing = [] - for dotted in dotted_names: - target = obj - for part in dotted.split("."): - target = getattr(target, part, None) - if target is None: - missing.append(dotted) - return missing - - -@functools.lru_cache(maxsize=None) -def _gemm_interface_reason(capability, mxfp8, int64_offsets): - del capability # The cache key: the architecture the checks ran on. - problems = [] - try: - if int64_offsets and not int64_offsets_supported(): - problems.append( - f"{_PKG} lacks INT64_OFFSETS: install a cuDNN frontend whose grouped GEMMs take" - " int64 expert offsets" - ) - for name, attributes in _SHARED_INTERFACE.items(): - missing = _missing(import_gemm_modules(name)[0], attributes) - if missing: - problems.append(f"{name} lacks {', '.join(missing)}") - arch = gemm_arch() - for role in ("dispatch_fwd", "dispatch_bwd", "combine"): - module_name, class_name = getattr(arch, role).rsplit(".", 1) - module = importlib.import_module(f"{_PKG}.{module_name}") - if getattr(module, class_name, None) is None: - problems.append(f"{module_name} lacks {class_name}") - if mxfp8: - for module_name in arch.mxfp8_modules: - import_gemm_modules(module_name) - except ImportError as e: - problems.append(f"cannot import {e.name or e}") - if problems: - return ( - "the cuDNN frontend grouped GEMM kernels do not match Transformer Engine: " - + "; ".join(problems) - ) - return None - - -def gemm_interface_reason(mxfp8=False, int64_offsets=False) -> Optional[str]: - """Why the installed cuDNN frontend lacks what the EP grouped GEMMs read, or None; ``mxfp8`` - also checks the MXFP8 kernels, ``int64_offsets`` int64 expert offsets. Checked once per - architecture and setting.""" - return _gemm_interface_reason(device_compute_capability(), mxfp8, int64_offsets) - - -def int64_offsets_supported() -> bool: - """Whether the cuDNN frontend grouped GEMMs take int64 expert offsets (int32 always works).""" - try: - return getattr(importlib.import_module(_PKG), "INT64_OFFSETS", False) - except ImportError: - return False - - -@functools.lru_cache(maxsize=None) -def dglu_skips_column_outputs() -> bool: - """Whether the MXFP8 dGLU leaves out its columnwise D when given none (older cuDNN - frontends always write it).""" - try: - return getattr(importlib.import_module(_PKG), "DGLU_OPTIONAL_SFD_COL", False) - except ImportError: - return False - - -@functools.lru_cache(maxsize=None) -def bf16_wgrad_waits_on_signal() -> bool: - """Whether the SM 10.x BF16 weight gradient can wait per tile on a readiness signal (older - cuDNN frontends lack it).""" - try: - return getattr(importlib.import_module(_PKG), "BF16_WGRAD_STREAMING_SIGNAL", False) - except ImportError: - return False - - -@functools.lru_cache(maxsize=None) def wide_bf16_wgrad_kernel(): - """The SM 10.x 256 x 512 BF16 weight-gradient kernel class when it claims from a caller's tile - counter and checks its shapes, else None (older cuDNN frontends).""" - try: - kernel_class = import_gemm_modules("moe_grouped_gemm_wgrad_wide")[0] - kernel_class = kernel_class.MoEGroupedGemmWgradWideBF16Kernel - except (ImportError, AttributeError): - return None - try: - params = inspect.signature(kernel_class.__call__).parameters - except (TypeError, ValueError): - return None - if "scheduler_counter" not in params or not hasattr(kernel_class, "can_implement"): - return None - return kernel_class + """The SM 10.x 256 x 512 BF16 weight-gradient kernel class.""" + return import_gemm_modules("moe_grouped_gemm_wgrad_wide")[0].MoEGroupedGemmWgradWideBF16Kernel def unsupported_device_reason(what): @@ -321,27 +192,10 @@ def blockscaled_kwargs(num_experts): } -def tail_tile_kwargs(token_alignment, fused=False): - """Constructor arguments for experts padded to ``token_alignment`` rows.""" - del token_alignment, fused - # TODO(phuonguyen): cuDNN FE has no sub-tile (tail) kernels, so experts pad to a full row tile - # and no tail arguments are passed. Restore the tail arguments once tail-tiles land. - return {} - - -def mxfp8_tail_tile_kwargs(token_alignment): - """``tail_tile_kwargs`` of the MXFP8 kernels.""" - del token_alignment - # TODO(phuonguyen): see tail_tile_kwargs; cuDNN FE has no MXFP8 tail kernels yet. - return {} - - def offsets_dtype(int64_offsets): - """CuTe dtype of the expert row ends: Int64 needs a cuDNN frontend with INT64_OFFSETS.""" + """CuTe dtype of the expert row ends.""" import cutlass # pylint: disable=import-outside-toplevel - if int64_offsets and not int64_offsets_supported(): - raise RuntimeError(f"{_PKG} lacks INT64_OFFSETS: it takes int32 expert offsets only") return cutlass.Int64 if int64_offsets else cutlass.Int32 diff --git a/transformer_engine/common/CuTeDSL/ep_gemm/combine_gemm.py b/transformer_engine/common/CuTeDSL/ep_gemm/combine_gemm.py index a0a09d08826..f5ad7107091 100644 --- a/transformer_engine/common/CuTeDSL/ep_gemm/combine_gemm.py +++ b/transformer_engine/common/CuTeDSL/ep_gemm/combine_gemm.py @@ -37,13 +37,11 @@ import_bf16_kernel, import_gemm_modules, is_sm107, - mxfp8_tail_tile_kwargs, prob_view, register_function, rows_view, scale_fake, tail_fakes, - tail_tile_kwargs, weight_view, ) @@ -100,7 +98,6 @@ def build_kernel(cfg: CombineGemmConfig): launch_pdl_dependents_at_entry=cfg.dependents_at_entry, **({"generate_c": False} if rubin else {}), **blockscaled_kwargs(cfg.num_experts), - **mxfp8_tail_tile_kwargs(cfg.token_alignment), ) kernel_class, _ = import_bf16_kernel("combine") return kernel_class( @@ -116,7 +113,6 @@ def build_kernel(cfg: CombineGemmConfig): use_dynamic_sched=True, streaming_output_notify=notify, launch_pdl_dependents_at_entry=cfg.dependents_at_entry, - **tail_tile_kwargs(cfg.token_alignment, fused=not cfg.backward), ) diff --git a/transformer_engine/common/CuTeDSL/ep_gemm/dispatch_gemm.py b/transformer_engine/common/CuTeDSL/ep_gemm/dispatch_gemm.py index 10e1941804c..3e166ced809 100644 --- a/transformer_engine/common/CuTeDSL/ep_gemm/dispatch_gemm.py +++ b/transformer_engine/common/CuTeDSL/ep_gemm/dispatch_gemm.py @@ -46,13 +46,11 @@ import_bf16_kernel, import_gemm_modules, is_sm107, - mxfp8_tail_tile_kwargs, prob_view, register_function, rows_view, scale_fake, tail_fakes, - tail_tile_kwargs, weight_view, ) @@ -120,7 +118,6 @@ def build_kernel(cfg: DispatchGemmConfig): "streaming_signal_capacity": cfg.signal_capacity, "compact_sfa_sf_warp": True, "use_pdl": True, - **mxfp8_tail_tile_kwargs(cfg.token_alignment), } if cfg.backward and rubin: # 128-deep K tiles of one scale atom each: the TMA warp queues the compact scales ahead. @@ -178,7 +175,6 @@ def build_kernel(cfg: DispatchGemmConfig): "use_dynamic_sched": True, "streaming_signal_capacity": cfg.signal_capacity, "use_pdl": True, - **tail_tile_kwargs(cfg.token_alignment, fused=not cfg.backward), } if cfg.backward: kernel_class, moe_utils = import_bf16_kernel("dispatch_bwd") diff --git a/transformer_engine/common/CuTeDSL/ep_gemm/wgrad_gemm.py b/transformer_engine/common/CuTeDSL/ep_gemm/wgrad_gemm.py index 6e23c0e7068..cc9ed3a169f 100644 --- a/transformer_engine/common/CuTeDSL/ep_gemm/wgrad_gemm.py +++ b/transformer_engine/common/CuTeDSL/ep_gemm/wgrad_gemm.py @@ -27,7 +27,6 @@ CLUSTER_MN, MMA_TILER_MN, SF_VEC_SIZE, - bf16_wgrad_waits_on_signal, fake_tensor, fp8_fake, import_gemm_modules, @@ -67,8 +66,8 @@ def mxfp8(self) -> bool: @property def waits_on_signal(self) -> bool: """Whether each tile waits for the dispatch flags of its rows instead of the kernel before - it: BF16 with a cuDNN frontend that has the wait.""" - return self.signal_unit_tokens > 0 and not self.mxfp8 and bf16_wgrad_waits_on_signal() + it.""" + return self.signal_unit_tokens > 0 @property def wide(self) -> bool: @@ -76,8 +75,7 @@ def wide(self) -> bool: whose shape it implements, with no wait on the dispatch flags.""" if self.mxfp8 or self.accumulate or self.fp32_out or self.waits_on_signal: return False - kernel_class = wide_bf16_wgrad_kernel() - return kernel_class is not None and kernel_class.can_implement(self.m, self.n) + return wide_bf16_wgrad_kernel().can_implement(self.m, self.n) def _mxfp8_kernels(): @@ -131,14 +129,6 @@ def _global_descriptor_kernel(cfg: WgradConfig): return dense -def reads_descriptors(cfg: WgradConfig) -> bool: - """Whether the launches of ``cfg`` read per-expert descriptors from a ``descriptors_only`` - launch.""" - del cfg - # The cuDNN FE stock kernel builds its per-expert descriptors in its own helper kernel. - return False - - def build_kernel(cfg: WgradConfig): """Weight-gradient kernel for ``cfg``. Persistent clusters claim output tiles from an atomic counter in the workspace, so launches sharing one workspace split the tiles across SMs. An @@ -276,22 +266,14 @@ def launch(grad, x, weight_grad, expert_row_ends, workspace, counter, stream): if not cfg.signal_unit_tokens: return compile_launch(launch, *fakes) - waits_on_signal = cfg.waits_on_signal @cute.jit def launch_signal(grad, x, weight_grad, expert_row_ends, workspace, counter, signal, stream): a, b, out = views(grad, x, weight_grad) - if cutlass.const_expr(waits_on_signal): - kernel( - a, b, out, expert_row_ends, workspace, num_clusters, stream, - scheduler_counter=counter, streaming_signal=signal, - ) # fmt: skip - else: - # A cuDNN frontend without the wait: the flags go unread. - kernel( - a, b, out, expert_row_ends, workspace, num_clusters, stream, - scheduler_counter=counter, - ) # fmt: skip + kernel( + a, b, out, expert_row_ends, workspace, num_clusters, stream, + scheduler_counter=counter, streaming_signal=signal, + ) # fmt: skip signal_fake = fake_tensor(cutlass.Int32, (rows // cfg.signal_unit_tokens,), (0,), 4) return compile_launch(launch_signal, *fakes, signal_fake) @@ -299,14 +281,11 @@ def launch_signal(grad, x, weight_grad, expert_row_ends, workspace, counter, sig def _config( rows, m, n, num_experts, num_clusters, fp32_out, accumulate, wait_primary_at_start, - signal_unit_tokens, scaling_mode, descriptors_only, token_alignment, routed_tokens, + signal_unit_tokens, scaling_mode, token_alignment, routed_tokens, int64_offsets=False, ): # fmt: skip - """Build a WgradConfig from the entry-point arguments. descriptors_only selects a cuDNN FE - kernel that does not exist (see build_kernel); it is accepted for ABI stability and ignored. - A launch with signal_unit_tokens takes the dispatch flags, which it reads where the kernel - waits on them and ignores elsewhere (it then waits as wait_primary_at_start says).""" - del descriptors_only + """Build a WgradConfig from the entry-point arguments. A launch with signal_unit_tokens takes + the dispatch flags and waits on them per tile.""" return WgradConfig( rows, m, n, num_experts, num_clusters, bool(fp32_out), bool(accumulate), int(scaling_mode), bool(wait_primary_at_start), token_alignment, routed_tokens, int(signal_unit_tokens), @@ -316,41 +295,27 @@ def _config( def get_ep_wgrad_workspace_layout( rows, m, n, num_experts, num_clusters, fp32_out, accumulate, wait_primary_at_start, - signal_unit_tokens, scaling_mode, descriptors_only, token_alignment, routed_tokens, + signal_unit_tokens, scaling_mode, token_alignment, routed_tokens, int64_offsets=False, ): # fmt: skip """[total bytes, counter offset] of the workspace of this configuration.""" return list(workspace_layout(_config( rows, m, n, num_experts, num_clusters, fp32_out, accumulate, wait_primary_at_start, - signal_unit_tokens, scaling_mode, descriptors_only, token_alignment, routed_tokens, + signal_unit_tokens, scaling_mode, token_alignment, routed_tokens, int64_offsets, ))) # fmt: skip -def get_ep_wgrad_reads_descriptors( - rows, m, n, num_experts, num_clusters, fp32_out, accumulate, wait_primary_at_start, - signal_unit_tokens, scaling_mode, descriptors_only, token_alignment, routed_tokens, - int64_offsets=False, -) -> bool: # fmt: skip - """Whether the launches of this configuration read the per-expert descriptors of a - ``descriptors_only`` launch.""" - return reads_descriptors(_config( - rows, m, n, num_experts, num_clusters, fp32_out, accumulate, wait_primary_at_start, - signal_unit_tokens, scaling_mode, descriptors_only, token_alignment, routed_tokens, - int64_offsets, - )) # fmt: skip - - def get_ep_wgrad_function( fn_name, rows, m, n, num_experts, num_clusters, fp32_out, accumulate, wait_primary_at_start, - signal_unit_tokens, scaling_mode, descriptors_only, token_alignment, routed_tokens, + signal_unit_tokens, scaling_mode, token_alignment, routed_tokens, int64_offsets=False, ) -> bool: # fmt: skip """Compile and register the weight gradient of this configuration as ``fn_name``; return whether it is.""" cfg = _config( rows, m, n, num_experts, num_clusters, fp32_out, accumulate, wait_primary_at_start, - signal_unit_tokens, scaling_mode, descriptors_only, token_alignment, routed_tokens, + signal_unit_tokens, scaling_mode, token_alignment, routed_tokens, int64_offsets, ) # fmt: skip return register_function(fn_name, lambda: _compile(cfg), "EP weight-gradient grouped GEMM") diff --git a/transformer_engine/common/ep/ep_gemm_api.cpp b/transformer_engine/common/ep/ep_gemm_api.cpp index 2b72d151284..beaa8576e45 100644 --- a/transformer_engine/common/ep/ep_gemm_api.cpp +++ b/transformer_engine/common/ep/ep_gemm_api.cpp @@ -374,36 +374,25 @@ std::optional make_wgrad(const EpGemmContext& ctx, NVTETensor grad, NVTET "weight_grad must be bfloat16 or float32"); const size_t routed_tokens = static_cast(ctx.group.max_tokens_per_rank) * ctx.layer_cfg.top_k; - Wgrad wgrad{ - grad, - x, - weight_grad, - {rows, m, n, num_experts, 1, out_type == kNVTEFloat32, accumulate, false, signal_unit_tokens, - scaling_mode, false, ctx.alignment(), routed_tokens, int64_offsets}, - {}}; + Wgrad wgrad{grad, + x, + weight_grad, + {rows, m, n, num_experts, 1, out_type == kNVTEFloat32, accumulate, false, + signal_unit_tokens, scaling_mode, ctx.alignment(), routed_tokens, int64_offsets}, + {}}; const auto layout = wgrad.config.workspace_layout(); NVTE_CHECK(layout.has_value(), "cannot query the weight-gradient workspace layout"); wgrad.layout = *layout; return wgrad; } -// Whether the MXFP8 weight gradient reads per-expert descriptors that a descriptors_only launch -// writes: an added or FP32 one, and on SM 10.7 a written BF16 one with long experts. The others -// read global descriptors. -bool needs_descriptors(const Wgrad& wgrad) { - return wgrad.config.is_mxfp8() && wgrad.config.reads_descriptors(); -} - // One launch of a weight gradient on num_clusters clusters (none: no launch), a programmatic // dependent of the kernel before it. Launches sharing the call's workspace split the tiles. // wait_primary_at_start: no load before that kernel completes. signal_unit_tokens (BF16): the -// launch takes the dispatch flags of that many rows each; where the kernel waits on them, no load -// before every flag of the expert rows is set, in place of wait_primary_at_start. -// descriptors_only (MXFP8): a plain launch that writes the per-expert descriptors the other -// launches read; it follows the scratch reset. +// launch takes the dispatch flags of that many rows each: no load before every flag of the expert +// rows is set, in place of wait_primary_at_start. void launch_wgrad(const Wgrad& wgrad, const GemmScratch& scratch, int num_clusters, - bool wait_primary_at_start, size_t signal_unit_tokens, cudaStream_t stream, - bool descriptors_only) { + bool wait_primary_at_start, size_t signal_unit_tokens, cudaStream_t stream) { if (num_clusters <= 0) { return; } @@ -411,7 +400,6 @@ void launch_wgrad(const Wgrad& wgrad, const GemmScratch& scratch, int num_cluste config.num_clusters = num_clusters; config.wait_primary_at_start = wait_primary_at_start; config.signal_unit_tokens = signal_unit_tokens; - config.descriptors_only = descriptors_only; ep::WorkspaceLayout layout; const tvm::ffi::Function gemm = get_gemm(config, &layout); // The call sized the scratch from its base configuration. A base and tail must land on one @@ -447,11 +435,11 @@ void launch_wgrad(const Wgrad& wgrad, const GemmScratch& scratch, int num_cluste // The columnwise MXFP8 copy of t's received rows, requantized from its rowwise data and compact // scales into GEMM-swizzled columnwise scales per expert slab. The shared grouped MXFP8 requant -// runs as a programmatic dependent (PDL): it overlaps the producing GEMM on the SMs the reverse -// dispatch frees. The expert slabs are given by the element offsets reset_workspace writes from the -// expert layout. +// With pdl it runs as a programmatic dependent that overlaps the producing GEMM; without it the +// kernel waits for the preceding one on the stream. The expert slabs are given by the element +// offsets reset_workspace writes from the expert layout. void launch_requant(NVTETensor t, const GemmScratch& scratch, size_t rows, size_t cols, - size_t num_experts, cudaStream_t stream) { + size_t num_experts, bool pdl, cudaStream_t stream) { using namespace transformer_engine; const NVTEBasicTensor row_data{nvte_tensor_data(t), nvte_tensor_type(t), nvte_tensor_shape(t)}; const NVTEBasicTensor row_sf = nvte_get_tensor_param(t, kNVTERowwiseScaleInv); @@ -471,8 +459,7 @@ void launch_requant(NVTETensor t, const GemmScratch& scratch, size_t rows, size_ output.set_with_gemm_swizzled_scales(true); GroupedTensor* const in = convertNVTEGroupedTensorCheck(input.data()); GroupedTensor* const out = convertNVTEGroupedTensorCheck(output.data()); - const bool ok = - cutedsl_backend::mxfp8_requantize_cutedsl(*in, out, nullptr, stream, /*pdl=*/true); + const bool ok = cutedsl_backend::mxfp8_requantize_cutedsl(*in, out, nullptr, stream, pdl); NVTE_CHECK(ok, "the EP MXFP8 requant is not available: needs NVTE_ENABLE_CUTEDSL_BACKEND=1, " "NVTE_MOE_OVERLAP=1 and SM 10.0, 10.3 or 10.7"); @@ -486,8 +473,17 @@ size_t wgrad_workspace_bytes(const EpGemmContext& ctx, size_t rows, size_t m, si static_cast(ctx.group.max_tokens_per_rank) * ctx.layer_cfg.top_k; size_t bytes = 0; for (const bool fp32_out : {false, true}) { - const ep::EpWgradConfig config{rows, m, n, num_experts, 1, fp32_out, - false, false, 0, scaling_mode, false, ctx.alignment(), + const ep::EpWgradConfig config{rows, + m, + n, + num_experts, + 1, + fp32_out, + false, + false, + 0, + scaling_mode, + ctx.alignment(), routed_tokens}; // The output precision is not known here, so size over both. A variant the device does not // support (e.g. the SM 10.7 FP32 MXFP8 weight gradient at or below 256 rows) throws while @@ -871,9 +867,6 @@ void nvte_ep_combine_gemm_bwd( scratch.reset.offsets_cols = static_cast(hidden); } ep::reset_workspace(scratch.reset, stream); - if (wgrad && needs_descriptors(*wgrad)) { - launch_wgrad(*wgrad, scratch, 1, false, 0, stream, true); - } // The reverse dispatch publishes one flag per slot; the GEMM consumes ready tiles. TensorWrapper signal(scratch.signal, @@ -915,7 +908,7 @@ void nvte_ep_combine_gemm_bwd( // The columnwise grad_expert_out, a dependent of the GEMM. It runs on the SMs the reverse // dispatch frees, so its rows are already delivered and it needs no per-tile readiness signal. if (requant) { - launch_requant(grad_expert_out, scratch, rows, hidden, num_experts, stream); + launch_requant(grad_expert_out, scratch, rows, hidden, num_experts, /*pdl=*/true, stream); } // Its tail on the SMs the reverse dispatch frees takes the tiles the GEMM has not claimed. const int tail_clusters = ctx.all_clusters - ctx.num_clusters; @@ -932,17 +925,17 @@ void nvte_ep_combine_gemm_bwd( // only these get the stock kernel. const bool helper = wgrad->config.accumulate || wgrad->config.fp32_out; const int base_clusters = helper ? ctx.all_clusters : ctx.num_clusters; - launch_wgrad(*wgrad, scratch, base_clusters, true, 0, stream, false); - launch_wgrad(*wgrad, scratch, ctx.all_clusters - base_clusters, false, 0, stream, false); + launch_wgrad(*wgrad, scratch, base_clusters, true, 0, stream); + launch_wgrad(*wgrad, scratch, ctx.all_clusters - base_clusters, false, 0, stream); } return; } auto b = wrap_rowwise(weight, false); gemm(&a, &b, &c, &d, &dprob, &row_ends, &alpha, &prob, &ws, static_cast(stream)); // The weight gradient on every SM: beside the GEMM, each tile once the dispatch flags of its rows - // are set, where the kernel waits on them; else once the GEMM completes. + // are set. if (wgrad) { - launch_wgrad(*wgrad, scratch, ctx.all_clusters, true, wgrad_signal_tokens, stream, false); + launch_wgrad(*wgrad, scratch, ctx.all_clusters, true, wgrad_signal_tokens, stream); } } @@ -1017,12 +1010,10 @@ void nvte_ep_dispatch_gemm_bwd(NVTETensor handle_mem, const NVTETensor grad_gemm scratch.reset.offsets_cols = static_cast(hidden); } ep::reset_workspace(scratch.reset, stream); - if (wgrad && needs_descriptors(*wgrad)) { - launch_wgrad(*wgrad, scratch, 1, false, 0, stream, true); - } - // The columnwise wgrad_input, before the GEMM. + // The columnwise wgrad_input, before the GEMM. It reads the resident dispatched tokens, so it + // overlaps as a programmatic dependent without a readiness signal. if (requant) { - launch_requant(wgrad_input, scratch, rows, hidden, num_experts, stream); + launch_requant(wgrad_input, scratch, rows, hidden, num_experts, /*pdl=*/true, stream); } // The GEMM fills the flags; the dispatch backward is its programmatic dependent. @@ -1045,7 +1036,7 @@ void nvte_ep_dispatch_gemm_bwd(NVTETensor handle_mem, const NVTETensor grad_gemm // The weight gradient starts once the GEMM completes and lets the dispatch backward in. The // dispatch backward completes after it, so a launch behind them would find no tiles left. if (wgrad) { - launch_wgrad(*wgrad, scratch, ctx.num_clusters, true, 0, stream, false); + launch_wgrad(*wgrad, scratch, ctx.num_clusters, true, 0, stream); } NVTECommWindow no_window{}; diff --git a/transformer_engine/common/ep/ep_gemm_config.h b/transformer_engine/common/ep/ep_gemm_config.h index 68f115c0f5e..80a0a9ea049 100644 --- a/transformer_engine/common/ep/ep_gemm_config.h +++ b/transformer_engine/common/ep/ep_gemm_config.h @@ -249,25 +249,20 @@ struct EpCombineGemmConfig { struct EpWgradConfig { static constexpr const char *kEntrypointName = "get_ep_wgrad_function"; static constexpr const char *kLayoutName = "get_ep_wgrad_workspace_layout"; - static constexpr const char *kDescriptorsName = "get_ep_wgrad_reads_descriptors"; size_t rows; // receive capacity size_t m; // rows of each expert's weight gradient size_t n; // columns of each expert's weight gradient size_t num_experts; - int num_clusters; // persistent clusters - bool fp32_out; // FP32 instead of BF16 weight gradient - bool accumulate; // add to the weight gradient instead of writing it - bool wait_primary_at_start; // wait for the kernel before it ahead of any load - size_t signal_unit_tokens; // wait for every dispatch flag of this many rows, 0: none - // Operand scaling: delayed for BF16, MXFP8 1D for MXFP8. With MXFP8 the GEMM launches of some - // weight gradients (reads_descriptors) read the per-expert descriptors that one launch with - // descriptors_only writes into the workspace first. - NVTEScalingMode scaling_mode; - bool descriptors_only; - size_t token_alignment; // rows per expert slab are a multiple of it - size_t routed_tokens; // rows a rank receives at capacity under uniform routing, unpadded - bool int64_offsets = false; // the row ends are int64 instead of int32 + int num_clusters; // persistent clusters + bool fp32_out; // FP32 instead of BF16 weight gradient + bool accumulate; // add to the weight gradient instead of writing it + bool wait_primary_at_start; // wait for the kernel before it ahead of any load + size_t signal_unit_tokens; // wait for every dispatch flag of this many rows, 0: none + NVTEScalingMode scaling_mode; // operand scaling: delayed for BF16, MXFP8 1D for MXFP8 + size_t token_alignment; // rows per expert slab are a multiple of it + size_t routed_tokens; // rows a rank receives at capacity under uniform routing, unpadded + bool int64_offsets = false; // the row ends are int64 instead of int32 bool is_mxfp8() const { return scaling_mode == NVTE_MXFP8_1D_SCALING; } @@ -277,7 +272,7 @@ struct EpWgradConfig { static_cast(rows), static_cast(m), static_cast(n), static_cast(num_experts), num_clusters, fp32_out, accumulate, wait_primary_at_start, static_cast(signal_unit_tokens), - static_cast(scaling_mode), descriptors_only, static_cast(token_alignment), + static_cast(scaling_mode), static_cast(token_alignment), static_cast(routed_tokens), int64_offsets); } @@ -291,19 +286,6 @@ struct EpWgradConfig { // total_bytes and the byte offset of the claim counter. std::optional workspace_layout() const { return query_layout(*this); } - - // Whether the GEMM launches read the per-expert descriptors of a descriptors_only launch, kept - // per configuration once found. Without an answer, the added and FP32 ones read them. - bool reads_descriptors() const { - static auto &cache = KeyedCache::create(); - return cache - .get(to_key(), - [&]() -> std::optional { - auto result = call_entry(kDescriptorsName, *this); - return result.has_value() ? result->template try_cast() : std::nullopt; - }) - .value_or(is_mxfp8() && (accumulate || fp32_out)); - } }; } // namespace ep diff --git a/transformer_engine/common/include/transformer_engine/ep_gemm.h b/transformer_engine/common/include/transformer_engine/ep_gemm.h index 4bf19cce3f2..bc886cc22d9 100644 --- a/transformer_engine/common/include/transformer_engine/ep_gemm.h +++ b/transformer_engine/common/include/transformer_engine/ep_gemm.h @@ -28,7 +28,7 @@ * Requirements (all calls): * - SM 10.0, 10.3 or 10.7; EP within one NVLink domain; num_comm_sms > 0; zero_copy off. * - dispatch_output_per_expert_alignment: bfloat16 is 64, 128 or 256; MXFP8 is 256, or 128 - * except on SM 10.7. The cuDNN FE kernels run alignment 256 only until they have tail tiles. + * except on SM 10.7. The cuDNN FE kernels run alignment 256 only. * - NVTE_ENABLE_CUTEDSL_BACKEND=1 and NVTE_MOE_OVERLAP=1. * - MXFP8: hidden_dim a multiple of 512, ffn_dim a multiple of 256. * - First call per shape compiles its GEMM: run it at warmup, outside CUDA graph capture. diff --git a/transformer_engine/pytorch/ops/fused/moe_overlap.py b/transformer_engine/pytorch/ops/fused/moe_overlap.py index 50a9608cfc8..0bb9f3ebb7f 100644 --- a/transformer_engine/pytorch/ops/fused/moe_overlap.py +++ b/transformer_engine/pytorch/ops/fused/moe_overlap.py @@ -101,20 +101,8 @@ class FusedMoE(FusedOperation): @classmethod def is_supported(cls) -> bool: """Whether this fused operation can run on the current system.""" - # TODO(phuonguyen): once the kernels and the overlap signals are upstreamed into cuDNN and - # NCCL EP, gate this on their minimum versions instead of the kernel path and interface - # check. - if not _moe_overlap_available() or _gemm_interface_reason() is not None: - return False - if get_device_compute_capability() != (10, 7): - return GroupedMLP_CuTeGEMMGLUBf16.is_supported() - # SM 10.7 has no BF16 cuDNN GLU kernels; the EP GEMMs replace them, and this op takes only - # the cuDNN wgrad kernel. - try: - kernel = GroupedMLP_CuTeGEMMGLUBf16.grouped_gemm_wgrad_kernel() - except ImportError: - return False - return getattr(kernel, "supports_bf16_canonical_layouts", False) + # TODO(phuonguyen): gate on the cuDNN FE minimum version once the kernels are upstreamed. + return _moe_overlap_available() def __init__( self, @@ -467,11 +455,9 @@ def empty(quantizer, cols): hidden, ) # The columnwise grad_gemm_out feeds the FC1 weight gradient and act_out the FC2 one, so - # the call writes neither for a frozen weight (the columnwise grad_gemm_out only where the - # cuDNN FE dGLU can leave it out). - grad_gemm_columnwise = fc1_ctx.weight_requires_grad or not _dglu_skips_column_outputs() + # the call writes neither for a frozen weight. grad_gemm = empty( - operands.gemm_both if grad_gemm_columnwise else operands.gemm_rowwise, 2 * ffn + operands.gemm_both if fc1_ctx.weight_requires_grad else operands.gemm_rowwise, 2 * ffn ) act_col = empty(operands.gemm_columnwise, ffn) if fc2_ctx.weight_requires_grad else None grad_recv_weights = torch.empty(rows, dtype=torch.float32, device=device) @@ -703,27 +689,6 @@ class _MxFp8WeightOperands(NamedTuple): columnwise: Optional[MXFP8TensorStorage] = None -def _gemm_interface_reason(mxfp8: bool = False) -> Optional[str]: - """Why the EP grouped GEMM kernel tree does not match Transformer Engine, or ``None``.""" - try: - from ....common.CuTeDSL.ep_gemm._loader import ( # pylint: disable=import-outside-toplevel - gemm_interface_reason, - ) - except ImportError as err: - return f"the CuTeDSL EP grouped GEMMs cannot be imported: {err}" - # PyTorch passes int64 expert counts and offsets. - return gemm_interface_reason(mxfp8, int64_offsets=True) - - -def _dglu_skips_column_outputs() -> bool: - """Whether the cuDNN FE MXFP8 dGLU can leave out the columnwise grad_gemm_out.""" - from ....common.CuTeDSL.ep_gemm._loader import ( # pylint: disable=import-outside-toplevel - dglu_skips_column_outputs, - ) - - return dglu_skips_column_outputs() - - def _mxfp8_quantizer(*, rowwise: bool, columnwise: bool, swizzled: bool) -> MXFP8Quantizer: """E4M3 quantizer of the MXFP8 EP transport and GEMM operands; it makes internal storages.""" quantizer = MXFP8Quantizer(DType.kFloat8E4M3, rowwise=rowwise, columnwise=columnwise) @@ -844,9 +809,9 @@ def _moe_overlap_unsupported_reason( ) -> Optional[str]: """Why a ``Sequential`` of ``MoeDispatch``, ``GroupedLinear``, ``ScaledSwiGLU``, ``GroupedLinear`` and ``MoeCombine`` built with these settings does not run as one - ``FusedMoE``, or ``None`` when it does. The reason names an unsupported setting or the - grouped GEMM backend failing to load on this device. It only queries the device and the - static settings; those that can change between calls are checked when the op runs. + ``FusedMoE``, or ``None`` when it does. The reason names an unsupported setting. It only + queries the device and the static settings; those that can change between calls are checked + when the op runs. Parameters ---------- @@ -872,16 +837,9 @@ def _moe_overlap_unsupported_reason( They must be MXFP8 and need the ``MXFP8BlockScaling`` recipe. """ if not FusedMoE.is_supported(): - reason = ( - "needs SM 10.0, 10.3 or 10.7, NVTE_ENABLE_CUTEDSL_BACKEND=1, NVTE_MOE_OVERLAP=1 and" - " the BF16 cuDNN grouped GEMM kernels" - ) - mismatch = _gemm_interface_reason() if _moe_overlap_available() else None - return f"{reason}: {mismatch}" if mismatch else reason + return "needs SM 10.0, 10.3 or 10.7, NVTE_ENABLE_CUTEDSL_BACKEND=1 and NVTE_MOE_OVERLAP=1" if config.payload_dtype is not torch.bfloat16: return "needs a BF16 payload" - # TODO(phuonguyen): the cuDNN FE grouped GEMMs have no tail-tile kernels, so every expert must - # pad to a full 256-row tile. Accept 64/128 alignment again once tail-tiles land. if config.alignment != _TILE: return f"the EP alignment must be {_TILE}" if config.zero_copy: @@ -889,11 +847,6 @@ def _moe_overlap_unsupported_reason( if recipe is not None: if not isinstance(recipe, MXFP8BlockScaling): return "quantized GEMMs other than MXFP8BlockScaling are not supported" - if not GroupedMLP_CuTeGEMMGLU.is_supported(): - return "MXFP8 needs the MXFP8 cuDNN grouped GEMM kernels" - mismatch = _gemm_interface_reason(mxfp8=True) - if mismatch: - return mismatch if recipe.fp8_format != Format.E4M3 or recipe.backward_override is not None: return "MXFP8 needs fp8_format E4M3 and no backward_override" # MXFP8 FusedMoE quantizes the EP transport itself, so the transport recipes need not be From 412786352de011c0a3f3f3d3ea3a96398c707ca6 Mon Sep 17 00:00:00 2001 From: Phuong Nguyen Date: Wed, 2 Dec 2026 16:10:35 -0800 Subject: [PATCH 31/67] [Common] Run the EP combine backward MXFP8 requant after the dGLU GEMM and its tail so it reads delivered rows Signed-off-by: Phuong Nguyen --- .../common/cast/mxfp8/requantize_mxfp8_cutedsl.cuh | 8 +++++--- transformer_engine/common/ep/ep_gemm_api.cpp | 13 +++++++------ 2 files changed, 12 insertions(+), 9 deletions(-) diff --git a/transformer_engine/common/cast/mxfp8/requantize_mxfp8_cutedsl.cuh b/transformer_engine/common/cast/mxfp8/requantize_mxfp8_cutedsl.cuh index f1f649ed833..3493c187088 100644 --- a/transformer_engine/common/cast/mxfp8/requantize_mxfp8_cutedsl.cuh +++ b/transformer_engine/common/cast/mxfp8/requantize_mxfp8_cutedsl.cuh @@ -73,7 +73,8 @@ struct MXFP8RequantConfig { }; inline bool mxfp8_requantize_cutedsl(const GroupedTensor &input, GroupedTensor *output, - Tensor *dequantized, cudaStream_t stream, bool pdl = false) { + Tensor *dequantized, cudaStream_t stream, bool pdl = false, + bool force_warp_tile = false) { using namespace tvm_ffi_bridge; if (!TVMFFICentral::getInstance().get_cutedsl_backend_enabled() || !input.all_same_last_dim()) return false; @@ -82,8 +83,9 @@ inline bool mxfp8_requantize_cutedsl(const GroupedTensor &input, GroupedTensor * const size_t groups = input.num_tensors; const bool return_dequantized = dequantized != nullptr && dequantized->data.dptr != nullptr; // Varying first dims without BF16 output use the warp-tile kernel, which loads scales as words. - // PDL is a warp-tile-only overlap, so pdl forces it regardless of whether the groups match. - const bool warp_tile = pdl || (!input.all_same_shape() && !return_dequantized); + // PDL is a warp-tile-only overlap, so pdl forces it regardless of whether the groups match; + // force_warp_tile selects it for expert slabs given by element offsets without PDL. + const bool warp_tile = pdl || force_warp_tile || (!input.all_same_shape() && !return_dequantized); if (pdl && return_dequantized) return false; if (rows == 0 || hidden == 0 || rows % 128 || hidden % 128 || (!warp_tile && hidden >= 512 && hidden % 512)) diff --git a/transformer_engine/common/ep/ep_gemm_api.cpp b/transformer_engine/common/ep/ep_gemm_api.cpp index beaa8576e45..d079358d837 100644 --- a/transformer_engine/common/ep/ep_gemm_api.cpp +++ b/transformer_engine/common/ep/ep_gemm_api.cpp @@ -459,7 +459,8 @@ void launch_requant(NVTETensor t, const GemmScratch& scratch, size_t rows, size_ output.set_with_gemm_swizzled_scales(true); GroupedTensor* const in = convertNVTEGroupedTensorCheck(input.data()); GroupedTensor* const out = convertNVTEGroupedTensorCheck(output.data()); - const bool ok = cutedsl_backend::mxfp8_requantize_cutedsl(*in, out, nullptr, stream, pdl); + const bool ok = cutedsl_backend::mxfp8_requantize_cutedsl(*in, out, nullptr, stream, pdl, + /*force_warp_tile=*/true); NVTE_CHECK(ok, "the EP MXFP8 requant is not available: needs NVTE_ENABLE_CUTEDSL_BACKEND=1, " "NVTE_MOE_OVERLAP=1 and SM 10.0, 10.3 or 10.7"); @@ -905,11 +906,6 @@ void nvte_ep_combine_gemm_bwd( auto norm_const = wrap_raw(scratch.alpha, kNVTEFloat32, 1); gemm(&a, &b, &sfb, &sfa, &c, &d, &d_col, &sfd_row, &sfd_col, &h, &sfh_col, &dprob, &row_ends, &alpha, &prob, &norm_const, &ws, static_cast(stream)); - // The columnwise grad_expert_out, a dependent of the GEMM. It runs on the SMs the reverse - // dispatch frees, so its rows are already delivered and it needs no per-tile readiness signal. - if (requant) { - launch_requant(grad_expert_out, scratch, rows, hidden, num_experts, /*pdl=*/true, stream); - } // Its tail on the SMs the reverse dispatch frees takes the tiles the GEMM has not claimed. const int tail_clusters = ctx.all_clusters - ctx.num_clusters; if (tail_clusters > 0) { @@ -917,6 +913,11 @@ void nvte_ep_combine_gemm_bwd( tail(&a, &b, &sfb, &sfa, &c, &d, &d_col, &sfd_row, &sfd_col, &h, &sfh_col, &dprob, &row_ends, &alpha, &prob, &norm_const, &ws, static_cast(stream)); } + // The columnwise grad_expert_out, on every SM once the GEMM and its tail complete: only then + // are all rows delivered, and it takes no per-tile readiness signal. + if (requant) { + launch_requant(grad_expert_out, scratch, rows, hidden, num_experts, /*pdl=*/false, stream); + } // The weight gradient once the GEMM and the requant complete: its base, which then lets its // tail in. An added or FP32 one runs on every SM: its kernel launches a helper kernel in front, // so a tail would wait for the base to complete. From 83924e3330fc6f08f2b79c3de5c5ada382cc716b Mon Sep 17 00:00:00 2001 From: Phuong Nguyen Date: Wed, 2 Dec 2026 16:53:24 -0800 Subject: [PATCH 32/67] [Common] Drop the PDL path of the grouped MXFP8 requant now that both EP callers run it on every SM Signed-off-by: Phuong Nguyen --- .../CuTeDSL/cast/mxfp8/requantize_mxfp8.py | 31 ++++--------------- .../cast/mxfp8/requantize_mxfp8_cutedsl.cuh | 16 ++++------ transformer_engine/common/ep/ep_gemm_api.cpp | 17 +++++----- 3 files changed, 20 insertions(+), 44 deletions(-) diff --git a/transformer_engine/common/CuTeDSL/cast/mxfp8/requantize_mxfp8.py b/transformer_engine/common/CuTeDSL/cast/mxfp8/requantize_mxfp8.py index ce6221fb7c0..935e4a5c890 100644 --- a/transformer_engine/common/CuTeDSL/cast/mxfp8/requantize_mxfp8.py +++ b/transformer_engine/common/CuTeDSL/cast/mxfp8/requantize_mxfp8.py @@ -1019,9 +1019,8 @@ class GroupedRequantizeWarpTile: BlocksPerTile = 4 def __init__( - self, hidden, *, input_dtype=cutlass.Float8E4M3FN, swizzled=True, rowwise_output=True, - pdl=False, - ): # fmt: skip + self, hidden, *, input_dtype=cutlass.Float8E4M3FN, swizzled=True, rowwise_output=True + ): if hidden <= 0 or hidden % self.TILE: raise ValueError("Grouped MXFP8 requantization requires a 128-aligned hidden size") if input_dtype not in (cutlass.Float8E4M3FN, cutlass.Float8E5M2): @@ -1031,9 +1030,6 @@ def __init__( self.use_scaled_cvt = _supports_scaled_bf16_conversion() self.swizzled = bool(swizzled) self.rowwise_output = bool(rowwise_output and swizzled) - # Run as a programmatic dependent (PDL) so it can overlap a producing kernel on the SMs - # that kernel frees, instead of waiting for it to finish. - self.pdl = bool(pdl) @cute.jit def __call__( @@ -1054,7 +1050,6 @@ def __call__( # At most 96 registers: ten CTAs per SM keep enough loads in flight. min_blocks_per_mp=10, stream=stream, - use_pdl=self.pdl, ) @cute.kernel @@ -1072,8 +1067,6 @@ def kernel( tiles_x = cutlass.const_expr(cols // self.TILE) sf_stride = cutlass.const_expr(cols // 32) rows_per_lane = cutlass.const_expr(self.RowsPerLane) - if cutlass.const_expr(self.pdl): - cute.arch.griddepcontrol_launch_dependents() tid, _, _ = cute.arch.thread_idx() bid, _, _ = cute.arch.block_idx() lane = tid % 32 @@ -1241,14 +1234,10 @@ def kernel( ), cute.make_layout((1,)), )[0] = Uint8(col_scales[pair] >> (block * 8)) - if cutlass.const_expr(self.pdl): - # The grid completes after the producing kernel: CTA 0 waits for it at exit. - if bid == 0: - cute.arch.griddepcontrol_wait() @functools.lru_cache(maxsize=None) -def _compile_warp_tile_requantization(input_dtype, hidden, swizzled, rowwise_output, pdl): +def _compile_warp_tile_requantization(input_dtype, hidden, swizzled, rowwise_output): """Compile the warp-tile kernel once for every row and group count.""" rows = cute.sym_int32(divisibility=128) scales = cute.sym_int32() @@ -1264,11 +1253,7 @@ def tensor(element_type, shape): compiled = cute.compile( GroupedRequantizeWarpTile( - hidden, - input_dtype=input_dtype, - swizzled=swizzled, - rowwise_output=rowwise_output, - pdl=pdl, + hidden, input_dtype=input_dtype, swizzled=swizzled, rowwise_output=rowwise_output ), tensor(input_dtype, (rows, hidden)), tensor(cutlass.Float8E8M0FNU, (rows, hidden // 32)), @@ -1295,10 +1280,8 @@ def get_mxfp8_requantization_function( rowwise_output, return_dequantized, sm_count, - pdl=False, ): - """Compile/register one common C API specialization, or request CUDA fallback. - ``pdl`` runs the warp-tile kernel as a programmatic dependent (EP overlap).""" + """Compile/register one common C API specialization, or request CUDA fallback.""" if tvm_ffi.get_global_func(fn_name, allow_missing=True) is not None: return True try: @@ -1307,13 +1290,11 @@ def get_mxfp8_requantization_function( tvm_ffi.register_global_func( fn_name, _compile_warp_tile_requantization( - input_dtype, hidden, bool(swizzled), bool(rowwise_output), bool(pdl) + input_dtype, hidden, bool(swizzled), bool(rowwise_output) ), override=True, ) return True - if pdl: - raise ValueError("PDL grouped MXFP8 requantization is not supported for now") kernel = GroupedRequantize( hidden, groups, diff --git a/transformer_engine/common/cast/mxfp8/requantize_mxfp8_cutedsl.cuh b/transformer_engine/common/cast/mxfp8/requantize_mxfp8_cutedsl.cuh index 3493c187088..ff9807da7d8 100644 --- a/transformer_engine/common/cast/mxfp8/requantize_mxfp8_cutedsl.cuh +++ b/transformer_engine/common/cast/mxfp8/requantize_mxfp8_cutedsl.cuh @@ -23,7 +23,6 @@ struct MXFP8RequantConfig { DType dtype; size_t rows, hidden, groups, uniform_rows; bool swizzled, rowwise_output, return_dequantized; - bool pdl = false; // run the warp-tile kernel as a programmatic dependent int sm_arch = cuda::sm_arch(); int sm_count = cuda::sm_count(); @@ -32,7 +31,7 @@ struct MXFP8RequantConfig { "_" + std::to_string(hidden) + "_" + std::to_string(groups) + "_" + std::to_string(uniform_rows) + "_" + std::to_string(swizzled) + "_" + std::to_string(rowwise_output) + "_" + std::to_string(return_dequantized) + "_" + - std::to_string(pdl) + "_" + std::to_string(sm_arch) + "_" + std::to_string(sm_count); + std::to_string(sm_arch) + "_" + std::to_string(sm_count); } bool retrieve_func_from_python(const std::string &name) const { @@ -41,7 +40,7 @@ struct MXFP8RequantConfig { return (*entrypoint)(tvm::ffi::String(name), tvm::ffi::String(to_string(dtype)), static_cast(rows), static_cast(hidden), static_cast(groups), static_cast(uniform_rows), swizzled, - rowwise_output, return_dequantized, sm_count, pdl) + rowwise_output, return_dequantized, sm_count) .try_cast() .value_or(false); } @@ -73,7 +72,7 @@ struct MXFP8RequantConfig { }; inline bool mxfp8_requantize_cutedsl(const GroupedTensor &input, GroupedTensor *output, - Tensor *dequantized, cudaStream_t stream, bool pdl = false, + Tensor *dequantized, cudaStream_t stream, bool force_warp_tile = false) { using namespace tvm_ffi_bridge; if (!TVMFFICentral::getInstance().get_cutedsl_backend_enabled() || !input.all_same_last_dim()) @@ -83,10 +82,8 @@ inline bool mxfp8_requantize_cutedsl(const GroupedTensor &input, GroupedTensor * const size_t groups = input.num_tensors; const bool return_dequantized = dequantized != nullptr && dequantized->data.dptr != nullptr; // Varying first dims without BF16 output use the warp-tile kernel, which loads scales as words. - // PDL is a warp-tile-only overlap, so pdl forces it regardless of whether the groups match; - // force_warp_tile selects it for expert slabs given by element offsets without PDL. - const bool warp_tile = pdl || force_warp_tile || (!input.all_same_shape() && !return_dequantized); - if (pdl && return_dequantized) return false; + // force_warp_tile selects it for expert slabs given by element offsets. + const bool warp_tile = force_warp_tile || (!input.all_same_shape() && !return_dequantized); if (rows == 0 || hidden == 0 || rows % 128 || hidden % 128 || (!warp_tile && hidden >= 512 && hidden % 512)) return false; @@ -112,8 +109,7 @@ inline bool mxfp8_requantize_cutedsl(const GroupedTensor &input, GroupedTensor * (!warp_tile && input.all_same_shape()) ? rows / groups : 0, output->with_gemm_swizzled_scales, rowwise, - return_dequantized, - pdl}; + return_dequantized}; auto kernel = config.get_kernel(); if (!kernel) return false; diff --git a/transformer_engine/common/ep/ep_gemm_api.cpp b/transformer_engine/common/ep/ep_gemm_api.cpp index d079358d837..05c96a203c6 100644 --- a/transformer_engine/common/ep/ep_gemm_api.cpp +++ b/transformer_engine/common/ep/ep_gemm_api.cpp @@ -434,12 +434,11 @@ void launch_wgrad(const Wgrad& wgrad, const GemmScratch& scratch, int num_cluste } // The columnwise MXFP8 copy of t's received rows, requantized from its rowwise data and compact -// scales into GEMM-swizzled columnwise scales per expert slab. The shared grouped MXFP8 requant -// With pdl it runs as a programmatic dependent that overlaps the producing GEMM; without it the -// kernel waits for the preceding one on the stream. The expert slabs are given by the element -// offsets reset_workspace writes from the expert layout. +// scales into GEMM-swizzled columnwise scales per expert slab. It runs after the preceding kernel +// on the stream, on every SM. The expert slabs are given by the element offsets reset_workspace +// writes from the expert layout. void launch_requant(NVTETensor t, const GemmScratch& scratch, size_t rows, size_t cols, - size_t num_experts, bool pdl, cudaStream_t stream) { + size_t num_experts, cudaStream_t stream) { using namespace transformer_engine; const NVTEBasicTensor row_data{nvte_tensor_data(t), nvte_tensor_type(t), nvte_tensor_shape(t)}; const NVTEBasicTensor row_sf = nvte_get_tensor_param(t, kNVTERowwiseScaleInv); @@ -459,7 +458,7 @@ void launch_requant(NVTETensor t, const GemmScratch& scratch, size_t rows, size_ output.set_with_gemm_swizzled_scales(true); GroupedTensor* const in = convertNVTEGroupedTensorCheck(input.data()); GroupedTensor* const out = convertNVTEGroupedTensorCheck(output.data()); - const bool ok = cutedsl_backend::mxfp8_requantize_cutedsl(*in, out, nullptr, stream, pdl, + const bool ok = cutedsl_backend::mxfp8_requantize_cutedsl(*in, out, nullptr, stream, /*force_warp_tile=*/true); NVTE_CHECK(ok, "the EP MXFP8 requant is not available: needs NVTE_ENABLE_CUTEDSL_BACKEND=1, " @@ -916,7 +915,7 @@ void nvte_ep_combine_gemm_bwd( // The columnwise grad_expert_out, on every SM once the GEMM and its tail complete: only then // are all rows delivered, and it takes no per-tile readiness signal. if (requant) { - launch_requant(grad_expert_out, scratch, rows, hidden, num_experts, /*pdl=*/false, stream); + launch_requant(grad_expert_out, scratch, rows, hidden, num_experts, stream); } // The weight gradient once the GEMM and the requant complete: its base, which then lets its // tail in. An added or FP32 one runs on every SM: its kernel launches a helper kernel in front, @@ -1012,9 +1011,9 @@ void nvte_ep_dispatch_gemm_bwd(NVTETensor handle_mem, const NVTETensor grad_gemm } ep::reset_workspace(scratch.reset, stream); // The columnwise wgrad_input, before the GEMM. It reads the resident dispatched tokens, so it - // overlaps as a programmatic dependent without a readiness signal. + // needs no readiness signal. if (requant) { - launch_requant(wgrad_input, scratch, rows, hidden, num_experts, /*pdl=*/true, stream); + launch_requant(wgrad_input, scratch, rows, hidden, num_experts, stream); } // The GEMM fills the flags; the dispatch backward is its programmatic dependent. From d2199cebaf9c861208eb3d316a1fc09407551bd2 Mon Sep 17 00:00:00 2001 From: Phuong Nguyen Date: Wed, 2 Dec 2026 17:24:11 -0800 Subject: [PATCH 33/67] [Common] Remove a detached comment above the EP GEMM signal word setup Signed-off-by: Phuong Nguyen --- transformer_engine/common/ep/ep_gemm_api.cpp | 3 --- 1 file changed, 3 deletions(-) diff --git a/transformer_engine/common/ep/ep_gemm_api.cpp b/transformer_engine/common/ep/ep_gemm_api.cpp index 05c96a203c6..a2fb45b628d 100644 --- a/transformer_engine/common/ep/ep_gemm_api.cpp +++ b/transformer_engine/common/ep/ep_gemm_api.cpp @@ -240,9 +240,6 @@ std::pair workspace_span(const NVTETensor workspace) { return {static_cast(ptr), nvte_tensor_numel(workspace)}; } -// Stage a GemmScratch's reset words once the GEMM's WorkspaceLayout is known: the readiness flags, -// scheduler state and layout entries each launch reinitializes. - // Words of a GEMM that waits on the dispatch tile flags: its tile counter, flags and scheduler // state. void set_signal_words(GemmScratch& scratch, const ep::WorkspaceLayout& layout, size_t slots) { From 614089518e002b21d5c6ebfbea810a88d17b7963 Mon Sep 17 00:00:00 2001 From: Phuong Nguyen Date: Wed, 2 Dec 2026 17:42:16 -0800 Subject: [PATCH 34/67] [Common] Pass the layer config by reference from the EP overlap calls to the backend Signed-off-by: Phuong Nguyen --- transformer_engine/common/ep/ep_gemm_api.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/transformer_engine/common/ep/ep_gemm_api.cpp b/transformer_engine/common/ep/ep_gemm_api.cpp index a2fb45b628d..05134a7b20e 100644 --- a/transformer_engine/common/ep/ep_gemm_api.cpp +++ b/transformer_engine/common/ep/ep_gemm_api.cpp @@ -669,7 +669,7 @@ void nvte_ep_dispatch_gemm_fwd(NVTETensor handle_mem, const NVTETensor topk_idx, ep::reset_workspace(scratch.reset, stream); ctx.backend.dispatch(handle_mem, topk_idx, tokens, tokens_win, topk_weights, no_window, recv_tokens, no_window, recv_topk_weights, no_window, &dispatch_signal, - &ctx.layer_cfg, stream); + ctx.layer_cfg, stream); } // The GEMM is a programmatic dependent of the dispatch: tiles start as their flags are set. The @@ -776,7 +776,7 @@ void nvte_ep_combine_gemm_fwd(NVTETensor handle_mem, const NVTETensor gemm_in, TensorWrapper signal(scratch.base + layout.signal, std::vector{DIVUP(n, n_chunk)}, DType::kInt32); const ep::EpSignal combine_signal{signal.data(), n_chunk}; - ctx.backend.combine(handle_mem, expert_out, no_window, result, &combine_signal, &ctx.layer_cfg, + ctx.backend.combine(handle_mem, expert_out, no_window, result, &combine_signal, ctx.layer_cfg, stream); } @@ -872,7 +872,7 @@ void nvte_ep_combine_gemm_bwd( const ep::EpSignal dispatch_signal{signal.data(), ctx.signal_unit_tokens()}; NVTECommWindow no_window{}; ctx.backend.combine_bwd(handle_mem, grad_result, grad_result_win, grad_expert_out, no_window, - &dispatch_signal, &ctx.layer_cfg, stream); + &dispatch_signal, ctx.layer_cfg, stream); // FC2 data gradient with the SwiGLU backward in its epilogue. auto a = wrap_rowwise(grad_expert_out, true); @@ -1042,7 +1042,7 @@ void nvte_ep_dispatch_gemm_bwd(NVTETensor handle_mem, const NVTETensor grad_gemm const ep::EpSignal combine_signal{signal.data(), chunk}; ctx.backend.dispatch_bwd(handle_mem, grad_recv_tokens, no_window, grad_recv_topk_weights, no_window, grad_tokens, grad_topk_weights, &combine_signal, - &ctx.layer_cfg, stream); + ctx.layer_cfg, stream); } } // extern "C" From 52829bd5c6c8d33ea9d99bf8d62b3d785b268bbb Mon Sep 17 00:00:00 2001 From: Phuong Nguyen Date: Wed, 2 Dec 2026 17:48:06 -0800 Subject: [PATCH 35/67] [Common] Require the 256 alignment in the EP overlap ops and drop the unused 64/128 alignment test paths Signed-off-by: Phuong Nguyen --- tests/pytorch/distributed/run_ep.py | 39 ++++++------------- .../cast/mxfp8/requantize_mxfp8_cutedsl.cuh | 3 +- transformer_engine/common/ep/ep_gemm_api.cpp | 4 +- .../include/transformer_engine/ep_gemm.h | 3 +- 4 files changed, 17 insertions(+), 32 deletions(-) diff --git a/tests/pytorch/distributed/run_ep.py b/tests/pytorch/distributed/run_ep.py index 4fc948ba14f..bc8b9b8bb9f 100644 --- a/tests/pytorch/distributed/run_ep.py +++ b/tests/pytorch/distributed/run_ep.py @@ -51,18 +51,16 @@ if not OVERLAP: # The other passes keep the MoE ops unfused, which the fuser rejects while the overlap is on. os.environ.pop("NVTE_MOE_OVERLAP", None) -# Per-expert alignment of the overlap tests: 256, 128 or 64 (BF16 only; MXFP8 cases skip). -OVERLAP_ALIGNMENT = int(os.environ.get("NVTE_EP_OVERLAP_ALIGNMENT", "256")) -# Below alignment 256 the unfused ops do not fuse into the grouped MLP, so single results of the -# fused op may round to other values than theirs. -UNFUSED_MLP_REFERENCE = OVERLAP_ALIGNMENT % 256 != 0 +# Per-expert alignment of the overlap tests: the overlap GEMMs take 256 only. +OVERLAP_ALIGNMENT = 256 # Must come after the transformer_engine import so libtransformer_engine.so is loaded. import transformer_engine_torch as tex # noqa: F401 # SM 10.7 has no BF16 grouped MLP fusion, so there the BF16 unfused ops never fuse into it. -UNFUSED_BF16_MLP_REFERENCE = UNFUSED_MLP_REFERENCE or ( - torch.cuda.is_available() and torch.cuda.get_device_capability() == (10, 7) +UNFUSED_BF16_MLP_REFERENCE = torch.cuda.is_available() and torch.cuda.get_device_capability() == ( + 10, + 7, ) NUM_LOCAL_EXPERTS = 2 @@ -116,18 +114,9 @@ def _overlap_test(fn): return fn -def _mxfp8_overlap_min_alignment() -> int: - """Smallest expert alignment of FusedMoE under MXFP8: SM 10.7 has no MXFP8 tail tiles.""" - return 256 if torch.cuda.get_device_capability() == (10, 7) else 128 - - def _mxfp8_overlap() -> bool: - """Whether the overlap tests run their MXFP8 cases: shapes and alignment FusedMoE takes.""" - return ( - HIDDEN_DIM % 512 == 0 - and TOKENS_PER_RANK % 32 == 0 - and OVERLAP_ALIGNMENT >= _mxfp8_overlap_min_alignment() - ) + """Whether the overlap tests run their MXFP8 cases: shapes FusedMoE takes.""" + return HIDDEN_DIM % 512 == 0 and TOKENS_PER_RANK % 32 == 0 class _StageToSymm(torch.autograd.Function): @@ -415,8 +404,6 @@ def _require_mxfp8_shapes(self): "MXFP8 needs HIDDEN_DIM % 512 == 0 and TOKENS_PER_RANK % 32 == 0 " "(set NVTE_EP_HIDDEN_DIM / NVTE_EP_TOKENS_PER_RANK)" ) - if OVERLAP and OVERLAP_ALIGNMENT < _mxfp8_overlap_min_alignment(): - self.skipTest("FusedMoE runs MXFP8 with alignment 128 or 256 (256 on SM 10.7)") def _capture(self, step): """Warm up ``step`` on a side stream then capture it into a CUDA graph. Returns @@ -2065,21 +2052,19 @@ def pack(tensor): # round the FC2 dgrad and the SwiGLU backward output to BF16 before quantizing them, so # outputs and weight gradients may differ by up to the E4M3 epsilon. norm_rtol = 2e-2 if recipe is None else 1 / 32 - unfused_reference = UNFUSED_BF16_MLP_REFERENCE if recipe is None else UNFUSED_MLP_REFERENCE - outputs_in_norm = unfused_reference or params_to_bf16 - outputs_rtol = 1 / 16 if recipe is not None and unfused_reference else norm_rtol + outputs_in_norm = (recipe is None and UNFUSED_BF16_MLP_REFERENCE) or params_to_bf16 if not input_grad: self.assertTrue(all(g is None for g in out[1:3] + ref[1:3])) for got, want in zip(out[: 3 if input_grad else 1], ref[:3]): if outputs_in_norm: - _assert_close_in_norm(got, want, rtol=outputs_rtol) + _assert_close_in_norm(got, want, rtol=norm_rtol) else: torch.testing.assert_close(got, want, rtol=2e-2, atol=2e-2) for g, g_ref in zip(out[3], ref[3]): if recipe is None and not (UNFUSED_BF16_MLP_REFERENCE or params_to_bf16): torch.testing.assert_close(g, g_ref, rtol=2e-2, atol=2e-2) else: - _assert_close_in_norm(g, g_ref, rtol=outputs_rtol) + _assert_close_in_norm(g, g_ref, rtol=norm_rtol) @_eager_test_include @_mxfp8_align_test @@ -2519,8 +2504,8 @@ def backward(model, x, topk_w, y, grad): xb, wb, yb = forward(model_b, call_b) inter_b = backward(model_b, xb, wb, yb, call_b[3]) inter_a = backward(model_a, xa, wa, ya, call_a[3]) - self._assert_moe_close(inter_a, alone_a, UNFUSED_MLP_REFERENCE, outputs_in_norm=False) - self._assert_moe_close(inter_b, alone_b, UNFUSED_MLP_REFERENCE, outputs_in_norm=False) + self._assert_moe_close(inter_a, alone_a, False, outputs_in_norm=False) + self._assert_moe_close(inter_b, alone_b, False, outputs_in_norm=False) # Autograd diff --git a/transformer_engine/common/cast/mxfp8/requantize_mxfp8_cutedsl.cuh b/transformer_engine/common/cast/mxfp8/requantize_mxfp8_cutedsl.cuh index ff9807da7d8..adb0ae4b011 100644 --- a/transformer_engine/common/cast/mxfp8/requantize_mxfp8_cutedsl.cuh +++ b/transformer_engine/common/cast/mxfp8/requantize_mxfp8_cutedsl.cuh @@ -82,7 +82,8 @@ inline bool mxfp8_requantize_cutedsl(const GroupedTensor &input, GroupedTensor * const size_t groups = input.num_tensors; const bool return_dequantized = dequantized != nullptr && dequantized->data.dptr != nullptr; // Varying first dims without BF16 output use the warp-tile kernel, which loads scales as words. - // force_warp_tile selects it for expert slabs given by element offsets. + // force_warp_tile selects it for unequal expert slabs given by element offsets, which the + // uniform-slab kernel does not take. const bool warp_tile = force_warp_tile || (!input.all_same_shape() && !return_dequantized); if (rows == 0 || hidden == 0 || rows % 128 || hidden % 128 || (!warp_tile && hidden >= 512 && hidden % 512)) diff --git a/transformer_engine/common/ep/ep_gemm_api.cpp b/transformer_engine/common/ep/ep_gemm_api.cpp index 05134a7b20e..b80cdf8c8a9 100644 --- a/transformer_engine/common/ep/ep_gemm_api.cpp +++ b/transformer_engine/common/ep/ep_gemm_api.cpp @@ -93,8 +93,8 @@ struct EpGemmContext { EpGemmContext make_context(const NVTEEpLayerConfig* layer_cfg, int NVTEEpSmConfig::*comm_sms) { const NVTEEpLayerConfig cfg = ep::normalize_layer_config(layer_cfg); const size_t alignment = cfg.dispatch_output_per_expert_alignment; - NVTE_CHECK(alignment == 64 || alignment == 128 || alignment == kRowsPerTile, - "dispatch_output_per_expert_alignment must be 64, 128 or ", kRowsPerTile); + NVTE_CHECK(alignment == kRowsPerTile, "dispatch_output_per_expert_alignment must be ", + kRowsPerTile, " for the overlapped ops, got ", alignment); ep::EPBackend& backend = ep::EPBackend::get(); const NVTEEpGroupConfig& group = backend.group_config(); NVTE_CHECK(group.num_comm_sms > 0, "the overlapped ops need an explicit num_comm_sms"); diff --git a/transformer_engine/common/include/transformer_engine/ep_gemm.h b/transformer_engine/common/include/transformer_engine/ep_gemm.h index bc886cc22d9..9294654e511 100644 --- a/transformer_engine/common/include/transformer_engine/ep_gemm.h +++ b/transformer_engine/common/include/transformer_engine/ep_gemm.h @@ -27,8 +27,7 @@ * * Requirements (all calls): * - SM 10.0, 10.3 or 10.7; EP within one NVLink domain; num_comm_sms > 0; zero_copy off. - * - dispatch_output_per_expert_alignment: bfloat16 is 64, 128 or 256; MXFP8 is 256, or 128 - * except on SM 10.7. The cuDNN FE kernels run alignment 256 only. + * - dispatch_output_per_expert_alignment is 256. * - NVTE_ENABLE_CUTEDSL_BACKEND=1 and NVTE_MOE_OVERLAP=1. * - MXFP8: hidden_dim a multiple of 512, ffn_dim a multiple of 256. * - First call per shape compiles its GEMM: run it at warmup, outside CUDA graph capture. From 97279f28d85354391ca0b8474cee77f3511f1a6a Mon Sep 17 00:00:00 2001 From: Phuong Nguyen Date: Wed, 2 Dec 2026 17:48:16 -0800 Subject: [PATCH 36/67] [PyTorch] Keep the SM 10.7 reference flag in the EP tests on one line Signed-off-by: Phuong Nguyen --- tests/pytorch/distributed/run_ep.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/pytorch/distributed/run_ep.py b/tests/pytorch/distributed/run_ep.py index bc8b9b8bb9f..e2cf206686e 100644 --- a/tests/pytorch/distributed/run_ep.py +++ b/tests/pytorch/distributed/run_ep.py @@ -58,9 +58,9 @@ import transformer_engine_torch as tex # noqa: F401 # SM 10.7 has no BF16 grouped MLP fusion, so there the BF16 unfused ops never fuse into it. -UNFUSED_BF16_MLP_REFERENCE = torch.cuda.is_available() and torch.cuda.get_device_capability() == ( - 10, - 7, +_SM107 = (10, 7) +UNFUSED_BF16_MLP_REFERENCE = torch.cuda.is_available() and ( + torch.cuda.get_device_capability() == _SM107 ) NUM_LOCAL_EXPERTS = 2 From ba08c29cc0a92f2ca7565d031fe170f65cee25e8 Mon Sep 17 00:00:00 2001 From: Phuong Nguyen Date: Wed, 2 Dec 2026 21:20:30 -0800 Subject: [PATCH 37/67] [Common] Forward TVMFFIBacktrace to libtvm_ffi with an empty fallback Signed-off-by: Phuong Nguyen --- transformer_engine/common/tvm_ffi_bridge.h | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/transformer_engine/common/tvm_ffi_bridge.h b/transformer_engine/common/tvm_ffi_bridge.h index 7470b2b5890..7a6aad34368 100644 --- a/transformer_engine/common/tvm_ffi_bridge.h +++ b/transformer_engine/common/tvm_ffi_bridge.h @@ -341,6 +341,13 @@ class TVMFFICentral { void move_error(TVMFFIObjectHandle *result) const noexcept { move_error_(result); } + // Returns an empty backtrace if libtvm_ffi is not loaded or does not export TVMFFIBacktrace. + const TVMFFIByteArray *backtrace(const char *filename, int lineno, const char *func, + int cross_ffi_boundary) const noexcept { + static const TVMFFIByteArray empty{"", 0}; + return backtrace_ != nullptr ? backtrace_(filename, lineno, func, cross_ffi_boundary) : ∅ + } + // Optionally warn or fail when CuTeDSL kernels are not chosen based on NVTE_REPORT_IF_CUTEDSL_BACKEND_NOT_CHOSEN. template // No-op while the CuTeDSL backend is disabled, since falling back is then expected. @@ -387,6 +394,7 @@ class TVMFFICentral { get_global_ = reinterpret_cast(dlsym(tvm_ffi_handle_, "TVMFFIFunctionGetGlobal")); move_error_ = reinterpret_cast(dlsym(tvm_ffi_handle_, "TVMFFIErrorMoveFromRaised")); + backtrace_ = reinterpret_cast(dlsym(tvm_ffi_handle_, "TVMFFIBacktrace")); if (get_global_ == nullptr || move_error_ == nullptr) { NVTE_WARN( "The CuTeDSL kernel is not chosen because the TVM-FFI library could not be loaded."); @@ -430,9 +438,11 @@ class TVMFFICentral { // These are symbols dynamically loaded from TVM-FFI using GetGlobalFn = decltype(&::TVMFFIFunctionGetGlobal); using MoveErrorFn = decltype(&::TVMFFIErrorMoveFromRaised); + using BacktraceFn = decltype(&::TVMFFIBacktrace); GetGlobalFn get_global_ = nullptr; MoveErrorFn move_error_ = nullptr; + BacktraceFn backtrace_ = nullptr; }; // A utility class that each Config struct can use to cache the registered TVM-FFI functions @@ -507,10 +517,11 @@ extern "C" inline void TVMFFIErrorMoveFromRaised(TVMFFIObjectHandle *result) { transformer_engine::tvm_ffi_bridge::TVMFFICentral::getInstance().move_error(result); } -// TVM-FFI error construction (e.g. in try_cast) references this symbol; backtraces stay empty. -extern "C" inline const TVMFFIByteArray *TVMFFIBacktrace(const char *, int, const char *, int) { - static const TVMFFIByteArray empty{"", 0}; - return ∅ +// TVM-FFI error construction (e.g. in try_cast) references this symbol. +extern "C" inline const TVMFFIByteArray *TVMFFIBacktrace(const char *filename, int lineno, + const char *func, int cross_ffi_boundary) { + return transformer_engine::tvm_ffi_bridge::TVMFFICentral::getInstance().backtrace( + filename, lineno, func, cross_ffi_boundary); } #endif // TRANSFORMER_ENGINE_COMMON_TVM_FFI_BRIDGE_H_ From 363437bfdbc1a368a37762834c22e694913b0a9a Mon Sep 17 00:00:00 2001 From: Phuong Nguyen Date: Wed, 2 Dec 2026 23:16:08 -0800 Subject: [PATCH 38/67] [Common] Keep the offsets operand of the grouped MXFP8 requant for unequal groups when the warp-tile kernel is not forced Signed-off-by: Phuong Nguyen --- .../common/cast/mxfp8/requantize_mxfp8_cutedsl.cuh | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/transformer_engine/common/cast/mxfp8/requantize_mxfp8_cutedsl.cuh b/transformer_engine/common/cast/mxfp8/requantize_mxfp8_cutedsl.cuh index adb0ae4b011..76067707464 100644 --- a/transformer_engine/common/cast/mxfp8/requantize_mxfp8_cutedsl.cuh +++ b/transformer_engine/common/cast/mxfp8/requantize_mxfp8_cutedsl.cuh @@ -92,8 +92,9 @@ inline bool mxfp8_requantize_cutedsl(const GroupedTensor &input, GroupedTensor * // The narrow specializations copy full-width compact scales as 1D bulk data. if (!warp_tile && input.all_same_shape() && (rows % groups || (rows / groups) % 128)) return false; - // The warp-tile kernel reads per-group boundaries from element offsets. - if (warp_tile && + // Kernels for unequal groups read per-group boundaries from element offsets. + const bool needs_offsets = warp_tile || !input.all_same_shape(); + if (needs_offsets && (input.tensor_offsets.dptr == nullptr || input.tensor_offsets.numel() < groups + 1)) { return false; } @@ -122,7 +123,7 @@ inline bool mxfp8_requantize_cutedsl(const GroupedTensor &input, GroupedTensor * DType::kFloat8E8M0); DLTensorWrapper mSrc(src, false, device), mSf(sf, false, device), mDst(dst, false, device), mColSf(col_sf, false, device), mOffsets, mRowSf, mDequantized; - if (warp_tile) { + if (needs_offsets) { const SimpleTensor offsets(input.tensor_offsets.dptr, {groups + 1}, DType::kInt64); mOffsets = DLTensorWrapper(offsets, false, device); } From 46274b6e4263cc9f847f187365982d74a0cad576 Mon Sep 17 00:00:00 2001 From: Phuong Nguyen Date: Wed, 2 Dec 2026 23:16:09 -0800 Subject: [PATCH 39/67] [Common][PyTorch] Validate the EP overlap entry points, take int64 expert offsets only, add the deterministic routing-weight gradient and extend the EP overlap tests and QA Signed-off-by: Phuong Nguyen --- docs/envvars.rst | 15 +- qa/L0_pytorch_unittest/test.sh | 4 + tests/pytorch/distributed/run_ep.py | 198 +++++++++++--- tests/pytorch/distributed/run_test_ep.sh | 37 ++- tests/pytorch/test_ep_gemm.py | 62 +++-- tests/pytorch/test_grouped_mlp.py | 31 +-- tests/pytorch/test_nccl_ep_discovery.py | 73 +++++ .../common/CuTeDSL/ep_gemm/_loader.py | 67 ++--- .../common/CuTeDSL/ep_gemm/combine_gemm.py | 19 +- .../common/CuTeDSL/ep_gemm/dispatch_gemm.py | 66 +++-- .../common/CuTeDSL/ep_gemm/wgrad_gemm.py | 32 +-- transformer_engine/common/ep/ep_gemm_api.cpp | 254 +++++++++++------- transformer_engine/common/ep/ep_gemm_config.h | 40 +-- transformer_engine/common/ep/ep_gemm_utils.h | 32 +-- .../common/ep/ep_overlap_workspace.cu | 37 ++- .../common/ep/ep_overlap_workspace.h | 14 +- .../common/include/transformer_engine/ep.h | 5 + .../include/transformer_engine/ep_gemm.h | 33 ++- .../pytorch/csrc/extensions/ep.cpp | 36 ++- transformer_engine/pytorch/ep.py | 38 ++- .../pytorch/ops/fused/grouped_mlp.py | 33 +-- .../pytorch/ops/fused/moe_overlap.py | 81 +++--- 22 files changed, 790 insertions(+), 417 deletions(-) diff --git a/docs/envvars.rst b/docs/envvars.rst index ba8b2a89dbb..051c1f7f9ab 100644 --- a/docs/envvars.rst +++ b/docs/envvars.rst @@ -167,10 +167,17 @@ General :Default: ``0`` :Description: Set to ``1`` to overlap the NCCL EP dispatch and combine with the expert grouped GEMMs (``ep_gemm.h``, used by the fused - :class:`transformer_engine.pytorch.ops.MoeDispatch` expert MLP). Requires - ``NVTE_ENABLE_CUTEDSL_BACKEND=1`` and the CuTeDSL grouped GEMMs from the cuDNN - frontend. If ``0``, the unfused ops run; if ``1``, a dispatch, grouped MLP and - combine sequence that cannot run fused raises an error. + :class:`transformer_engine.pytorch.ops.MoeDispatch` expert MLP). Requires a + Transformer Engine build with ``NVTE_WITH_CUTEDSL=1``, ``NVTE_ENABLE_CUTEDSL_BACKEND=1``, + an SM 10.0, 10.3 or 10.7 GPU and a cuDNN frontend package whose CuTeDSL grouped + GEMMs take int64 expert offsets. If ``0``, the unfused ops run; if ``1``, a + dispatch, grouped MLP and combine sequence that cannot run fused raises an error. + With ``NVTE_ALLOW_NONDETERMINISTIC_ALGO=0`` or + ``torch.use_deterministic_algorithms(True)``, the fused backward reduces the + routing-weight gradient in a fixed order. This needs a per-token scratch of one + fp32 slot per output tile column in the overlap workspace, and the setting is + fixed when a CUDA graph is captured. The weight gradients are not yet reproducible + bit for bit. .. envvar:: NVTE_GROUPED_TENSOR_HANDLE_POOL_SIZE_MB diff --git a/qa/L0_pytorch_unittest/test.sh b/qa/L0_pytorch_unittest/test.sh index 17bddf39bb8..31ee33dea27 100644 --- a/qa/L0_pytorch_unittest/test.sh +++ b/qa/L0_pytorch_unittest/test.sh @@ -103,6 +103,10 @@ PYTORCH_JIT=0 NVTE_TORCH_COMPILE=0 python3 -m pytest --tb=auto --junitxml=$XML_L PYTORCH_JIT=0 NVTE_TORCH_COMPILE=0 python3 -m pytest --tb=auto --junitxml=$XML_LOG_DIR/pytest_test_ops_grouped_linear_distributed_weight.xml $TE_PATH/tests/pytorch/test_ops_grouped_linear_distributed_weight.py || test_fail "test_ops_grouped_linear_distributed_weight.py" PYTORCH_JIT=0 NVTE_TORCH_COMPILE=0 python3 -m pytest --tb=auto --junitxml=$XML_LOG_DIR/pytest_test_module_grouped_linear_distributed_weight.xml $TE_PATH/tests/pytorch/test_module_grouped_linear_distributed_weight.py || test_fail "test_module_grouped_linear_distributed_weight.py" python3 -m pytest --tb=auto --junitxml=$XML_LOG_DIR/pytest_test_grouped_mlp.xml $TE_PATH/tests/pytorch/test_grouped_mlp.py || test_fail "test_grouped_mlp.py" +python3 -m pytest --tb=auto --junitxml=$XML_LOG_DIR/pytest_test_nccl_ep_discovery.xml $TE_PATH/tests/pytorch/test_nccl_ep_discovery.py || test_fail "test_nccl_ep_discovery.py" +# The EP overlap kernel tests skip the whole module unless NVTE_MOE_OVERLAP=1. +# TODO(phuonguyen): set NVTE_ENABLE_CUTEDSL_BACKEND=1 NVTE_MOE_OVERLAP=1 once TE builds CuTeDSL by default. +python3 -m pytest --tb=auto --junitxml=$XML_LOG_DIR/pytest_test_ep_gemm.xml $TE_PATH/tests/pytorch/test_ep_gemm.py || test_fail "test_ep_gemm.py" if [ "$RET" -ne 0 ]; then echo "Error in the following test cases:$FAILED_CASES" diff --git a/tests/pytorch/distributed/run_ep.py b/tests/pytorch/distributed/run_ep.py index e2cf206686e..5dabdd6a607 100644 --- a/tests/pytorch/distributed/run_ep.py +++ b/tests/pytorch/distributed/run_ep.py @@ -24,6 +24,7 @@ from transformer_engine.pytorch.ep import ( EpBuffer, EpConfig, + EpOverlapConfig, EpSmConfig, ep_bootstrap, ep_finalize, @@ -76,6 +77,20 @@ COMM_SMS = tuple(int(sms) for sms in os.environ.get("NVTE_EP_COMM_SMS", "0,0,0,0").split(",")) if len(COMM_SMS) != 4: raise ValueError(f"NVTE_EP_COMM_SMS needs 4 comma-separated counts, got {COMM_SMS}") +# Overlap tuning of the group (NVTE_EP_OVERLAP_CONFIG=combine_chunk_hidden,push_last_chunk_sms, +# reduce_last_chunk_sms,dispatch_chunk_tokens); unset keeps the ep_bootstrap defaults. +_OVERLAP_CONFIG_ENV = os.environ.get("NVTE_EP_OVERLAP_CONFIG") +OVERLAP_CONFIG = None +if _OVERLAP_CONFIG_ENV: + _chunk_hidden, _push_sms, _reduce_sms, _dispatch_chunk = ( + int(value) for value in _OVERLAP_CONFIG_ENV.split(",") + ) + OVERLAP_CONFIG = EpOverlapConfig( + dispatch_chunk_tokens=_dispatch_chunk, + combine_chunk_hidden=_chunk_hidden, + combine_push_last_chunk_sms=_push_sms, + combine_reduce_last_chunk_sms=_reduce_sms, + ) def _zero_copy_test_include(fn): @@ -302,6 +317,7 @@ def setUpClass(cls): drop_on_overflow=OVERFLOW, max_num_sms=OVERLAP_COMM_SMS if OVERLAP else 0, sm_config=EpSmConfig(*COMM_SMS), + overlap_config=OVERLAP_CONFIG, ) except RuntimeError as err: # A backward count other than the forward one needs NCCL EP backward budgets. @@ -1840,7 +1856,7 @@ def test_moe_overlap_op_mxfp8(self): topk_idx, tokens, w = _make_identity_inputs(self.cfg.rank, self.cfg.ep_size) with te.autocast(recipe=recipe): model(tokens, topk_idx, w, topk_idx) - self.assertTrue(self._moe_overlap_selected(model)) + self._assert_fusion(model, True) @_eager_test_include @_overflow_test_include @@ -2008,8 +2024,7 @@ def pack(tensor): out = run(True) self.assertFalse(ref[4]) self.assertTrue(out[4], "fusion selection") - # The launcher requires this line from every rank of an overlap pass. - print(f"OVERLAP_EXECUTED rank={self.cfg.rank}", flush=True) + self._report_overlap_executed() reason = _moe_overlap_unsupported_reason( config, ffn, params_dtype=torch.bfloat16, glu_interleave_size=32, single_grouped_weight=True, recipe=recipe, @@ -2119,7 +2134,7 @@ def pop_tensor(packed, pop=pop): y = model(x, topk_idx, topk_w, topk_idx) y.backward(grad_out) torch.cuda.synchronize() - self.assertTrue(self._moe_overlap_selected(model)) + self._assert_fusion(model, True) self.assertEqual(bool(saved), offload, "offloaded tensors") for before, after in saved: self.assertTrue(torch.equal(before, after.cpu()), "a saved tensor changed") @@ -2150,6 +2165,17 @@ def _moe_fusion(fused): return contextlib.nullcontext() return mock.patch.object(moe_overlap, "_moe_overlap_available", return_value=False) + def _report_overlap_executed(self): + """Tell the launcher this test ran the fused overlap ops on this rank; an overlap pass + needs a minimum number of such tests on every rank.""" + print(f"OVERLAP_EXECUTED test={self._testMethodName} rank={self.cfg.rank}", flush=True) + + def _assert_fusion(self, model, fused): + """Check that ``model`` ran FusedMoE exactly when ``fused``, and report it when it did.""" + self.assertEqual(bool(self._moe_overlap_selected(model)), fused) + if fused: + self._report_overlap_executed() + @staticmethod def _moe_overlap_selected(model): """The FusedMoE ops of the plan ``model`` ran last.""" @@ -2232,7 +2258,7 @@ def test_moe_overlap_wgrad(self): model = te_ops.Sequential(*ops) outs = [self._moe_call(model, *call) for call in calls] torch.cuda.synchronize() - self.assertEqual(bool(self._moe_overlap_selected(model)), fused) + self._assert_fusion(model, fused) for p in weights: self.assertTrue(p.grad_added_to_main_grad) results.append((outs, [p.main_grad.clone() for p in weights])) @@ -2271,7 +2297,7 @@ def test_moe_overlap_inference(self): model = te_ops.Sequential(*ops) out = model(tokens, topk_idx, w, topk_idx) torch.cuda.synchronize() - self.assertEqual(bool(self._moe_overlap_selected(model)), fused) + self._assert_fusion(model, fused) results.append( ( out, @@ -2313,7 +2339,7 @@ def test_moe_overlap_rank_without_tokens(self): model = te_ops.Sequential(*ops) out = self._moe_call(model, tokens, topk_idx, w, grad) torch.cuda.synchronize() - self.assertEqual(bool(self._moe_overlap_selected(model)), fused) + self._assert_fusion(model, fused) results.append((out, self._param_grads(model))) self._assert_moe_close(results[1], results[0]) has_tokens = self.cfg.rank < 2 @@ -2327,44 +2353,134 @@ def test_moe_overlap_rank_without_tokens(self): @_overflow_test_include @_mxfp8_align_test @_overlap_test - def test_moe_overlap_int32_counts(self): - """With int32 per-expert counts and recv total the fused op matches its int64 run, and - the overlapped dispatch refuses counts and expert offsets of different dtypes.""" - from transformer_engine.pytorch.ops.fused import moe_overlap - + def test_moe_overlap_rejects_int32_counts(self): + """The fused op reads the per-expert counts as int64 and rejects other dtypes.""" self._require_moe_overlap() config = self._overlap_config() buffer = self._make_buffer_from_config(config) ops = self._moe_ops(config, buffer) + buffer.tokens_per_expert = buffer.tokens_per_expert.to(torch.int32) + model = te_ops.Sequential(*ops) tokens, topk_idx, w, grad = self._moe_calls(1)[0] - results = [] - for dtype in (torch.int64, torch.int32): - total = buffer.total_recv_tokens - buffer.tokens_per_expert = buffer.tokens_per_expert.to(dtype) - buffer.total_recv_tokens = torch.empty( - 1, dtype=dtype, device=total.device, pin_memory=total.is_pinned() - ) - for p in ops[1].parameters(): - p.grad = None - for p in ops[3].parameters(): - p.grad = None - model = te_ops.Sequential(*ops) - out = self._moe_call(model, tokens, topk_idx, w, grad) - torch.cuda.synchronize() - self.assertTrue(self._moe_overlap_selected(model)) - results.append((out, self._param_grads(model))) - self._assert_moe_close(results[1], results[0]) + with self.assertRaisesRegex(TypeError, "int64"): + self._moe_call(model, tokens, topk_idx, w, grad) + + def _native_dispatch_gemm_fwd(self, alignment, offsets_dtype=torch.int64): + """tex.ep_dispatch_gemm_fwd on zero operands, as a caller that bypasses FusedMoE.""" + device = self.cfg.device + buffer = self._make_buffer_from_config(self._overlap_config()) + ffn = 256 + rows = buffer.recv_capacity_per_rank or 2 * OVERLAP_ALIGNMENT + return tex.ep_dispatch_gemm_fwd( + buffer.handle_mem, + torch.zeros(TOKENS_PER_RANK, TOP_K, dtype=torch.int64, device=device), + torch.zeros(TOKENS_PER_RANK, HIDDEN_DIM, dtype=torch.bfloat16, device=device), + torch.ones(TOKENS_PER_RANK, TOP_K, dtype=torch.float32, device=device), + torch.zeros( + NUM_LOCAL_EXPERTS, 2 * ffn, HIDDEN_DIM, dtype=torch.bfloat16, device=device + ), + torch.zeros(rows, HIDDEN_DIM, dtype=torch.bfloat16, device=device), + torch.zeros(rows, dtype=torch.float32, device=device), + torch.zeros(NUM_LOCAL_EXPERTS, dtype=torch.int64, device=device), + torch.zeros(NUM_LOCAL_EXPERTS + 1, dtype=offsets_dtype, device=device), + torch.zeros(rows, 2 * ffn, dtype=torch.bfloat16, device=device), + torch.zeros(rows, ffn, dtype=torch.bfloat16, device=device), + TOP_K, + alignment, + ) + + @_mxfp8_align_test + @_overlap_test + def test_moe_overlap_rejects_other_alignment(self): + """The native overlapped dispatch takes the alignment 256 only, for callers that bypass + FusedMoE.""" + self._require_moe_overlap() + with self.assertRaisesRegex(RuntimeError, "must be 256"): + self._native_dispatch_gemm_fwd(128) + + @_mxfp8_align_test + @_overlap_test + def test_moe_overlap_rejects_int32_expert_offsets(self): + """The expert layout the native overlapped GEMMs read is int64.""" + self._require_moe_overlap() + with self.assertRaisesRegex(RuntimeError, "(?i)int64"): + self._native_dispatch_gemm_fwd(OVERLAP_ALIGNMENT, offsets_dtype=torch.int32) - dispatch_gemm_fwd = moe_overlap.tex.ep_dispatch_gemm_fwd + @_mxfp8_align_test + @_overlap_test + def test_moe_overlap_rejects_dispatch_chunk(self): + """A dispatch chunk other than the alignment, set through the group's overlap config, is + rejected when the overlapped op runs. Runs in the pass that sets such a chunk.""" + chunk = OVERLAP_CONFIG.dispatch_chunk_tokens if OVERLAP_CONFIG is not None else 0 + if chunk in (0, OVERLAP_ALIGNMENT): + self.skipTest("needs NVTE_EP_OVERLAP_CONFIG with a dispatch chunk other than 256") + self._require_moe_overlap() + config = self._overlap_config() + model = te_ops.Sequential(*self._moe_ops(config, self._make_buffer_from_config(config))) + tokens, topk_idx, w, _ = self._moe_calls(1)[0] + with self.assertRaisesRegex(RuntimeError, "dispatch_chunk_tokens"): + self._moe_call(model, tokens, topk_idx, w, None) - def int64_offsets(*args, **kwargs): - offsets = args[8] - mixed = torch.zeros(offsets.numel() + 1, dtype=torch.int64, device=offsets.device) - return dispatch_gemm_fwd(*args[:8], mixed[1:], *args[9:], **kwargs) + @staticmethod + @contextlib.contextmanager + def _deterministic_algorithms(): + """Require deterministic algorithms, warning for torch ops that have none.""" + enabled = torch.are_deterministic_algorithms_enabled() + warn_only = torch.is_deterministic_algorithms_warn_only_enabled() + torch.use_deterministic_algorithms(True, warn_only=True) + try: + yield + finally: + torch.use_deterministic_algorithms(enabled, warn_only=warn_only) - with mock.patch.object(moe_overlap.tex, "ep_dispatch_gemm_fwd", side_effect=int64_offsets): - with self.assertRaisesRegex(RuntimeError, "must share a dtype"): - self._moe_call(te_ops.Sequential(*ops), tokens, topk_idx, w, None) + def _assert_bitwise_equal(self, got, ref, path="result"): + """Nested lists of tensors (or None) are equal bit for bit.""" + if isinstance(ref, (list, tuple)): + self.assertEqual(len(got), len(ref), path) + for i, (g, r) in enumerate(zip(got, ref)): + self._assert_bitwise_equal(g, r, f"{path}[{i}]") + elif ref is None: + self.assertIsNone(got, path) + else: + diff = (got.float() - ref.float()).abs().max().item() + self.assertTrue(torch.equal(got, ref), f"{path} differs between runs by {diff}") + + @_mxfp8_align_test + @_overlap_test + def test_moe_overlap_deterministic(self): + """With deterministic algorithms required, two runs of the fused forward and backward agree + bit for bit in the output and the input and routing-weight gradients, and within tolerance + in the weight gradients, and match the run that allows non-deterministic algorithms within + tolerance; in BF16 and, where the overlap tests run MXFP8, under MXFP8 transport.""" + self._require_moe_overlap() + for recipe in [None] + ([MXFP8BlockScaling()] if _mxfp8_overlap() else []): + with self.subTest(recipe=recipe): + self._run_moe_overlap_deterministic(recipe) + + def _run_moe_overlap_deterministic(self, recipe): + if recipe is not None: + self._require_mxfp8_shapes() + config = self._overlap_config(recipe) + model = te_ops.Sequential(*self._moe_ops(config, self._make_buffer_from_config(config))) + tokens, topk_idx, w, grad = self._moe_calls(1)[0] + + def run(): + for p in model.parameters(): + p.grad = None + with te.autocast(enabled=recipe is not None, recipe=recipe): + out = self._moe_call(model, tokens, topk_idx, w, grad) + torch.cuda.synchronize() + return out, self._param_grads(model) + + fast = run() + self._assert_fusion(model, True) + with self._deterministic_algorithms(): + first = run() + second = run() + self._assert_fusion(model, True) + self._assert_bitwise_equal(second[0], first[0]) + self._assert_moe_close(second[1], first[1]) + self._assert_moe_close(first, fast) @_mxfp8_align_test @_overlap_test @@ -2427,7 +2543,7 @@ def step(): out["y"].backward(grad) graph = self._capture(step) - self.assertTrue(self._moe_overlap_selected(model)) + self._assert_fusion(model, True) results = [] for call in replays: with torch.no_grad(): @@ -2471,7 +2587,7 @@ def test_moe_overlap_instances(self): topk_idx, tokens, w = _make_identity_inputs(self.cfg.rank, self.cfg.ep_size) model(tokens, topk_idx, w, topk_idx) torch.cuda.synchronize() - self.assertTrue(self._moe_overlap_selected(model)) + self._assert_fusion(model, True) # Separate instances and buffers; _moe_ops seeds identical weights. model_a = te_ops.Sequential(*self._moe_ops(config, self._make_buffer_from_config(config))) @@ -2493,10 +2609,10 @@ def backward(model, x, topk_w, y, grad): # Each call run alone, as the serial reference. xa, wa, ya = forward(model_a, call_a) alone_a = backward(model_a, xa, wa, ya, call_a[3]) - self.assertTrue(self._moe_overlap_selected(model_a)) + self._assert_fusion(model_a, True) xb, wb, yb = forward(model_b, call_b) alone_b = backward(model_b, xb, wb, yb, call_b[3]) - self.assertTrue(self._moe_overlap_selected(model_b)) + self._assert_fusion(model_b, True) # Interleaved: the second instance's whole call lands between the first's forward and # backward; separate buffers keep each call's routing state intact. diff --git a/tests/pytorch/distributed/run_test_ep.sh b/tests/pytorch/distributed/run_test_ep.sh index 1bc17c7d669..276044f8333 100755 --- a/tests/pytorch/distributed/run_test_ep.sh +++ b/tests/pytorch/distributed/run_test_ep.sh @@ -63,6 +63,8 @@ run_pass() { local mxfp8="${5:-0}" local fused="${6:-0}" local overlap="${7:-0}" + # Overlap passes: fused-op tests that must have run on every rank (0 for a pass that runs none). + local min_executed="${8:-3}" local log="stdout_ep_${label}.txt" # The overlap passes compile CuTeDSL GEMMs on first use and need a longer timeout. local timeout_s="${TEST_TIMEOUT_S}" @@ -89,18 +91,24 @@ run_pass() { echo "[${label}] ERROR: no test summary — likely hang or early crash" RET=1 fi - # An overlap pass in which a rank never ran the fused ops covers nothing: tests that skip, or - # that fall back to the unfused ops, do not report. Every rank reports from a numerical test. - if [ "${overlap}" = "1" ]; then - local executed - executed=$(grep -oE "OVERLAP_EXECUTED rank=[0-9]+" "${log}" | sort -u | wc -l) + # An overlap pass in which a rank ran too few fused-op tests covers nothing: tests that skip, or + # that fall back to the unfused ops, do not report. Each such test prints + # "OVERLAP_EXECUTED test= rank=". + if [ "${overlap}" = "1" ] && [ "${min_executed}" -gt 0 ]; then # A pass skipped for lack of backward SM budgets in NCCL EP executed nothing, by design. if grep -q "NCCL EP has no backward SM budgets" "${log}"; then echo "[${label}] SKIPPED: NCCL EP has no backward SM budgets" - elif [ "${executed}" -lt "${NUM_RANKS}" ]; then - echo "[${label}] ERROR: the fused overlap ops ran on ${executed} of ${NUM_RANKS} ranks;" \ - "set NVTE_ENABLE_CUTEDSL_BACKEND=1 and NVTE_MOE_OVERLAP=1" - RET=1 + else + local rank executed + for ((rank = 0; rank < NUM_RANKS; rank++)); do + executed=$(grep -oE "OVERLAP_EXECUTED test=[A-Za-z0-9_]+ rank=${rank}\b" "${log}" \ + | sort -u | wc -l) + if [ "${executed}" -lt "${min_executed}" ]; then + echo "[${label}] ERROR: rank ${rank} ran ${executed} fused overlap tests, need at least" \ + "${min_executed}; set NVTE_ENABLE_CUTEDSL_BACKEND=1 and NVTE_MOE_OVERLAP=1" + RET=1 + fi + done fi fi if [ -z "${KEEP_EP_LOGS:-}" ]; then rm -f "${log}"; fi @@ -171,10 +179,17 @@ else run_pass "overlap_overflow" 0 0 1 1 0 1 # Per-direction SM counts (dispatch fwd, combine fwd, dispatch bwd, combine bwd). The backward # split skips when Transformer Engine was built against an NCCL EP without backward SM budgets. - NVTE_EP_COMM_SMS=12,20,0,0 run_pass "overlap_split" 0 0 0 1 0 1 + # NVTE_EP_OVERLAP_CONFIG: combine_chunk_hidden,push_last_chunk_sms,reduce_last_chunk_sms, + # dispatch_chunk_tokens. Flags per 256 combine columns without splitting the last chunk here, + # three combine chunks per row with split last chunks in the hidden 1536 pass below. + NVTE_EP_OVERLAP_CONFIG=256,0,0,0 NVTE_EP_COMM_SMS=12,20,0,0 run_pass "overlap_split" 0 0 0 1 0 1 NVTE_EP_COMM_SMS=12,20,24,16 run_pass "overlap_split_bwd" 0 0 0 1 0 1 # A hidden size that 1024 does not divide: the combine waits on whole rows. - NVTE_EP_HIDDEN_DIM=1536 run_pass "overlap_h1536" 0 0 0 1 0 1 + NVTE_EP_OVERLAP_CONFIG=512,16,8,0 NVTE_EP_HIDDEN_DIM=1536 run_pass "overlap_h1536" 0 0 0 1 0 1 + # A dispatch chunk other than the alignment is rejected; only that test runs and it runs no + # fused op. + NVTE_EP_OVERLAP_CONFIG=0,0,0,128 NVTE_EP_TEST_FILTER=test_moe_overlap_rejects_dispatch_chunk \ + run_pass "overlap_dispatch_chunk" 0 0 0 1 0 1 0 fi finish diff --git a/tests/pytorch/test_ep_gemm.py b/tests/pytorch/test_ep_gemm.py index cc9b6183b4a..f43f1a9101a 100644 --- a/tests/pytorch/test_ep_gemm.py +++ b/tests/pytorch/test_ep_gemm.py @@ -19,6 +19,8 @@ import tvm_ffi +import transformer_engine.pytorch # pylint: disable=unused-import +import transformer_engine_torch as tex from transformer_engine.common.CuTeDSL.ep_gemm import ( combine_gemm, dispatch_gemm, @@ -43,14 +45,11 @@ def _unit_e8m0(count, device): return torch.full((count,), 127, dtype=torch.uint8, device=device).view(torch.float8_e8m0fnu) -def _run_gemm( - rows_per_expert, rows_alignment, mxfp8, tail_clusters, device_layout, int64_offsets=False -): +def _run_gemm(rows_per_expert, rows_alignment, mxfp8, tail_clusters, device_layout): """Launch the forward GEMM with every row tile ready, and with ``tail_clusters`` a second launch behind it on the same workspace; return (a, b, alpha, prob, c, d, claims) with MXFP8 operands at unit scales in float32, the MXFP8 ``d`` dequantized and the final claim counter. - ``device_layout``: the row ends follow expert 0's offset, as the dispatch writes them. - ``int64_offsets``: the row ends are int64.""" + ``device_layout``: the row ends follow expert 0's offset, as the dispatch writes them.""" device = torch.device("cuda") hidden, n, experts = 1024, 1024, len(rows_per_expert) rows = sum(rows_per_expert) + TILE # spare tile: the capacity exceeds the rows in use @@ -64,7 +63,6 @@ def _run_gemm( scaling_mode=scaling_mode, token_alignment=rows_alignment, device_layout=device_layout, - int64_offsets=int64_offsets, ) launches = [] for num_clusters in (cfg.num_clusters, tail_clusters): @@ -72,7 +70,6 @@ def _run_gemm( continue name = ( f"test_ep_gemm_{rows}_{rows_alignment}_{int(mxfp8)}_{num_clusters}_{int(device_layout)}" - f"_{int(int64_offsets)}" ) assert dispatch_gemm.get_ep_dispatch_gemm_function( name, @@ -85,7 +82,6 @@ def _run_gemm( mxfp8, rows_alignment, device_layout, - int64_offsets=int64_offsets, ) launches.append(tvm_ffi.get_global_func(name)) @@ -96,12 +92,11 @@ def _run_gemm( # Powers of two: alpha and prob cost no tolerance. alpha = torch.pow(2.0, (torch.arange(experts, device=device) % 5 - 2).float()) prob = torch.pow(2.0, (torch.arange(rows, device=device) % 3 - 1).float()) - offsets_type = torch.int64 if int64_offsets else torch.int32 - ends = torch.tensor(rows_per_expert, device=device).cumsum(0).to(offsets_type) + ends = torch.tensor(rows_per_expert, device=device).cumsum(0).to(torch.int64) if device_layout: # Offsets then the total: expert 0's offset is the entry before the 16-byte aligned ends. pad = 16 // ends.element_size() - layout = torch.zeros(pad + experts, dtype=offsets_type, device=device) + layout = torch.zeros(pad + experts, dtype=torch.int64, device=device) layout[pad:] = ends ends = layout[pad:] d_cols = n // 2 @@ -150,18 +145,17 @@ def _run_gemm( ) @pytest.mark.parametrize("tail_clusters", [0, 4]) @pytest.mark.parametrize("device_layout", [False, True]) -@pytest.mark.parametrize("int64_offsets", [False, True]) def test_dispatch_gemm_matches_reference( - rows_alignment, mxfp8, rows_per_expert, tail_clusters, device_layout, int64_offsets + rows_alignment, mxfp8, rows_per_expert, tail_clusters, device_layout ): """Grouped GEMM over padded slabs matches a float32 reference, also with experts padded to - fewer rows than a tile, with a tail launch sharing the tiles, with the dispatch-written - layout and with int64 row ends; rows past the last expert stay 0.""" + fewer rows than a tile, with a tail launch sharing the tiles and with the dispatch-written + layout; rows past the last expert stay 0.""" args = (rows_per_expert, rows_alignment, mxfp8) - a, b, alpha, prob, c, d, claims = _run_gemm(*args, tail_clusters, device_layout, int64_offsets) + a, b, alpha, prob, c, d, claims = _run_gemm(*args, tail_clusters, device_layout) if tail_clusters: # The tail's schedulers claimed from the counter they share with the base's. - assert claims > _run_gemm(*args, 0, device_layout, int64_offsets)[-1] + assert claims > _run_gemm(*args, 0, device_layout)[-1] used = sum(rows_per_expert) ref_c = torch.zeros(a.shape[0], b.shape[1], dtype=torch.float32, device=a.device) start = 0 @@ -199,7 +193,7 @@ def _run_combine(rows_per_expert, rows_alignment, mxfp8, backward): # Powers of two: alpha and prob cost no tolerance. alpha = torch.pow(2.0, (torch.arange(experts, device=device) % 5 - 2).float()) prob = torch.pow(2.0, (torch.arange(rows, device=device) % 3 - 1).float()) - ends = torch.tensor(rows_per_expert, device=device).cumsum(0).to(torch.int32) + ends = torch.tensor(rows_per_expert, device=device).cumsum(0).to(torch.int64) d = torch.zeros(rows, n, dtype=torch.bfloat16, device=device) ws_bytes = combine_gemm.get_ep_combine_gemm_workspace_layout( rows, k, n, experts, 8, 0, False, backward, mxfp8, rows_alignment @@ -274,7 +268,7 @@ def _run_wgrad(rows_per_expert, mxfp8, fp32_out, accumulate, n=512, kernel_class experts, m, n ) weight_grad = (init if accumulate else torch.zeros_like(init)).to(out_dtype, copy=True) - ends = torch.tensor(rows_per_expert, device=device).cumsum(0).to(torch.int32) + ends = torch.tensor(rows_per_expert, device=device).cumsum(0).to(torch.int64) ws_bytes = wgrad_gemm.get_ep_wgrad_workspace_layout(*args)[0] workspace = torch.zeros(ws_bytes, dtype=torch.uint8, device=device) # Shared tile counter the launches claim from; the kernel does not reset it. @@ -333,3 +327,33 @@ def test_wgrad_gemm_reuse_matches_reference(): start += count err = (weight_grad - ref).abs() / ref.abs().clamp_min(1e-6) assert err.max() <= 2.0**-8 + + +def _dispatch_gemm_fwd_args(tokens_shape=(8, 1024)): + """Arguments of ``tex.ep_dispatch_gemm_fwd`` with BF16 operands of consistent shapes, 4 local + experts and 2 tiles of receive rows; the call needs no EP group when it is rejected.""" + device = torch.device("cuda") + hidden, ffn, experts, rows = 1024, 1024, 4, 2 * TILE + # Offsets then the total, 16-byte aligned: the layout the dispatch writes. + offsets = torch.zeros(1 + experts + 1, dtype=torch.int64, device=device) + return ( + torch.empty(4096, dtype=torch.uint8, device=device), + torch.zeros(8, 2, dtype=torch.int64, device=device), + torch.zeros(tokens_shape, dtype=torch.bfloat16, device=device), + torch.ones(8, 2, dtype=torch.float32, device=device), + torch.zeros(experts, 2 * ffn, hidden, dtype=torch.bfloat16, device=device), + torch.zeros(rows, hidden, dtype=torch.bfloat16, device=device), + torch.zeros(rows, dtype=torch.float32, device=device), + torch.zeros(experts, dtype=torch.int64, device=device), + offsets[1:], + torch.zeros(rows, 2 * ffn, dtype=torch.bfloat16, device=device), + torch.zeros(rows, ffn, dtype=torch.bfloat16, device=device), + 2, + TILE, + ) + + +def test_dispatch_gemm_fwd_rejects_flat_tokens(): + """Tokens that are not [num_tokens, hidden] raise an error before any GEMM work.""" + with pytest.raises(RuntimeError, match="tokens must be"): + tex.ep_dispatch_gemm_fwd(*_dispatch_gemm_fwd_args(tokens_shape=(8 * 1024,))) diff --git a/tests/pytorch/test_grouped_mlp.py b/tests/pytorch/test_grouped_mlp.py index dfb6920d679..cf9555e7975 100644 --- a/tests/pytorch/test_grouped_mlp.py +++ b/tests/pytorch/test_grouped_mlp.py @@ -1830,33 +1830,17 @@ def test_grouped_mlp_glu_mxfp8_real_cudnn_fusion( assert traced_cudnn_grouped_glu_wrappers == expected_calls @pytest.mark.skipif(not mxfp8_available, reason=reason_for_no_mxfp8) - @pytest.mark.parametrize( - "int64_offsets", - (False, True, None), - ids=("offsets_int32", "offsets_int64", "offsets_detected"), - ) - def test_grouped_mlp_mxfp8_offsets_dtype( - self, monkeypatch, int64_offsets: Optional[bool] - ) -> None: - """The cuDNN MXFP8 GEMMs take int64 offsets where the frontend accepts them. - - ``None`` keeps the dtype detected from the installed frontend. - """ + def test_grouped_mlp_mxfp8_offsets_dtype(self, monkeypatch) -> None: + """The cuDNN MXFP8 GEMMs take int64 offsets.""" if not _cudnn_frontend_version_supported(): pytest.skip("Requires cuDNN frontend >= 1.31.0") if not device_is_blackwell: pytest.skip("Requires Blackwell") import cudnn + from cudnn.gemm.cutedsl import grouped - supported = grouped_mlp_module._cudnn_frontend_supports_int64_offsets() - if int64_offsets and not supported: + if not getattr(grouped, "INT64_OFFSETS", False): pytest.skip("The cuDNN frontend takes only int32 offsets") - if int64_offsets is None: - int64_offsets = supported - else: - monkeypatch.setattr( - grouped_mlp_module, "_cudnn_frontend_supports_int64_offsets", lambda: int64_offsets - ) offsets_dtypes = {} for name, key in ( ("grouped_gemm_glu_wrapper_sm100", "padded_offsets"), @@ -1891,11 +1875,10 @@ def traced(*args, _wrapper=getattr(cudnn, name), _name=name, _key=key, **kwargs) finally: _clear_grouped_glu_kernel_caches() fused_cls.grouped_gemm_wgrad_kernel.cache_clear() - expected = torch.int64 if int64_offsets else torch.int32 assert offsets_dtypes == { - "grouped_gemm_glu_wrapper_sm100": {expected}, - "grouped_gemm_dglu_wrapper_sm100": {expected}, - "grouped_gemm_wgrad_wrapper_sm100": {expected}, + "grouped_gemm_glu_wrapper_sm100": {torch.int64}, + "grouped_gemm_dglu_wrapper_sm100": {torch.int64}, + "grouped_gemm_wgrad_wrapper_sm100": {torch.int64}, } @pytest.mark.skipif(not nvfp4_available, reason=reason_for_no_nvfp4) diff --git a/tests/pytorch/test_nccl_ep_discovery.py b/tests/pytorch/test_nccl_ep_discovery.py index 6fc20e72ee9..e2d40a75561 100644 --- a/tests/pytorch/test_nccl_ep_discovery.py +++ b/tests/pytorch/test_nccl_ep_discovery.py @@ -96,3 +96,76 @@ def test_moe_overlap_rejects_unsupported_alignment(monkeypatch): config, 1024, params_dtype=torch.bfloat16, glu_interleave_size=32 ) assert reason is not None and "alignment" in reason + + +def _overlap_ep_config(**overrides): + from transformer_engine.pytorch.ep import EpConfig + + fields = dict( + top_k=2, + hidden_dim=1024, + num_local_experts=4, + max_tokens_per_rank=256, + recv_capacity_per_rank=1024, + ep_group=None, + alignment=256, + ) + fields.update(overrides) + return EpConfig(**fields) + + +@pytest.mark.parametrize( + "config_overrides,reason_overrides,expected", + [ + ({}, {}, None), + ({"zero_copy": True}, {}, "zero-copy"), + ({"recv_capacity_per_rank": 1152}, {}, "recv_capacity_per_rank must be a multiple of 256"), + ({}, {"bias": True}, "biases are not supported"), + ({}, {"single_grouped_weight": False}, "single_grouped_weight=True"), + ({}, {"activation": "ScaledGeGLU"}, "SwiGLU"), + ({}, {"glu_interleave_size": 16}, "glu_interleave_size 32"), + ({}, {"glu_interleave_size": None}, "glu_interleave_size 32"), + ], +) +def test_moe_overlap_unsupported_reason(monkeypatch, config_overrides, reason_overrides, expected): + """A window FusedMoE cannot run names the unsupported setting; a supported one has no reason.""" + import torch + from transformer_engine.pytorch.ops.fused import moe_overlap + + monkeypatch.setattr(moe_overlap.FusedMoE, "is_supported", classmethod(lambda cls: True)) + kwargs = dict(params_dtype=torch.bfloat16, glu_interleave_size=32, single_grouped_weight=True) + kwargs.update(reason_overrides) + reason = moe_overlap._moe_overlap_unsupported_reason( + _overlap_ep_config(**config_overrides), 1024, **kwargs + ) + if expected is None: + assert reason is None + else: + assert reason is not None and expected in reason + + +@pytest.mark.parametrize( + "config", + [ + {"sm_config": ("EpSmConfig", {"dispatch_fwd_num_sms": -1})}, + {"sm_config": ("EpSmConfig", {"combine_bwd_num_sms": -4})}, + {"overlap_config": ("EpOverlapConfig", {"combine_chunk_hidden": -256})}, + {"overlap_config": ("EpOverlapConfig", {"combine_push_last_chunk_sms": -1})}, + {"overlap_config": ("EpOverlapConfig", {"combine_reduce_last_chunk_sms": -1})}, + {"overlap_config": ("EpOverlapConfig", {"dispatch_chunk_tokens": -256})}, + ], +) +def test_ep_bootstrap_rejects_negative_budgets(config): + """Negative SM budgets and chunk sizes are rejected before the EP group is touched.""" + from transformer_engine.pytorch import ep + + kwargs = {name: getattr(ep, cls)(**fields) for name, (cls, fields) in config.items()} + with pytest.raises(ValueError, match="negative"): + ep.ep_bootstrap( + None, + num_experts=8, + max_tokens_per_rank=64, + hidden_dim=512, + num_topk=2, + **kwargs, + ) diff --git a/transformer_engine/common/CuTeDSL/ep_gemm/_loader.py b/transformer_engine/common/CuTeDSL/ep_gemm/_loader.py index d175c560557..f8b584b7998 100644 --- a/transformer_engine/common/CuTeDSL/ep_gemm/_loader.py +++ b/transformer_engine/common/CuTeDSL/ep_gemm/_loader.py @@ -70,14 +70,9 @@ class GemmArch: dispatch_bwd="dglu.moe_grouped_gemm_dglu_dbias.MoEGroupedGemmDgluDbiasBf16Kernel", combine="unfused.moe_grouped_gemm.MoEGroupedGemmBf16Kernel", ) -# SM 10.7 (Rubin) runs the SM 10.0 BF16 kernels, which cuDNN FE sizes to the device's shared memory. -_SM107 = GemmArch( - dispatch_fwd=_SM100.dispatch_fwd, - dispatch_bwd=_SM100.dispatch_bwd, - combine=_SM100.combine, -) -# Kernels by compute capability; other architectures run the unfused ops. -GEMM_ARCHS = {(10, 0): _SM100, (10, 3): _SM100, (10, 7): _SM107} +# Kernels by compute capability; other architectures run the unfused ops. SM 10.7 runs the SM 10.0 +# BF16 kernels, which cuDNN FE sizes to the device's shared memory. +GEMM_ARCHS = {(10, 0): _SM100, (10, 3): _SM100, (10, 7): _SM100} def gemm_arch(): @@ -92,10 +87,10 @@ def is_sm107(): def import_gemm_modules(*names): """Import the named modules of the kernel package (and ``moe_utils`` last).""" - out = [] - for name in (*names, "moe_utils"): - out.append(importlib.import_module(f"{_PKG}.{_MODULE_PATHS.get(name, name)}")) - return tuple(out) + return tuple( + importlib.import_module(f"{_PKG}.{_MODULE_PATHS.get(name, name)}") + for name in (*names, "moe_utils") + ) def import_bf16_kernel(role): @@ -160,6 +155,22 @@ def prob_view(prob, rows): return cute.make_tensor(prob.iterator, cute.make_layout((rows, 1, 1), stride=(1, 1, 1))) +def dprob_n_slots(n): + """Slots per row of the deterministic routing-weight gradient of a GEMM with n columns: one per + N tile. Tiles are scheduled per cluster, so the count rounds up to the cluster's N extent.""" + cluster_n = CLUSTER_MN[1] + return -(-n // (MMA_TILER_MN[1] * cluster_n)) * cluster_n + + +def slots_view(slots, rows, n_slots): + """[rows * n_slots] slots as the kernel's (rows, n_slots, 1) tensor.""" + from cutlass import cute # pylint: disable=import-outside-toplevel + + return cute.make_tensor( + slots.iterator, cute.make_layout((rows, n_slots, 1), stride=(n_slots, 1, rows * n_slots)) + ) + + def fp8_fake(shape, order): """A fake E4M3 operand.""" import cutlass # pylint: disable=import-outside-toplevel @@ -192,19 +203,12 @@ def blockscaled_kwargs(num_experts): } -def offsets_dtype(int64_offsets): - """CuTe dtype of the expert row ends.""" - import cutlass # pylint: disable=import-outside-toplevel - - return cutlass.Int64 if int64_offsets else cutlass.Int32 - - -def tail_fakes(rows, experts, ws_bytes, int64_offsets=False): - """Fake row ends, alpha, prob and workspace operands shared by every launch.""" +def tail_fakes(rows, experts, ws_bytes): + """Fake int64 row ends, alpha, prob and workspace operands shared by every launch.""" import cutlass # pylint: disable=import-outside-toplevel return ( - fake_tensor(offsets_dtype(int64_offsets), (experts,), (0,), 16), + fake_tensor(cutlass.Int64, (experts,), (0,), 16), fake_tensor(cutlass.Float32, (experts,), (0,), 16), fake_tensor(cutlass.Float32, (rows,), (0,), 16), fake_tensor(cutlass.Uint8, (ws_bytes,), (0,), 128), @@ -212,15 +216,16 @@ def tail_fakes(rows, experts, ws_bytes, int64_offsets=False): def register_function(fn_name, compile_fn, what) -> bool: - """Compile and register ``fn_name`` unless registered; return whether it is.""" + """Compile and register ``fn_name`` unless registered; return whether it is. False means the + device is unsupported. A failed compile or import raises, so that it is reported with its cause + and retried by the next call.""" + if tvm_ffi.get_global_func(fn_name, allow_missing=True) is not None: + return True + if (reason := unsupported_device_reason(what)) is not None: + logger.warning("%s", reason) + return False try: - if tvm_ffi.get_global_func(fn_name, allow_missing=True) is not None: - return True - if (reason := unsupported_device_reason(what)) is not None: - logger.warning("%s", reason) - return False tvm_ffi.register_global_func(fn_name, tvm_ffi_function(compile_fn()), override=True) - return True except Exception as e: # pylint: disable=broad-exception-caught - logger.error("The %s is not available: %s", what, e) - return False + raise RuntimeError(f"The {what} is not available: {e}") from e + return True diff --git a/transformer_engine/common/CuTeDSL/ep_gemm/combine_gemm.py b/transformer_engine/common/CuTeDSL/ep_gemm/combine_gemm.py index f5ad7107091..db54333fb11 100644 --- a/transformer_engine/common/CuTeDSL/ep_gemm/combine_gemm.py +++ b/transformer_engine/common/CuTeDSL/ep_gemm/combine_gemm.py @@ -10,8 +10,8 @@ backward [rows,k] [E,k,n] (the forward weight) [rows,n] BF16, scaled per row by prob BF16 operands, or E4M3 with GEMM-swizzled E8M0 scales ``sfa`` and ``sfb`` for MXFP8 (the backward -reads the columnwise forward weight). Common operands: ``expert_row_ends`` [E] int32 (int64 -with ``int64_offsets``), ``alpha`` [E] FP32, ``prob`` [rows] FP32, ``workspace`` uint8, stream. +reads the columnwise forward weight). Common operands: ``expert_row_ends`` [E] int64, +``alpha`` [E] FP32, ``prob`` [rows] FP32, ``workspace`` uint8, stream. ``signal[u] = u`` once columns ``[u * n_chunk, (u + 1) * n_chunk)`` of ``d`` are final; the caller sets ``signal[]`` to -1 before each launch. With ``n_chunk`` 0 the GEMM publishes nothing and runs in the stock tile order; its workspace ends in one flag word the caller sets. @@ -61,7 +61,6 @@ class CombineGemmConfig: scaling_mode: int = DELAYED_TENSOR_SCALING # operand scaling (NVTEScalingMode) token_alignment: int = ROWS_PER_TILE # rows per expert slab are a multiple of it grid_clusters: int = 0 # clusters launched (0: num_clusters), extras stop after the first chunk - int64_offsets: bool = False # int64 instead of int32 expert row ends # Kernels, workspace layouts and compiled functions are specific to the device architecture. capability: tuple = field(default_factory=device_compute_capability) @@ -150,7 +149,7 @@ def launch(a, b, d, expert_row_ends, alpha, prob, workspace, stream): cutlass.BFloat16, (experts, k, n) if backward else (experts, n, k), (2, 1, 0), 16 ), fake_tensor(cutlass.BFloat16, (rows, n), (1, 0), 16), - *tail_fakes(rows, experts, workspace_layout(cfg)[0], cfg.int64_offsets), + *tail_fakes(rows, experts, workspace_layout(cfg)[0]), ) @@ -190,42 +189,40 @@ def launch_rubin(a, b, sfb, sfa, d, expert_row_ends, alpha, prob, workspace, str scale_fake(experts * n, k), scale_fake(rows, k), fake_tensor(cutlass.BFloat16, (rows, n), (1, 0), 16), - *tail_fakes(rows, experts, workspace_layout(cfg)[0], cfg.int64_offsets), + *tail_fakes(rows, experts, workspace_layout(cfg)[0]), ) def _config( rows, k, n, num_experts, num_clusters, n_chunk, dependents_at_entry, backward, scaling_mode, - token_alignment, grid_clusters, int64_offsets, + token_alignment, grid_clusters, ): # fmt: skip """Build a CombineGemmConfig from the entry-point arguments.""" return CombineGemmConfig( rows, k, n, num_experts, num_clusters, n_chunk, bool(dependents_at_entry), bool(backward), - int(scaling_mode), token_alignment, grid_clusters, bool(int64_offsets), + int(scaling_mode), token_alignment, grid_clusters, ) # fmt: skip def get_ep_combine_gemm_workspace_layout( rows, k, n, num_experts, num_clusters, n_chunk, dependents_at_entry, backward, scaling_mode=DELAYED_TENSOR_SCALING, token_alignment=ROWS_PER_TILE, grid_clusters=0, - int64_offsets=False, ): # fmt: skip """[total bytes, signal offset, signal entries] of the workspace of this configuration.""" return list(workspace_layout(_config( rows, k, n, num_experts, num_clusters, n_chunk, dependents_at_entry, backward, scaling_mode, - token_alignment, grid_clusters, int64_offsets, + token_alignment, grid_clusters, ))) # fmt: skip def get_ep_combine_gemm_function( fn_name, rows, k, n, num_experts, num_clusters, n_chunk, dependents_at_entry, backward, scaling_mode=DELAYED_TENSOR_SCALING, token_alignment=ROWS_PER_TILE, grid_clusters=0, - int64_offsets=False, ) -> bool: # fmt: skip """Compile and register the GEMM of this configuration as ``fn_name``; return whether it is.""" cfg = _config( rows, k, n, num_experts, num_clusters, n_chunk, dependents_at_entry, backward, scaling_mode, - token_alignment, grid_clusters, int64_offsets, + token_alignment, grid_clusters, ) # fmt: skip compile_fn = _compile_mxfp8 if cfg.mxfp8 else _compile return register_function(fn_name, lambda: compile_fn(cfg), "EP grouped GEMM combine") diff --git a/transformer_engine/common/CuTeDSL/ep_gemm/dispatch_gemm.py b/transformer_engine/common/CuTeDSL/ep_gemm/dispatch_gemm.py index 3e166ced809..8c0418f1814 100644 --- a/transformer_engine/common/CuTeDSL/ep_gemm/dispatch_gemm.py +++ b/transformer_engine/common/CuTeDSL/ep_gemm/dispatch_gemm.py @@ -14,7 +14,7 @@ Forward is FC1 (gate and up alternate in 32-column blocks of ``c``). Backward is the FC2 data gradient with the SwiGLU backward in the epilogue; its ``c`` is the FC1 output [rows, 2n]. -Common operands: ``expert_row_ends`` [E] int32 (int64 with ``int64_offsets``), ``alpha`` [E] +Common operands: ``expert_row_ends`` [E] int64, ``alpha`` [E] FP32, ``prob`` [rows] FP32, ``workspace`` uint8, stream. With ``device_layout`` the forward also waits for the dispatch to write ``expert_row_ends`` and the entry before it (expert 0's offset), both -1 beforehand. The kernel waits until they are at least 0. @@ -24,6 +24,9 @@ ``sfd_col`` and ``sfh_col`` (swizzled per expert). Without ``d_col`` or ``h`` in the configuration the backward takes None for ``d_col`` and ``sfd_col``, or ``h`` and ``sfh_col``, and does not write them. + +The routing-weight gradient dprob is added to atomically, or with ``deterministic`` written to one +FP32 slot per row and N tile, ``dprob`` then being [rows * dprob_n_slots(n)] to sum in a fixed order. """ import functools @@ -36,6 +39,7 @@ from ..utils import DELAYED_TENSOR_SCALING, MXFP8_1D_SCALING from ._loader import ( device_compute_capability, + dprob_n_slots, CLUSTER_MN, MMA_TILER_MN, ROWS_PER_TILE, @@ -50,6 +54,7 @@ register_function, rows_view, scale_fake, + slots_view, tail_fakes, weight_view, ) @@ -73,7 +78,7 @@ class DispatchGemmConfig: device_layout: bool = False # forward: the dispatch writes the expert row ends d_col: bool = True # MXFP8 backward: writes the columnwise d and its scales h: bool = True # MXFP8 backward: writes the columnwise h and its scales - int64_offsets: bool = False # int64 instead of int32 expert row ends + deterministic: bool = False # backward: dprob in per-N-tile slots instead of atomics activation: str = "swiglu" # Kernels, workspace layouts and compiled functions are specific to the device architecture. capability: tuple = field(default_factory=device_compute_capability) @@ -106,11 +111,23 @@ def _tail_trigger() -> dict: return {"launch_pdl_dependents_at_entry": True} +def _backward_kernel_class(mxfp8: bool): + """Class of the device's dGLU backward kernel for BF16 or MXFP8 operands.""" + if not mxfp8: + return import_bf16_kernel("dispatch_bwd")[0] + if is_sm107(): + module = import_gemm_modules("moe_blockscaled_grouped_gemm_dglu_rubin")[0] + return module.BlockScaledMoEGroupedGemmDgluKernel + module = import_gemm_modules("moe_blockscaled_grouped_gemm_dglu_dbias")[0] + return module.BlockScaledMoEGroupedGemmDgluDbiasKernel + + def build_kernel(cfg: DispatchGemmConfig): """Kernel for ``cfg``; row tiles wait on ``signal[]``. A forward one lets its tail launch at the ``_tail_trigger`` point. The backward one lets the kernel behind it start at entry.""" backward_activation = _BACKWARD_ACTIVATIONS[cfg.activation] rubin = is_sm107() + deterministic = {"deterministic": True} if cfg.backward and cfg.deterministic else {} if cfg.mxfp8: # The TMA warp turns the received compact scales into the GEMM's layout per tile. common = { @@ -121,19 +138,19 @@ def build_kernel(cfg: DispatchGemmConfig): } if cfg.backward and rubin: # 128-deep K tiles of one scale atom each: the TMA warp queues the compact scales ahead. - module = import_gemm_modules("moe_blockscaled_grouped_gemm_dglu_rubin")[0] # TODO(phuonguyen): fp8_k_tile / compact_sfa_queue are computed internally by cuDNN FE. - return module.BlockScaledMoEGroupedGemmDgluKernel( + return _backward_kernel_class(True)( discrete_col_sfd=True, act_func=backward_activation, + **deterministic, **common, ) if cfg.backward: - module = import_gemm_modules("moe_blockscaled_grouped_gemm_dglu_dbias")[0] - return module.BlockScaledMoEGroupedGemmDgluDbiasKernel( + return _backward_kernel_class(True)( discrete_col_sfd=True, act_func=backward_activation, launch_pdl_dependents_at_entry=True, + **deterministic, **common, ) if rubin: @@ -177,11 +194,12 @@ def build_kernel(cfg: DispatchGemmConfig): "use_pdl": True, } if cfg.backward: - kernel_class, moe_utils = import_bf16_kernel("dispatch_bwd") - return kernel_class( + moe_utils = import_gemm_modules()[0] + return _backward_kernel_class(False)( weight_mode=moe_utils.MoEWeightMode.DENSE, act_func=backward_activation, launch_pdl_dependents_at_entry=True, + **deterministic, **common, ) kernel_class, moe_utils = import_bf16_kernel("dispatch_fwd") @@ -208,7 +226,7 @@ def _prologue(cfg: DispatchGemmConfig): """Kernel, (rows, k, n, experts, num_clusters) and workspace tail fakes shared by a compiler.""" kernel = build_kernel(cfg) dims = (cfg.rows, cfg.k, cfg.n, cfg.num_experts, cfg.num_clusters) - tail = tail_fakes(cfg.rows, cfg.num_experts, workspace_layout(cfg)[0], cfg.int64_offsets) + tail = tail_fakes(cfg.rows, cfg.num_experts, workspace_layout(cfg)[0]) return kernel, dims, tail @@ -241,15 +259,19 @@ def _compile_backward(cfg: DispatchGemmConfig): """FC2 data gradient with the forward weight [experts, k, n] read N-major, and SwiGLU backward in the epilogue (unit alpha and beta).""" kernel, (rows, k, n, experts, num_clusters), tail = _prologue(cfg) + n_slots = dprob_n_slots(n) if cfg.deterministic else 1 @cute.jit def launch(a, b, c, d, dprob, expert_row_ends, alpha, prob, workspace, stream): weight = weight_view(b, n, k, experts, n_major=True) + dprob_out = ( + slots_view(dprob, rows, n_slots) if cfg.deterministic else prob_view(dprob, rows) + ) kernel( rows_view(a, rows, k), weight, cutlass.Int32(0), cutlass.Int32(0), cutlass.Int64(0), OperandMajorMode.K, workspace.iterator, rows_view(c, rows, 2 * n), rows_view(d, rows, 2 * n), expert_row_ends, alpha, alpha, prob_view(prob, rows), - prob_view(dprob, rows), cutlass.Float32(0.0), None, num_clusters, stream, + dprob_out, cutlass.Float32(0.0), None, num_clusters, stream, ) # fmt: skip return compile_launch( @@ -258,7 +280,7 @@ def launch(a, b, c, d, dprob, expert_row_ends, alpha, prob, workspace, stream): fake_tensor(cutlass.BFloat16, (experts, k, n), (2, 1, 0), 16), fake_tensor(cutlass.BFloat16, (rows, 2 * n), (1, 0), 16), fake_tensor(cutlass.BFloat16, (rows, 2 * n), (1, 0), 16), - fake_tensor(cutlass.Float32, (rows,), (0,), 16), + fake_tensor(cutlass.Float32, (rows * n_slots,), (0,), 16), *tail, ) @@ -318,6 +340,7 @@ def _compile_backward_mxfp8(cfg: DispatchGemmConfig): """MXFP8 FC2 data gradient with the columnwise forward weight [experts, k, n] read N-major, SwiGLU backward in the epilogue, and the forward activation recomputed columnwise.""" kernel, (rows, k, n, experts, num_clusters), tail = _prologue(cfg) + n_slots = dprob_n_slots(n) if cfg.deterministic else 1 @cute.jit def launch( @@ -325,12 +348,15 @@ def launch( prob, norm_const, workspace, stream, ): # fmt: skip weight = weight_view(b, n, k, experts, n_major=True) + dprob_out = ( + slots_view(dprob, rows, n_slots) if cfg.deterministic else prob_view(dprob, rows) + ) kernel( rows_view(a, rows, k), weight, sfb, cutlass.Int32(0), cutlass.Int32(0), cutlass.Int64(0), OperandMajorMode.K, workspace.iterator, rows_view(c, rows, 2 * n), rows_view(d, rows, 2 * n), _optional_rows_view(d_col, rows, 2 * n), sfa, sfd_row, sfd_col, None, norm_const, expert_row_ends, alpha, alpha, prob_view(prob, rows), - prob_view(dprob, rows), None, num_clusters, stream, + dprob_out, None, num_clusters, stream, h_tensor=_optional_rows_view(h, rows, n), sfh_col_tensor=sfh_col, ) # fmt: skip @@ -348,7 +374,7 @@ def launch( scale_fake(rows, 2 * n) if cfg.d_col else None, fp8_fake((rows, n), (1, 0)) if cfg.h else None, scale_fake(rows, n) if cfg.h else None, - fake_tensor(cutlass.Float32, (rows,), (0,), 16), + fake_tensor(cutlass.Float32, (rows * n_slots,), (0,), 16), row_ends, alpha, prob, @@ -366,35 +392,33 @@ def launch( def _config(rows, k, n, num_experts, num_clusters, backward, scaling_mode, token_alignment, - device_layout, d_col, h, int64_offsets): # fmt: skip + device_layout, d_col, h, deterministic): # fmt: skip """Build a DispatchGemmConfig from the entry-point arguments.""" return DispatchGemmConfig( rows, k, n, num_experts, num_clusters, bool(backward), int(scaling_mode), token_alignment, - bool(device_layout), bool(d_col), bool(h), bool(int64_offsets), + bool(device_layout), bool(d_col), bool(h), bool(deterministic), ) # fmt: skip def get_ep_dispatch_gemm_workspace_layout( rows, k, n, num_experts, num_clusters, backward, scaling_mode=DELAYED_TENSOR_SCALING, - token_alignment=ROWS_PER_TILE, device_layout=False, d_col=True, h=True, - int64_offsets=False, + token_alignment=ROWS_PER_TILE, device_layout=False, d_col=True, h=True, deterministic=False, ): # fmt: skip """[total bytes, counter, signal, state] byte offsets of the workspace of this configuration.""" return list(workspace_layout(_config( rows, k, n, num_experts, num_clusters, backward, scaling_mode, token_alignment, device_layout, - d_col, h, int64_offsets, + d_col, h, deterministic, ))) # fmt: skip def get_ep_dispatch_gemm_function( fn_name, rows, k, n, num_experts, num_clusters, backward, scaling_mode=DELAYED_TENSOR_SCALING, - token_alignment=ROWS_PER_TILE, device_layout=False, d_col=True, h=True, - int64_offsets=False, + token_alignment=ROWS_PER_TILE, device_layout=False, d_col=True, h=True, deterministic=False, ) -> bool: # fmt: skip """Compile and register the GEMM of this configuration as ``fn_name``; return whether it is.""" cfg = _config( rows, k, n, num_experts, num_clusters, backward, scaling_mode, token_alignment, device_layout, - d_col, h, int64_offsets, + d_col, h, deterministic, ) # fmt: skip compile_fn = _COMPILERS[cfg.backward, cfg.mxfp8] return register_function(fn_name, lambda: compile_fn(cfg), "EP dispatch grouped GEMM") diff --git a/transformer_engine/common/CuTeDSL/ep_gemm/wgrad_gemm.py b/transformer_engine/common/CuTeDSL/ep_gemm/wgrad_gemm.py index cc9ed3a169f..bfae7f7c24f 100644 --- a/transformer_engine/common/CuTeDSL/ep_gemm/wgrad_gemm.py +++ b/transformer_engine/common/CuTeDSL/ep_gemm/wgrad_gemm.py @@ -7,7 +7,7 @@ ``weight_grad[e] = grad[rows of e]^T x[rows of e]`` per expert: ``grad`` [rows, m] and ``x`` [rows, n] BF16, or MXFP8 columnwise data with their GEMM-swizzled columnwise scales, ``weight_grad`` [experts, m, n] BF16 or FP32, written or added to. Operands: ``expert_row_ends`` -[experts] int32 (int64 with ``int64_offsets``), ``workspace`` uint8, stream. +[experts] int64, ``workspace`` uint8, stream. Each launch is a persistent grid that claims output tiles from an atomic counter in ``workspace``, so launches sharing one workspace split the tiles across SMs. It is a programmatic dependent of the @@ -31,7 +31,6 @@ fp8_fake, import_gemm_modules, is_sm107, - offsets_dtype, register_function, scale_fake, wide_bf16_wgrad_kernel, @@ -54,7 +53,6 @@ class WgradConfig: token_alignment: int = 0 # rows per expert slab are a multiple of it routed_tokens: int = 0 # rows a rank receives on average signal_unit_tokens: int = 0 # rows per dispatch flag the launch takes, 0: none - int64_offsets: bool = False # int64 instead of int32 expert row ends # Kernels, workspace layouts and compiled functions are specific to the device architecture. capability: tuple = field(default_factory=device_compute_capability) @@ -140,16 +138,16 @@ def build_kernel(cfg: WgradConfig): writes: the global-descriptor kernels let the kernel behind them start at entry and wait at exit; the others, which launch a helper kernel first, wait at start. A BF16 launch that waits on the dispatch flags instead starts beside the kernel before it and waits for it at exit.""" - common = dict( - acc_dtype=cutlass.Float32, - use_2cta_instrs=True, - mma_tiler_mn=MMA_TILER_MN, - cluster_shape_mn=CLUSTER_MN, - accumulate_on_output=cfg.accumulate, - expert_cnt=cfg.num_experts, - atomic_counter_claim=True, - use_pdl=True, - ) + common = { + "acc_dtype": cutlass.Float32, + "use_2cta_instrs": True, + "mma_tiler_mn": MMA_TILER_MN, + "cluster_shape_mn": CLUSTER_MN, + "accumulate_on_output": cfg.accumulate, + "expert_cnt": cfg.num_experts, + "atomic_counter_claim": True, + "use_pdl": True, + } if cfg.mxfp8: stock, _, _, moe_utils = _mxfp8_kernels() kernel_class = _global_descriptor_kernel(cfg) @@ -215,7 +213,7 @@ def views(grad, x, weight_grad): cutlass.Float32 if cfg.fp32_out else cutlass.BFloat16, (experts, m, n), (2, 1, 0), 16 ) tail = ( - fake_tensor(offsets_dtype(cfg.int64_offsets), (experts,), (0,), 16), + fake_tensor(cutlass.Int64, (experts,), (0,), 16), fake_tensor(cutlass.Uint8, (workspace_layout(cfg)[0],), (0,), 128), # Shared tile counter: launches into one workspace split one tile list. fake_tensor(cutlass.Int32, (1,), (0,), 16), @@ -282,40 +280,34 @@ def launch_signal(grad, x, weight_grad, expert_row_ends, workspace, counter, sig def _config( rows, m, n, num_experts, num_clusters, fp32_out, accumulate, wait_primary_at_start, signal_unit_tokens, scaling_mode, token_alignment, routed_tokens, - int64_offsets=False, ): # fmt: skip """Build a WgradConfig from the entry-point arguments. A launch with signal_unit_tokens takes the dispatch flags and waits on them per tile.""" return WgradConfig( rows, m, n, num_experts, num_clusters, bool(fp32_out), bool(accumulate), int(scaling_mode), bool(wait_primary_at_start), token_alignment, routed_tokens, int(signal_unit_tokens), - bool(int64_offsets), ) # fmt: skip def get_ep_wgrad_workspace_layout( rows, m, n, num_experts, num_clusters, fp32_out, accumulate, wait_primary_at_start, signal_unit_tokens, scaling_mode, token_alignment, routed_tokens, - int64_offsets=False, ): # fmt: skip """[total bytes, counter offset] of the workspace of this configuration.""" return list(workspace_layout(_config( rows, m, n, num_experts, num_clusters, fp32_out, accumulate, wait_primary_at_start, signal_unit_tokens, scaling_mode, token_alignment, routed_tokens, - int64_offsets, ))) # fmt: skip def get_ep_wgrad_function( fn_name, rows, m, n, num_experts, num_clusters, fp32_out, accumulate, wait_primary_at_start, signal_unit_tokens, scaling_mode, token_alignment, routed_tokens, - int64_offsets=False, ) -> bool: # fmt: skip """Compile and register the weight gradient of this configuration as ``fn_name``; return whether it is.""" cfg = _config( rows, m, n, num_experts, num_clusters, fp32_out, accumulate, wait_primary_at_start, signal_unit_tokens, scaling_mode, token_alignment, routed_tokens, - int64_offsets, ) # fmt: skip return register_function(fn_name, lambda: _compile(cfg), "EP weight-gradient grouped GEMM") diff --git a/transformer_engine/common/ep/ep_gemm_api.cpp b/transformer_engine/common/ep/ep_gemm_api.cpp index b80cdf8c8a9..ec225221c5d 100644 --- a/transformer_engine/common/ep/ep_gemm_api.cpp +++ b/transformer_engine/common/ep/ep_gemm_api.cpp @@ -11,8 +11,10 @@ #if defined(NVTE_WITH_NCCL_EP) && defined(NVTE_WITH_CUTEDSL) #include +#include #include +#include #include #include #include @@ -33,6 +35,10 @@ namespace ep = transformer_engine::ep; namespace { constexpr size_t kWorkspaceAlign = 128; +// What a missing CuTeDSL kernel needs. +constexpr const char* kCutedslNeeds = + "needs TE built with NVTE_WITH_CUTEDSL=1, NVTE_ENABLE_CUTEDSL_BACKEND=1, NVTE_MOE_OVERLAP=1, " + "the nvidia-cudnn-frontend package with the EP grouped GEMM kernels, and SM 10.0, 10.3 or 10.7"; using ep::check_ep_expert_token_offsets; using ep::check_ep_mxfp8_dims; using ep::ep_overlap_scaling_mode; @@ -81,11 +87,10 @@ struct EpGemmContext { int all_clusters; // clusters of every SM // max_recv_tokens_per_rank == 0: the caller sized the recv buffers with nvte_ep_prepare. bool eager; - // Rows the dispatch writes per readiness flag and the GEMM waits on, resolved in make_context. - size_t dispatch_signal_unit; size_t alignment() const { return layer_cfg.dispatch_output_per_expert_alignment; } - size_t signal_unit_tokens() const { return dispatch_signal_unit; } + // Rows the dispatch writes per readiness flag and the GEMM waits on. + size_t signal_unit_tokens() const { return alignment(); } }; // comm_sms: the group's SM count of the NCCL EP call that the entry point overlaps; the GEMM runs @@ -130,11 +135,17 @@ EpGemmContext make_context(const NVTEEpLayerConfig* layer_cfg, int NVTEEpSmConfi cfg, (sm_count - comm_sms_count) / static_cast(kClusterSize), sm_count / static_cast(kClusterSize), - group.max_recv_tokens_per_rank == 0, - alignment}; + group.max_recv_tokens_per_rank == 0}; return ctx; } +// A 2D tensor of the given shape. +void check_2d(const NVTETensor t, size_t rows, size_t cols, const char* name) { + const NVTEShape shape = nvte_tensor_shape(t); + NVTE_CHECK(shape.ndim == 2 && shape.data[0] == rows && shape.data[1] == cols, name, " must be [", + rows, ", ", cols, "]"); +} + // Rows: the group capacity, or any multiple of the flag rows in eager mode. void check_rows(const EpGemmContext& ctx, size_t rows, const char* name) { NVTE_CHECK(rows % ctx.signal_unit_tokens() == 0, name, " rows (", rows, @@ -155,8 +166,7 @@ bool dispatch_writes_layout(const EpGemmContext& ctx, size_t num_local_experts) // The forward combine_gemm GEMM of [rows, k] inputs and n output columns. ep::EpCombineGemmConfig combine_fwd_config(const EpGemmContext& ctx, size_t rows, size_t k, size_t n, size_t num_experts, - NVTEScalingMode scaling_mode, - bool int64_offsets = false) { + NVTEScalingMode scaling_mode) { return ep::EpCombineGemmConfig{rows, k, n, @@ -167,8 +177,7 @@ ep::EpCombineGemmConfig combine_fwd_config(const EpGemmContext& ctx, size_t rows false, scaling_mode, ctx.alignment(), - ctx.all_clusters, - int64_offsets}; + ctx.all_clusters}; } // Per-call scratch for the GEMM's readiness flags and state, sliced from the caller's workspace. @@ -179,17 +188,19 @@ struct ScratchLayout { size_t ones; // [rows] float32 of 1, the probability operand when the GEMM is unweighted size_t offsets; // [num_experts + 1] int64 element offsets of the MXFP8 requant grouped tensor size_t wgrad; // backward weight-gradient accumulation workspace, empty when no weight gradient - size_t total; // end offset: the bytes the caller must provide + size_t dprob_slots; // [rows, slots per row] float32 of a deterministic routing-weight gradient + size_t total; // end offset: the bytes the caller must provide }; ScratchLayout scratch_layout(size_t gemm_bytes, size_t num_experts, size_t rows, bool unit_probs, - size_t wgrad_bytes) { + size_t wgrad_bytes, size_t dprob_slots_bytes = 0) { ScratchLayout l; l.alpha = align_up(gemm_bytes); l.ones = l.alpha + align_up(sizeof(float) * num_experts); l.offsets = l.ones + (unit_probs ? align_up(sizeof(float) * rows) : 0); l.wgrad = l.offsets + align_up(sizeof(int64_t) * (num_experts + 1)); - l.total = l.wgrad + align_up(wgrad_bytes); + l.dprob_slots = l.wgrad + align_up(wgrad_bytes); + l.total = l.dprob_slots + align_up(dprob_slots_bytes); return l; } @@ -198,26 +209,31 @@ ScratchLayout scratch_layout(size_t gemm_bytes, size_t num_experts, size_t rows, struct GemmScratch { uint8_t* base; uint8_t* wgrad = nullptr; - void* layout = nullptr; // [num_experts + 1] int32 or int64 - bool int64_offsets = false; // layout dtype - float* alpha = nullptr; // [num_experts] - float* ones = nullptr; // [rows] - int64_t* offsets = nullptr; // [num_experts + 1] requant grouped-tensor element offsets - int32_t* signal = nullptr; // [signal_capacity] readiness flags + int64_t* layout = nullptr; // [num_experts + 1] + float* alpha = nullptr; // [num_experts] + float* ones = nullptr; // [rows] + float* dprob_slots = nullptr; // [rows * slots per row] deterministic routing-weight gradient + int64_t* offsets = nullptr; // [num_experts + 1] requant grouped-tensor element offsets + int32_t* signal = nullptr; // [signal_capacity] readiness flags int signal_capacity = 0; int num_experts = 0; ep::WorkspaceReset reset; }; GemmScratch claim_scratch(uint8_t* base, size_t workspace_bytes, size_t gemm_bytes, - size_t num_experts, size_t rows, bool unit_probs, size_t wgrad_bytes) { - const ScratchLayout l = scratch_layout(gemm_bytes, num_experts, rows, unit_probs, wgrad_bytes); + size_t num_experts, size_t rows, bool unit_probs, size_t wgrad_bytes, + size_t dprob_slots_bytes = 0) { + const ScratchLayout l = + scratch_layout(gemm_bytes, num_experts, rows, unit_probs, wgrad_bytes, dprob_slots_bytes); NVTE_CHECK(l.total <= workspace_bytes, "the EP overlap workspace needs ", l.total, " bytes, got ", workspace_bytes, "; size it with nvte_ep_overlap_prepare"); GemmScratch scratch{base}; if (wgrad_bytes > 0) { scratch.wgrad = base + l.wgrad; } + if (dprob_slots_bytes > 0) { + scratch.dprob_slots = reinterpret_cast(base + l.dprob_slots); + } scratch.alpha = reinterpret_cast(base + l.alpha); scratch.offsets = reinterpret_cast(base + l.offsets); scratch.num_experts = static_cast(num_experts); @@ -262,32 +278,22 @@ void set_chunk_words(GemmScratch& scratch, const ep::WorkspaceLayout& layout, si } // The caller's expert layout the GEMMs read, checked by check_ep_expert_token_offsets. -void set_layout(GemmScratch& scratch, NVTETensor expert_token_offsets, bool int64_offsets) { - scratch.layout = nvte_tensor_data(expert_token_offsets); - scratch.int64_offsets = int64_offsets; +void set_layout(GemmScratch& scratch, NVTETensor expert_token_offsets) { + scratch.layout = static_cast(nvte_tensor_data(expert_token_offsets)); scratch.reset.layout = scratch.layout; - scratch.reset.layout_int64 = int64_offsets; scratch.reset.num_experts = scratch.num_experts; } -// Bytes of one layout entry. -size_t layout_entry_bytes(const GemmScratch& scratch) { - return scratch.int64_offsets ? sizeof(int64_t) : sizeof(int32_t); -} - // The per-expert row ends operand: the layout past expert 0's start. DLTensorWrapper wrap_row_ends(const GemmScratch& scratch) { - return wrap_raw(static_cast(scratch.layout) + layout_entry_bytes(scratch), - scratch.int64_offsets ? kNVTEInt64 : kNVTEInt32, scratch.num_experts); + return wrap_raw(scratch.layout + 1, kNVTEInt64, scratch.num_experts); } // Compiled GEMM and workspace layout of a configuration. template tvm::ffi::Function get_gemm(const Config& config, ep::WorkspaceLayout* layout) { auto kernel = config.get_kernel(); - NVTE_CHECK(kernel.has_value(), - "the EP grouped GEMM is not available: needs NVTE_ENABLE_CUTEDSL_BACKEND=1, " - "NVTE_MOE_OVERLAP=1 and SM 10.0, 10.3 or 10.7"); + NVTE_CHECK(kernel.has_value(), "the EP grouped GEMM is not available: ", kCutedslNeeds); const auto offsets = config.workspace_layout(); NVTE_CHECK(offsets.has_value(), "cannot query the GEMM workspace layout"); *layout = *offsets; @@ -323,7 +329,7 @@ struct Wgrad { std::optional make_wgrad(const EpGemmContext& ctx, NVTETensor grad, NVTETensor x, NVTETensor weight_grad, bool accumulate, size_t rows, size_t num_experts, NVTEScalingMode scaling_mode, - bool int64_offsets, size_t signal_unit_tokens = 0) { + size_t signal_unit_tokens = 0) { const bool mxfp8 = transformer_engine::is_mxfp8_scaling(scaling_mode); if (weight_grad == nullptr) { NVTE_CHECK(x == nullptr, "wgrad_input needs weight_grad"); @@ -375,7 +381,7 @@ std::optional make_wgrad(const EpGemmContext& ctx, NVTETensor grad, NVTET x, weight_grad, {rows, m, n, num_experts, 1, out_type == kNVTEFloat32, accumulate, false, - signal_unit_tokens, scaling_mode, ctx.alignment(), routed_tokens, int64_offsets}, + signal_unit_tokens, scaling_mode, ctx.alignment(), routed_tokens}, {}}; const auto layout = wgrad.config.workspace_layout(); NVTE_CHECK(layout.has_value(), "cannot query the weight-gradient workspace layout"); @@ -457,9 +463,7 @@ void launch_requant(NVTETensor t, const GemmScratch& scratch, size_t rows, size_ GroupedTensor* const out = convertNVTEGroupedTensorCheck(output.data()); const bool ok = cutedsl_backend::mxfp8_requantize_cutedsl(*in, out, nullptr, stream, /*force_warp_tile=*/true); - NVTE_CHECK(ok, - "the EP MXFP8 requant is not available: needs NVTE_ENABLE_CUTEDSL_BACKEND=1, " - "NVTE_MOE_OVERLAP=1 and SM 10.0, 10.3 or 10.7"); + NVTE_CHECK(ok, "the EP MXFP8 requant is not available: ", kCutedslNeeds); } // Bytes of the chained weight-gradient workspace of a backward GEMM over num_experts slabs of @@ -469,6 +473,7 @@ size_t wgrad_workspace_bytes(const EpGemmContext& ctx, size_t rows, size_t m, si const size_t routed_tokens = static_cast(ctx.group.max_tokens_per_rank) * ctx.layer_cfg.top_k; size_t bytes = 0; + std::string skipped; // why the last variant was left out for (const bool fp32_out : {false, true}) { const ep::EpWgradConfig config{rows, m, @@ -483,17 +488,22 @@ size_t wgrad_workspace_bytes(const EpGemmContext& ctx, size_t rows, size_t m, si ctx.alignment(), routed_tokens}; // The output precision is not known here, so size over both. A variant the device does not - // support (e.g. the SM 10.7 FP32 MXFP8 weight gradient at or below 256 rows) throws while - // building its kernel; skip it rather than failing the sizing of a supported call. + // support (e.g. the SM 10.7 FP32 MXFP8 weight gradient at or below 256 rows) is rejected with + // a TVM-FFI error while building its kernel; skip it rather than failing the sizing of a + // supported call. try { const auto layout = config.workspace_layout(); if (layout.has_value()) { bytes = std::max(bytes, layout->total_bytes); + } else { + skipped = "its workspace layout is not available"; } - } catch (...) { - // An unsupported output precision is simply left out of the workspace sizing. + } catch (const tvm::ffi::Error& e) { + skipped = e.message(); } } + NVTE_CHECK(bytes > 0, "no EP weight-gradient GEMM supports weight gradients of [", m, ", ", n, + "]: ", skipped); return bytes; } @@ -501,9 +511,7 @@ size_t wgrad_workspace_bytes(const EpGemmContext& ctx, size_t rows, size_t m, si template size_t gemm_workspace_bytes(const Config& config) { const auto layout = config.workspace_layout(); - NVTE_CHECK(layout.has_value(), - "the EP grouped GEMM is not available: needs NVTE_ENABLE_CUTEDSL_BACKEND=1, " - "NVTE_MOE_OVERLAP=1 and SM 10.0, 10.3 or 10.7"); + NVTE_CHECK(layout.has_value(), "the EP grouped GEMM is not available: ", kCutedslNeeds); return layout->total_bytes; } @@ -525,9 +533,11 @@ size_t nvte_ep_overlap_prepare(size_t hidden_dim, size_t ffn_dim, size_t num_loc size_t need = 0; // Largest scratch of a call whose GEMM uses `config`; unit_probs sizes the per-row ones buffer // and wgrad the weight-gradient workspace. - const auto consider = [&](const auto& config, bool unit_probs, size_t wgrad) { - need = std::max( - need, scratch_layout(gemm_workspace_bytes(config), ne, rows, unit_probs, wgrad).total); + const auto consider = [&](const auto& config, bool unit_probs, size_t wgrad, + size_t dprob_slots_bytes = 0) { + need = std::max(need, scratch_layout(gemm_workspace_bytes(config), ne, rows, unit_probs, wgrad, + dprob_slots_bytes) + .total); }; // Forward dispatch: FC1 + SwiGLU, no weight gradient. @@ -546,9 +556,13 @@ size_t nvte_ep_overlap_prepare(size_t hidden_dim, size_t ffn_dim, size_t num_loc { const EpGemmContext ctx = make_context(layer_cfg, &NVTEEpSmConfig::dispatch_bwd_num_sms); const size_t wgrad = wg ? wgrad_workspace_bytes(ctx, rows, hidden_dim, ffn_dim, ne, mx) : 0; - consider(ep::EpDispatchGemmConfig{rows, hidden_dim, ffn_dim, ne, ctx.num_clusters, true, mx, - ctx.alignment()}, - false, wgrad); + // The slots of a deterministic routing-weight gradient are sized for every call, so the + // workspace fits either mode. + ep::EpDispatchGemmConfig config{rows, hidden_dim, ffn_dim, ne, ctx.num_clusters, + true, mx, ctx.alignment()}; + config.deterministic = ctx.layer_cfg.allow_nondeterministic == 0; + const size_t slots_bytes = rows * ep::dprob_slots_per_row(ffn_dim) * sizeof(float); + consider(config, false, wgrad, slots_bytes); } // Backward dispatch: FC1 dgrad, with the FC1 weight gradient [2 * ffn, hidden]. { @@ -582,23 +596,29 @@ void nvte_ep_dispatch_gemm_fwd(NVTETensor handle_mem, const NVTETensor topk_idx, checkCuDriverContext(stream); const auto [ws_base, ws_bytes] = workspace_span(workspace); + NVTE_CHECK(nvte_tensor_shape(tokens).ndim == 2 && nvte_tensor_shape(recv_tokens).ndim == 2 && + nvte_tensor_shape(weight).ndim == 3, + "tokens and recv_tokens must be 2D and weight [num_local_experts, 2 * ffn_dim, " + "hidden_dim]"); const size_t rows = nvte_tensor_shape(recv_tokens).data[0]; const size_t hidden = nvte_tensor_shape(tokens).data[1]; const size_t num_experts = nvte_tensor_shape(weight).data[0]; const size_t n = nvte_tensor_shape(weight).data[1]; check_rows(ctx, rows, "recv_tokens"); + NVTE_CHECK(nvte_tensor_shape(weight).data[2] == hidden && + nvte_tensor_shape(recv_tokens).data[1] == hidden, + "weight columns and recv_tokens columns must equal the tokens columns (", hidden, ")"); NVTE_CHECK(num_experts * ctx.group.ep_size == static_cast(ctx.group.num_experts), "weight has ", num_experts, " experts, expected num_experts / ep_size = ", ctx.group.num_experts / ctx.group.ep_size); - NVTE_CHECK(nvte_tensor_shape(act_out).data[1] * 2 == n, "weight rows (", n, - ") must be 2 * the act_out columns: SwiGLU"); - const bool int64_offsets = - check_ep_expert_token_offsets(expert_token_offsets, num_experts, recv_tokens_per_expert); - const NVTEDType offsets_type = int64_offsets ? kNVTEInt64 : kNVTEInt32; + NVTE_CHECK(n % 2 == 0, "weight rows (", n, ") must be 2 * the act_out columns: SwiGLU"); + check_2d(act_out, rows, n / 2, "act_out"); + check_2d(gemm_out, rows, n, "gemm_out"); + check_ep_expert_token_offsets(expert_token_offsets, num_experts, recv_tokens_per_expert); check_vector(recv_topk_weights, rows, kNVTEFloat32, "recv_topk_weights"); NVTE_CHECK(total_recv_tokens == nullptr || (nvte_tensor_numel(total_recv_tokens) == 1 && - nvte_tensor_type(total_recv_tokens) == offsets_type), - "total_recv_tokens must be a tensor of 1 element of the expert_token_offsets dtype"); + nvte_tensor_type(total_recv_tokens) == kNVTEInt64), + "total_recv_tokens must be an int64 tensor of 1 element"); const NVTEScalingMode scaling_mode = ep_overlap_scaling_mode(tokens); const bool mxfp8 = scaling_mode == NVTE_MXFP8_1D_SCALING; if (mxfp8) { @@ -607,7 +627,7 @@ void nvte_ep_dispatch_gemm_fwd(NVTETensor handle_mem, const NVTETensor topk_idx, check_mxfp8(weight, true, "weight"); check_mxfp8(act_out, true, "act_out"); NVTE_CHECK(nvte_tensor_type(gemm_out) == kNVTEBFloat16, "gemm_out must be bfloat16"); - check_ep_mxfp8_dims(hidden, n / 2, ctx.alignment()); + check_ep_mxfp8_dims(hidden, n / 2); } else { NVTE_CHECK( nvte_tensor_type(tokens) == kNVTEBFloat16 && nvte_tensor_type(weight) == kNVTEBFloat16, @@ -623,7 +643,6 @@ void nvte_ep_dispatch_gemm_fwd(NVTETensor handle_mem, const NVTETensor topk_idx, ep::EpDispatchGemmConfig config{rows, hidden, n, num_experts, ctx.num_clusters, false, scaling_mode, ctx.alignment(), device_layout}; - config.int64_offsets = int64_offsets; std::vector gemms{get_gemm(config, &layout)}; const int tail_clusters = ctx.all_clusters - ctx.num_clusters; if (tail_clusters > 0) { @@ -633,10 +652,8 @@ void nvte_ep_dispatch_gemm_fwd(NVTETensor handle_mem, const NVTETensor topk_idx, claim_scratch(ws_base, ws_bytes, layout.total_bytes, num_experts, rows, false, 0); set_signal_words(scratch, layout, rows / ctx.signal_unit_tokens()); // NCCL EP writes the expert starts, layout[0, num_experts), and the padded counts. - set_layout(scratch, expert_token_offsets, int64_offsets); - const size_t entry_bytes = layout_entry_bytes(scratch); - TensorWrapper offsets(scratch.layout, std::vector{num_experts}, - static_cast(offsets_type)); + set_layout(scratch, expert_token_offsets); + TensorWrapper offsets(scratch.layout, std::vector{num_experts}, DType::kInt64); // The dispatch publishes one flag per slot of rows; the GEMM behind it consumes ready tiles. TensorWrapper signal(scratch.signal, @@ -648,11 +665,10 @@ void nvte_ep_dispatch_gemm_fwd(NVTETensor handle_mem, const NVTETensor topk_idx, // Flags, scheduler state and unset layout entries, before the dispatch that sets them. The // fused dispatch writes the starts and the padded counts in one scan, and the num total recv // tokens after them, final as it does not run with drops. - scratch.reset.fill(scratch.layout, static_cast((num_experts + 1) * entry_bytes / 4), + scratch.reset.fill(scratch.layout, static_cast((num_experts + 1) * 2), ep::kFillMinusOne); // in int32 words ep::reset_workspace(scratch.reset, stream); - TensorWrapper total(static_cast(scratch.layout) + num_experts * entry_bytes, - std::vector{1}, static_cast(offsets_type)); + TensorWrapper total(scratch.layout + num_experts, std::vector{1}, DType::kInt64); ctx.backend.prepare_and_dispatch(handle_mem, topk_idx, tokens, tokens_win, topk_weights, no_window, recv_tokens, no_window, recv_topk_weights, no_window, recv_tokens_per_expert, total.data(), @@ -665,7 +681,7 @@ void nvte_ep_dispatch_gemm_fwd(NVTETensor handle_mem, const NVTETensor topk_idx, } // Flags, scheduler state and the final post-drop num total recv tokens, from NCCL EP's // post-drop starts and counts, before the dispatch that sets the flags. - scratch.reset.counts = nvte_tensor_data(recv_tokens_per_expert); + scratch.reset.counts = static_cast(nvte_tensor_data(recv_tokens_per_expert)); ep::reset_workspace(scratch.reset, stream); ctx.backend.dispatch(handle_mem, topk_idx, tokens, tokens_win, topk_weights, no_window, recv_tokens, no_window, recv_topk_weights, no_window, &dispatch_signal, @@ -699,10 +715,9 @@ void nvte_ep_dispatch_gemm_fwd(NVTETensor handle_mem, const NVTETensor topk_idx, // The layout the dispatch wrote ends in the recv total; no row drops in this mode. It follows // the GEMM launches so that it does not sit between the dispatch and its programmatic dependent. if (device_layout && total_recv_tokens != nullptr) { - NVTE_CHECK_CUDA( - cudaMemcpyAsync(nvte_tensor_data(total_recv_tokens), - static_cast(scratch.layout) + num_experts * entry_bytes, - entry_bytes, cudaMemcpyDefault, stream)); + NVTE_CHECK_CUDA(cudaMemcpyAsync(nvte_tensor_data(total_recv_tokens), + scratch.layout + num_experts, sizeof(int64_t), + cudaMemcpyDefault, stream)); } } @@ -717,24 +732,29 @@ void nvte_ep_combine_gemm_fwd(NVTETensor handle_mem, const NVTETensor gemm_in, checkCuDriverContext(stream); const auto [ws_base, ws_bytes] = workspace_span(workspace); + NVTE_CHECK(nvte_tensor_shape(gemm_in).ndim == 2 && nvte_tensor_shape(weight).ndim == 3, + "gemm_in must be 2D and weight [num_local_experts, hidden_dim, ffn_dim]"); const size_t rows = nvte_tensor_shape(gemm_in).data[0]; const size_t k = nvte_tensor_shape(gemm_in).data[1]; const size_t num_experts = nvte_tensor_shape(weight).data[0]; const size_t n = nvte_tensor_shape(weight).data[1]; check_rows(ctx, rows, "gemm_in"); NVTE_CHECK(nvte_tensor_shape(weight).data[2] == k, "weight columns must equal gemm_in columns"); + check_2d(expert_out, rows, n, "expert_out"); + NVTE_CHECK(nvte_tensor_shape(result).ndim == 2 && nvte_tensor_shape(result).data[1] == n, + "result must be [T, ", n, "]"); const NVTEScalingMode scaling_mode = ep_overlap_scaling_mode(gemm_in); const bool mxfp8 = scaling_mode == NVTE_MXFP8_1D_SCALING; if (mxfp8) { check_mxfp8(gemm_in, true, "gemm_in"); check_mxfp8(weight, true, "weight"); - check_ep_mxfp8_dims(n, k, ctx.alignment()); + check_ep_mxfp8_dims(n, k); } else { NVTE_CHECK( nvte_tensor_type(gemm_in) == kNVTEBFloat16 && nvte_tensor_type(weight) == kNVTEBFloat16, "gemm_in and weight must be bfloat16 or MXFP8"); } - const bool int64_offsets = check_ep_expert_token_offsets(expert_token_offsets, num_experts); + check_ep_expert_token_offsets(expert_token_offsets, num_experts); const bool weighted = recv_topk_weights != nullptr; NVTE_CHECK(!weighted || (nvte_tensor_type(recv_topk_weights) == kNVTEFloat32 && nvte_tensor_numel(recv_topk_weights) == rows), @@ -744,7 +764,7 @@ void nvte_ep_combine_gemm_fwd(NVTETensor handle_mem, const NVTETensor gemm_in, // first chunk and leave their SMs to the combine. ep::WorkspaceLayout layout; const ep::EpCombineGemmConfig config = - combine_fwd_config(ctx, rows, k, n, num_experts, scaling_mode, int64_offsets); + combine_fwd_config(ctx, rows, k, n, num_experts, scaling_mode); const size_t n_chunk = config.n_chunk; const tvm::ffi::Function gemm = get_gemm(config, &layout); // Own workspace for the signal, scheduler and alpha words; the expert layout is the caller's @@ -752,7 +772,7 @@ void nvte_ep_combine_gemm_fwd(NVTETensor handle_mem, const NVTETensor gemm_in, GemmScratch scratch = claim_scratch(ws_base, ws_bytes, layout.total_bytes, num_experts, rows, !weighted, 0); set_chunk_words(scratch, layout, DIVUP(n, n_chunk), layout.signal); - set_layout(scratch, expert_token_offsets, int64_offsets); + set_layout(scratch, expert_token_offsets); ep::reset_workspace(scratch.reset, stream); // The GEMM fills the flags; the combine is its programmatic dependent. @@ -795,15 +815,20 @@ void nvte_ep_combine_gemm_bwd( checkCuDriverContext(stream); const auto [ws_base, ws_bytes] = workspace_span(workspace); + NVTE_CHECK(nvte_tensor_shape(grad_expert_out).ndim == 2 && nvte_tensor_shape(weight).ndim == 3, + "grad_expert_out must be 2D and weight [num_local_experts, hidden_dim, ffn_dim]"); const size_t rows = nvte_tensor_shape(grad_expert_out).data[0]; const size_t hidden = nvte_tensor_shape(grad_expert_out).data[1]; const size_t num_experts = nvte_tensor_shape(weight).data[0]; const size_t ffn = nvte_tensor_shape(weight).data[2]; check_rows(ctx, rows, "grad_expert_out"); - NVTE_CHECK(nvte_tensor_shape(weight).data[1] == hidden && - nvte_tensor_shape(gemm_out).data[1] == 2 * ffn && - nvte_tensor_shape(grad_gemm_out).data[1] == 2 * ffn, - "weight must be [experts, hidden, ffn] with 2 * ffn the gemm_out columns: SwiGLU"); + NVTE_CHECK(nvte_tensor_shape(weight).data[1] == hidden, + "weight must be [experts, hidden, ffn] with hidden the grad_expert_out columns"); + check_2d(gemm_out, rows, 2 * ffn, "gemm_out"); + check_2d(grad_gemm_out, rows, 2 * ffn, "grad_gemm_out"); + NVTE_CHECK( + nvte_tensor_shape(grad_result).ndim == 2 && nvte_tensor_shape(grad_result).data[1] == hidden, + "grad_result must be [T, ", hidden, "]"); NVTE_CHECK(nvte_tensor_type(gemm_out) == kNVTEBFloat16, "gemm_out must be bfloat16"); const NVTEScalingMode scaling_mode = ep_overlap_scaling_mode(grad_result); const bool mxfp8 = scaling_mode == NVTE_MXFP8_1D_SCALING; @@ -818,14 +843,14 @@ void nvte_ep_combine_gemm_bwd( } NVTE_CHECK(act_out != nullptr || weight_grad == nullptr, "the MXFP8 weight gradient reads the act_out this call writes"); - check_ep_mxfp8_dims(hidden, ffn, ctx.alignment()); + check_ep_mxfp8_dims(hidden, ffn); } else { NVTE_CHECK( nvte_tensor_type(grad_result) == kNVTEBFloat16 && nvte_tensor_type(weight) == kNVTEBFloat16, "grad_result and weight must be bfloat16 or MXFP8"); NVTE_CHECK(act_out == nullptr, "act_out is written for MXFP8 only"); } - const bool int64_offsets = check_ep_expert_token_offsets(expert_token_offsets, num_experts); + check_ep_expert_token_offsets(expert_token_offsets, num_experts); check_vector(recv_topk_weights, rows, kNVTEFloat32, "recv_topk_weights"); check_vector(grad_recv_topk_weights, rows, kNVTEFloat32, "grad_recv_topk_weights"); @@ -838,7 +863,7 @@ void nvte_ep_combine_gemm_bwd( const size_t wgrad_signal_tokens = mxfp8 ? 0 : ctx.signal_unit_tokens(); const std::optional wgrad = make_wgrad(ctx, grad_expert_out, wgrad_input, weight_grad, accumulate_weight_grad, rows, - num_experts, scaling_mode, int64_offsets, wgrad_signal_tokens); + num_experts, scaling_mode, wgrad_signal_tokens); ep::WorkspaceLayout layout; ep::EpDispatchGemmConfig config{ @@ -847,18 +872,31 @@ void nvte_ep_combine_gemm_bwd( config.d_col = mxfp8 && nvte_get_tensor_param(grad_gemm_out, kNVTEColumnwiseData).data_ptr != nullptr; config.h = act_out != nullptr; - config.int64_offsets = int64_offsets; - const tvm::ffi::Function gemm = get_gemm(config, &layout); - GemmScratch scratch = claim_scratch(ws_base, ws_bytes, layout.total_bytes, num_experts, rows, - false, wgrad ? wgrad->layout.total_bytes : 0); + // The GEMM writes each row's routing-weight gradient into one slot per output tile, which a + // kernel after the weight gradient sums in a fixed order; or adds it atomically. + config.deterministic = ctx.layer_cfg.allow_nondeterministic == 0; + const size_t dprob_slots_per_row = ep::dprob_slots_per_row(ffn); + NVTE_CHECK(rows * dprob_slots_per_row <= static_cast(INT_MAX), + "too many routing-weight gradient slots: ", rows, " x ", dprob_slots_per_row); + const size_t dprob_slots_bytes = + config.deterministic ? rows * dprob_slots_per_row * sizeof(float) : 0; + tvm::ffi::Function gemm = get_gemm(config, &layout); + GemmScratch scratch = + claim_scratch(ws_base, ws_bytes, layout.total_bytes, num_experts, rows, false, + wgrad ? wgrad->layout.total_bytes : 0, dprob_slots_bytes); set_signal_words(scratch, layout, rows / ctx.signal_unit_tokens()); if (wgrad) { scratch.reset.fill(scratch.wgrad + wgrad->layout.counter, 1, ep::kFillZero); } - // The GEMM adds each row's routing-weight gradient into grad_recv_topk_weights. - scratch.reset.fill(nvte_tensor_data(grad_recv_topk_weights), static_cast(rows), - ep::kFillZero); - set_layout(scratch, expert_token_offsets, int64_offsets); + if (config.deterministic) { + scratch.reset.fill(scratch.dprob_slots, static_cast(rows * dprob_slots_per_row), + ep::kFillZero); + } else { + // The GEMM adds each row's routing-weight gradient into grad_recv_topk_weights. + scratch.reset.fill(nvte_tensor_data(grad_recv_topk_weights), static_cast(rows), + ep::kFillZero); + } + set_layout(scratch, expert_token_offsets); if (requant) { scratch.reset.offsets = scratch.offsets; scratch.reset.offsets_cols = static_cast(hidden); @@ -878,7 +916,17 @@ void nvte_ep_combine_gemm_bwd( auto a = wrap_rowwise(grad_expert_out, true); auto c = wrap_rowwise(gemm_out, true); auto d = wrap_rowwise(grad_gemm_out, true); - auto dprob = wrap_rowwise(grad_recv_topk_weights, false); + auto dprob = config.deterministic + ? wrap_raw(scratch.dprob_slots, kNVTEFloat32, rows * dprob_slots_per_row) + : wrap_rowwise(grad_recv_topk_weights, false); + // Sums the slots once the GEMM and its tail complete: stream order, after everything launched. + const auto reduce_dprob = [&] { + if (config.deterministic) { + ep::reduce_dprob_slots(scratch.dprob_slots, + static_cast(nvte_tensor_data(grad_recv_topk_weights)), + static_cast(rows), static_cast(dprob_slots_per_row), stream); + } + }; auto row_ends = wrap_row_ends(scratch); auto alpha = wrap_raw(scratch.alpha, kNVTEFloat32, num_experts); auto prob = wrap_rowwise(recv_topk_weights, false); @@ -925,6 +973,7 @@ void nvte_ep_combine_gemm_bwd( launch_wgrad(*wgrad, scratch, base_clusters, true, 0, stream); launch_wgrad(*wgrad, scratch, ctx.all_clusters - base_clusters, false, 0, stream); } + reduce_dprob(); return; } auto b = wrap_rowwise(weight, false); @@ -934,6 +983,7 @@ void nvte_ep_combine_gemm_bwd( if (wgrad) { launch_wgrad(*wgrad, scratch, ctx.all_clusters, true, wgrad_signal_tokens, stream); } + reduce_dprob(); } void nvte_ep_dispatch_gemm_bwd(NVTETensor handle_mem, const NVTETensor grad_gemm_out, @@ -950,6 +1000,11 @@ void nvte_ep_dispatch_gemm_bwd(NVTETensor handle_mem, const NVTETensor grad_gemm checkCuDriverContext(stream); const auto [ws_base, ws_bytes] = workspace_span(workspace); + NVTE_CHECK(nvte_tensor_shape(grad_gemm_out).ndim == 2 && + nvte_tensor_shape(grad_recv_tokens).ndim == 2 && + nvte_tensor_shape(weight).ndim == 3, + "grad_gemm_out and grad_recv_tokens must be 2D and weight [num_local_experts, " + "2 * ffn_dim, hidden_dim]"); const size_t rows = nvte_tensor_shape(grad_gemm_out).data[0]; const size_t k = nvte_tensor_shape(grad_gemm_out).data[1]; const size_t hidden = nvte_tensor_shape(grad_recv_tokens).data[1]; @@ -957,7 +1012,11 @@ void nvte_ep_dispatch_gemm_bwd(NVTETensor handle_mem, const NVTETensor grad_gemm check_rows(ctx, rows, "grad_gemm_out"); NVTE_CHECK(nvte_tensor_shape(weight).data[1] == k && nvte_tensor_shape(weight).data[2] == hidden, "weight must be [experts, 2 * ffn, hidden]"); - const bool int64_offsets = check_ep_expert_token_offsets(expert_token_offsets, num_experts); + check_2d(grad_recv_tokens, rows, hidden, "grad_recv_tokens"); + NVTE_CHECK( + nvte_tensor_shape(grad_tokens).ndim == 2 && nvte_tensor_shape(grad_tokens).data[1] == hidden, + "grad_tokens must be [T, ", hidden, "]"); + check_ep_expert_token_offsets(expert_token_offsets, num_experts); check_vector(grad_recv_topk_weights, rows, kNVTEFloat32, "grad_recv_topk_weights"); const NVTEScalingMode scaling_mode = ep_overlap_scaling_mode(grad_gemm_out); const bool mxfp8 = scaling_mode == NVTE_MXFP8_1D_SCALING; @@ -966,7 +1025,7 @@ void nvte_ep_dispatch_gemm_bwd(NVTETensor handle_mem, const NVTETensor grad_gemm check_mxfp8(weight, true, "weight"); NVTE_CHECK(nvte_tensor_type(grad_recv_tokens) == kNVTEBFloat16, "grad_recv_tokens must be bfloat16"); - check_ep_mxfp8_dims(hidden, k / 2, ctx.alignment()); + check_ep_mxfp8_dims(hidden, k / 2); } else { NVTE_CHECK(nvte_tensor_type(grad_gemm_out) == kNVTEBFloat16 && nvte_tensor_type(weight) == kNVTEBFloat16, @@ -974,7 +1033,7 @@ void nvte_ep_dispatch_gemm_bwd(NVTETensor handle_mem, const NVTETensor grad_gemm } const std::optional wgrad = make_wgrad(ctx, grad_gemm_out, wgrad_input, weight_grad, accumulate_weight_grad, rows, - num_experts, scaling_mode, int64_offsets); + num_experts, scaling_mode); // MXFP8: the call writes the columnwise wgrad_input from its rowwise data when that is set. const bool requant = wgrad && mxfp8 && nvte_get_tensor_param(wgrad_input, kNVTERowwiseData).data_ptr != nullptr; @@ -992,7 +1051,6 @@ void nvte_ep_dispatch_gemm_bwd(NVTETensor handle_mem, const NVTETensor grad_gemm ep::EpCombineGemmConfig config{ rows, k, hidden, num_experts, wgrad ? ctx.all_clusters : ctx.num_clusters, n_chunk, !plain, true, scaling_mode, ctx.alignment()}; - config.int64_offsets = int64_offsets; const tvm::ffi::Function gemm = get_gemm(config, &layout); GemmScratch scratch = claim_scratch(ws_base, ws_bytes, layout.total_bytes, num_experts, rows, true, wgrad ? wgrad->layout.total_bytes : 0); @@ -1001,7 +1059,7 @@ void nvte_ep_dispatch_gemm_bwd(NVTETensor handle_mem, const NVTETensor grad_gemm if (wgrad) { scratch.reset.fill(scratch.wgrad + wgrad->layout.counter, 1, ep::kFillZero); } - set_layout(scratch, expert_token_offsets, int64_offsets); + set_layout(scratch, expert_token_offsets); if (requant) { scratch.reset.offsets = scratch.offsets; scratch.reset.offsets_cols = static_cast(hidden); diff --git a/transformer_engine/common/ep/ep_gemm_config.h b/transformer_engine/common/ep/ep_gemm_config.h index 80a0a9ea049..33ff6e52bb5 100644 --- a/transformer_engine/common/ep/ep_gemm_config.h +++ b/transformer_engine/common/ep/ep_gemm_config.h @@ -27,16 +27,24 @@ namespace transformer_engine { namespace ep { -// Rows per GEMM M tile (cluster tile M). Smaller expert alignments end an expert in a tail tile. +// Rows per GEMM M tile (cluster tile M); the expert alignment equals it. constexpr size_t kRowsPerTile = 256; // GEMM CTA tile N; combine readiness flags cover a multiple of it. constexpr size_t kTileN = 256; constexpr size_t kClusterSize = 2; +// Cluster extent along N, as CLUSTER_MN[1] of CuTeDSL/ep_gemm/_loader.py. +constexpr size_t kClusterTileN = 1; + +// FP32 slots per row of the deterministic routing-weight gradient of a GEMM with n columns: one per +// N tile, as dprob_n_slots of CuTeDSL/ep_gemm/_loader.py (tiles are scheduled per cluster). +inline size_t dprob_slots_per_row(size_t n) { + const size_t cluster_cols = kTileN * kClusterTileN; + return (n + cluster_cols - 1) / cluster_cols * kClusterTileN; +} -// MXFP8 GEMM shape requirements: hidden and ffn dims, and the smallest expert row alignment. +// MXFP8 GEMM shape requirements: hidden and ffn dims. constexpr size_t kMxfp8HiddenMultiple = 512; constexpr size_t kMxfp8FfnMultiple = 256; -constexpr size_t kMxfp8MinAlignment = 128; // Signal-aware grouped GEMMs (CuTeDSL via TVM-FFI), keyed by configuration. The first // get_kernel of a configuration compiles: call it at warmup, outside graph capture. @@ -61,6 +69,9 @@ class KeyedCache { static KeyedCache &create() { return *new KeyedCache(); } // The value of key, from make() on a miss. A missing value is cached only with cache_missing. + // make() runs unlocked: it calls into Python and may compile. Threads missing the same key may + // each run it, which is harmless as registering a compiled function overrides; the first value + // stored wins. template std::optional get(const std::string &key, Make &&make, bool cache_missing = false) { { @@ -70,14 +81,10 @@ class KeyedCache { return it->second; } } - std::unique_lock lock(mutex_); - auto it = map_.find(key); - if (it != map_.end()) { - return it->second; - } std::optional value = make(); if (value.has_value() || cache_missing) { - map_.emplace(key, value); + std::unique_lock lock(mutex_); + return map_.emplace(key, value).first->second; } return value; } @@ -104,9 +111,11 @@ std::optional get_cached_kernel(const Config &config) { return central.load_tvm_ffi_function(config); } static auto &cache = KeyedCache::create(); + // A failed compile throws and is not cached. A missing kernel is cached once TVM-FFI is loaded: + // it means the device is unsupported. return cache.get( config.to_key(), [&] { return central.load_tvm_ffi_function(config); }, - /*cache_missing=*/true); + /*cache_missing=*/central.get_tvm_ffi_available()); } // Calls the global function `name` with the configuration's arguments, prefixed by `prefix`. @@ -178,7 +187,8 @@ struct EpDispatchGemmConfig { // second GEMM. bool d_col = true; bool h = true; - bool int64_offsets = false; // the row ends are int64 instead of int32 + // Backward: the routing-weight gradient in per-tile slots, summed in a fixed order afterwards. + bool deterministic = false; bool is_mxfp8() const { return scaling_mode == NVTE_MXFP8_1D_SCALING; } @@ -188,7 +198,7 @@ struct EpDispatchGemmConfig { static_cast(n), static_cast(num_experts), num_clusters, backward, static_cast(scaling_mode), static_cast(token_alignment), device_layout, d_col, h, - int64_offsets); + deterministic); } std::string to_key() const { return config_key("ep_dispatch_gemm", args()); } @@ -219,7 +229,6 @@ struct EpCombineGemmConfig { size_t token_alignment; // rows per expert slab are a multiple of it // Clusters launched, 0: num_clusters. Those past num_clusters stop after the first chunk. int grid_clusters = 0; - bool int64_offsets = false; // the row ends are int64 instead of int32 bool is_mxfp8() const { return scaling_mode == NVTE_MXFP8_1D_SCALING; } @@ -229,7 +238,7 @@ struct EpCombineGemmConfig { static_cast(n), static_cast(num_experts), num_clusters, static_cast(n_chunk), dependents_at_entry, backward, static_cast(scaling_mode), - static_cast(token_alignment), grid_clusters, int64_offsets); + static_cast(token_alignment), grid_clusters); } std::string to_key() const { return config_key("ep_combine_gemm", args()); } @@ -262,7 +271,6 @@ struct EpWgradConfig { NVTEScalingMode scaling_mode; // operand scaling: delayed for BF16, MXFP8 1D for MXFP8 size_t token_alignment; // rows per expert slab are a multiple of it size_t routed_tokens; // rows a rank receives at capacity under uniform routing, unpadded - bool int64_offsets = false; // the row ends are int64 instead of int32 bool is_mxfp8() const { return scaling_mode == NVTE_MXFP8_1D_SCALING; } @@ -273,7 +281,7 @@ struct EpWgradConfig { static_cast(num_experts), num_clusters, fp32_out, accumulate, wait_primary_at_start, static_cast(signal_unit_tokens), static_cast(scaling_mode), static_cast(token_alignment), - static_cast(routed_tokens), int64_offsets); + static_cast(routed_tokens)); } std::string to_key() const { return config_key("ep_wgrad", args()); } diff --git a/transformer_engine/common/ep/ep_gemm_utils.h b/transformer_engine/common/ep/ep_gemm_utils.h index 92b79b6b3ed..c07239bdfa1 100644 --- a/transformer_engine/common/ep/ep_gemm_utils.h +++ b/transformer_engine/common/ep/ep_gemm_utils.h @@ -28,39 +28,31 @@ inline NVTEScalingMode ep_overlap_scaling_mode(NVTETensor t) { return mode; } -// Shapes the MXFP8 GEMMs take: compact scale rows of whole 16-byte TMA boxes, SwiGLU tiles and -// expert slabs of whole 128-row scale tiles. -inline void check_ep_mxfp8_dims(size_t hidden, size_t ffn, size_t alignment) { +// Shapes the MXFP8 GEMMs take: compact scale rows of whole 16-byte TMA boxes and SwiGLU tiles. +inline void check_ep_mxfp8_dims(size_t hidden, size_t ffn) { NVTE_CHECK(hidden % kMxfp8HiddenMultiple == 0 && ffn % kMxfp8FfnMultiple == 0, "MXFP8 needs hidden_dim (", hidden, ") a multiple of ", kMxfp8HiddenMultiple, " and ffn_dim (", ffn, ") a multiple of ", kMxfp8FfnMultiple); - NVTE_CHECK(alignment >= kMxfp8MinAlignment, "MXFP8 needs dispatch_output_per_expert_alignment ", - kMxfp8MinAlignment, " or ", kRowsPerTile); } -// The expert layout the GEMMs read: [num_experts + 1] int32 or int64, expert 0's start (0), then -// the row ends from expert_token_offsets[1:], which must start 16-byte aligned. Returns whether -// it is int64. counts, when given, must share its dtype. -inline bool check_ep_expert_token_offsets(const NVTETensor expert_token_offsets, size_t num_experts, +// The expert layout the GEMMs read: [num_experts + 1] int64, expert 0's start (0), then the row +// ends from expert_token_offsets[1:], which must start 16-byte aligned. counts, when given, must +// be int64 too. +inline void check_ep_expert_token_offsets(const NVTETensor expert_token_offsets, size_t num_experts, const NVTETensor counts = nullptr) { NVTE_CHECK(expert_token_offsets != nullptr, "expert_token_offsets must not be null"); - const NVTEDType dtype = nvte_tensor_type(expert_token_offsets); NVTE_CHECK(nvte_tensor_numel(expert_token_offsets) == num_experts + 1 && - (dtype == kNVTEInt32 || dtype == kNVTEInt64), - "expert_token_offsets must be an int32 or int64 tensor of num_experts + 1 elements"); - const size_t elem = dtype == kNVTEInt64 ? sizeof(int64_t) : sizeof(int32_t); + nvte_tensor_type(expert_token_offsets) == kNVTEInt64, + "expert_token_offsets must be an int64 tensor of num_experts + 1 elements"); const auto *row_ends = - static_cast(nvte_tensor_data(expert_token_offsets)) + elem; + static_cast(nvte_tensor_data(expert_token_offsets)) + sizeof(int64_t); NVTE_CHECK(reinterpret_cast(row_ends) % 16 == 0, "expert_token_offsets[1:] (the per-expert row ends) must start 16-byte aligned"); if (counts != nullptr) { - NVTE_CHECK(nvte_tensor_shape(counts).ndim == 1 && nvte_tensor_numel(counts) == num_experts, - "recv_tokens_per_expert must be a 1-D tensor of num_experts elements"); - NVTE_CHECK(nvte_tensor_type(counts) == dtype, - "recv_tokens_per_expert and expert_token_offsets must share a dtype, int32 or " - "int64"); + NVTE_CHECK(nvte_tensor_shape(counts).ndim == 1 && nvte_tensor_numel(counts) == num_experts && + nvte_tensor_type(counts) == kNVTEInt64, + "recv_tokens_per_expert must be an int64 tensor of num_experts elements"); } - return dtype == kNVTEInt64; } } // namespace ep diff --git a/transformer_engine/common/ep/ep_overlap_workspace.cu b/transformer_engine/common/ep/ep_overlap_workspace.cu index 06f52d0d748..8799dd2f03a 100644 --- a/transformer_engine/common/ep/ep_overlap_workspace.cu +++ b/transformer_engine/common/ep/ep_overlap_workspace.cu @@ -32,28 +32,32 @@ __global__ void reset_workspace_kernel(WorkspaceReset reset) { return; } const int64_t num_experts = reset.num_experts; - const auto load = [&](const void* p, int64_t i) -> int64_t { - return reset.layout_int64 ? static_cast(p)[i] - : static_cast(p)[i]; - }; // TODO(phuonguyen): drop offsets + counts once NCCL EP outputs the final post-drop num total // recv tokens, and read the row ends straight from NCCL EP. if (reset.counts != nullptr && tid == 0) { - const int64_t end = load(reset.layout, num_experts - 1) + load(reset.counts, num_experts - 1); - if (reset.layout_int64) { - static_cast(reset.layout)[num_experts] = end; - } else { - static_cast(reset.layout)[num_experts] = static_cast(end); - } + reset.layout[num_experts] = reset.layout[num_experts - 1] + reset.counts[num_experts - 1]; } if (reset.offsets != nullptr) { __syncthreads(); for (int64_t e = tid; e <= num_experts; e += kThreads) { - reset.offsets[e] = load(reset.layout, e) * reset.offsets_cols; + reset.offsets[e] = reset.layout[e] * reset.offsets_cols; } } } +__global__ void reduce_dprob_slots_kernel(const float* slots, float* dprob, int rows, int n_slots) { + const int row = blockIdx.x * blockDim.x + threadIdx.x; + if (row >= rows) { + return; + } + const float* row_slots = slots + static_cast(row) * n_slots; + float sum = 0.0f; + for (int i = 0; i < n_slots; ++i) { + sum += row_slots[i]; + } + dprob[row] = sum; +} + } // namespace void WorkspaceReset::fill(void* words, int count, int32_t value) { @@ -75,5 +79,16 @@ void reset_workspace(const WorkspaceReset& reset, cudaStream_t stream) { NVTE_CHECK_CUDA(cudaGetLastError()); } +void reduce_dprob_slots(const float* slots, float* dprob, int rows, int n_slots, + cudaStream_t stream) { + if (rows == 0) { + return; + } + constexpr int kBlock = 256; + reduce_dprob_slots_kernel<<<(rows + kBlock - 1) / kBlock, kBlock, 0, stream>>>(slots, dprob, rows, + n_slots); + NVTE_CHECK_CUDA(cudaGetLastError()); +} + } // namespace ep } // namespace transformer_engine diff --git a/transformer_engine/common/ep/ep_overlap_workspace.h b/transformer_engine/common/ep/ep_overlap_workspace.h index e333197b4e4..e391358785e 100644 --- a/transformer_engine/common/ep/ep_overlap_workspace.h +++ b/transformer_engine/common/ep/ep_overlap_workspace.h @@ -30,14 +30,13 @@ struct WorkspaceReset { }; Fill fills[kMaxFills]; int num_fills = 0; - // Expert layout [num_experts + 1] of int32 or int64: expert 0's start (0), then the row ends. - void* layout = nullptr; - bool layout_int64 = false; + // Expert layout [num_experts + 1] int64: expert 0's start (0), then the row ends. + int64_t* layout = nullptr; int num_experts = 0; - // Optional [num_experts] padded counts of the layout's dtype. The reset writes the final + // Optional [num_experts] int64 padded counts. The reset writes the final // post-drop num total recv tokens, layout[num_experts] = layout[num_experts - 1] + // counts[num_experts - 1]. - const void* counts = nullptr; + const int64_t* counts = nullptr; // Optional [num_experts + 1] int64 element offsets of the requant grouped tensor: layout * cols. int64_t* offsets = nullptr; int64_t offsets_cols = 0; @@ -49,6 +48,11 @@ struct WorkspaceReset { // One launch performing every fill and the layout writes of reset. void reset_workspace(const WorkspaceReset& reset, cudaStream_t stream); +// dprob[row] = the sum of slots[row, 0 .. n_slots) in ascending order, for rows rows: the fixed +// order reduction of a deterministic routing-weight gradient. +void reduce_dprob_slots(const float* slots, float* dprob, int rows, int n_slots, + cudaStream_t stream); + } // namespace ep } // namespace transformer_engine diff --git a/transformer_engine/common/include/transformer_engine/ep.h b/transformer_engine/common/include/transformer_engine/ep.h index 98267dc861a..3715f4aa6b8 100644 --- a/transformer_engine/common/include/transformer_engine/ep.h +++ b/transformer_engine/common/include/transformer_engine/ep.h @@ -126,6 +126,11 @@ typedef struct { /*! topk_idx dtype used at prepare (kNVTEInt32 or kNVTEInt64). Read only by the * per-step ops. */ NVTEDType topk_idx_dtype; + /*! Read only by nvte_ep_combine_gemm_bwd. 0 (default) writes the routing-weight gradient in a + * fixed summation order, at the cost of a scratch of one FP32 slot per row and output tile and a + * reduce kernel. Nonzero lets the GEMM add into it atomically, in tile scheduling order. The + * deterministic mode errors on a GEMM kernel that has no such mode; it never falls back. */ + int allow_nondeterministic; } NVTEEpLayerConfig; /* Zero-init a config with struct_size set to the current layout: diff --git a/transformer_engine/common/include/transformer_engine/ep_gemm.h b/transformer_engine/common/include/transformer_engine/ep_gemm.h index 9294654e511..2b058400baf 100644 --- a/transformer_engine/common/include/transformer_engine/ep_gemm.h +++ b/transformer_engine/common/include/transformer_engine/ep_gemm.h @@ -23,12 +23,15 @@ * - Combine side: the GEMM leads. The forward combine follows the GEMM's hidden-column chunks * and takes the SMs it frees; the backward combine is unsignaled and overlaps only the weight * gradient. - * - Backward C names overlap the opposite transfer (see the EP call column). + * - Each backward call overlaps the reverse of its forward's transfer (EP call column): the + * FC2 backward with a dispatch backward, the FC1 backward with a combine backward. * * Requirements (all calls): * - SM 10.0, 10.3 or 10.7; EP within one NVLink domain; num_comm_sms > 0; zero_copy off. * - dispatch_output_per_expert_alignment is 256. - * - NVTE_ENABLE_CUTEDSL_BACKEND=1 and NVTE_MOE_OVERLAP=1. + * - TE built with NVTE_WITH_CUTEDSL=1, NVTE_ENABLE_CUTEDSL_BACKEND=1 and NVTE_MOE_OVERLAP=1, and + * the nvidia-cudnn-frontend package with the EP grouped GEMM kernels. + * - recv_tokens_per_expert, expert_token_offsets and total_recv_tokens are int64. * - MXFP8: hidden_dim a multiple of 512, ffn_dim a multiple of 256. * - First call per shape compiles its GEMM: run it at warmup, outside CUDA graph capture. * - A group's calls on one stream, same order on every rank. A call throws otherwise. @@ -76,20 +79,19 @@ extern "C" { * \param[out] recv_topk_weights [recv_capacity] float32 per-row routing weights. * \param[out] gemm_out [recv_capacity, 2 * ffn_dim] GEMM output. * \param[out] act_out [recv_capacity, ffn_dim] SwiGLU output. - * \param[in,out] recv_tokens_per_expert [num_local_experts] int32 or int64 padded counts, the - * dtype of expert_token_offsets. Eager mode passes the ones - * nvte_ep_prepare wrote; capacity mode writes them, from the + * \param[in,out] recv_tokens_per_expert [num_local_experts] int64 padded counts. Eager mode + * passes the ones nvte_ep_prepare wrote; capacity mode + * writes them, from the * dispatch when there are no drops and at most 2048 local * experts, else from the routing prepare. - * \param[in,out] expert_token_offsets [num_local_experts + 1] int32 or int64 expert layout in + * \param[in,out] expert_token_offsets [num_local_experts + 1] int64 expert layout in * tokens (rows): expert 0's start (0), then each expert's * padded row end, the GEMM operand. expert_token_offsets[1:] * must start 16-byte aligned. NCCL EP writes the starts * (eager mode: nvte_ep_prepare); the last entry, the final * post-drop num total recv tokens, is the dispatch's total * or the last start plus the last count. - * \param[out] total_recv_tokens [1] recv total before any overflow drop, of the - * expert_token_offsets dtype, or null. + * \param[out] total_recv_tokens [1] int64 recv total before any overflow drop, or null. * The routing prepare writes it; when the dispatch writes * expert_token_offsets instead (no drops), it is * expert_token_offsets[-1], the padded total of the kept @@ -126,7 +128,7 @@ void nvte_ep_dispatch_gemm_fwd(NVTETensor handle_mem, const NVTETensor topk_idx, * nvte_ep_dispatch_gemm_fwd, bfloat16 or MXFP8. * \param[in] recv_topk_weights [recv_capacity] float32 per-row routing weights; null for * unit weights (bfloat16 act_out carries them). - * \param[in] expert_token_offsets [num_local_experts + 1] int32 or int64 expert layout from + * \param[in] expert_token_offsets [num_local_experts + 1] int64 expert layout from * nvte_ep_dispatch_gemm_fwd (the GEMM reads its row ends); * expert_token_offsets[1:] must start 16-byte aligned. * \param[in] weight [num_local_experts, hidden_dim, ffn_dim] weights. @@ -156,6 +158,11 @@ void nvte_ep_combine_gemm_fwd(NVTETensor handle_mem, const NVTETensor gemm_in, * grad_recv_topk_weights uses the unweighted activation silu(gate) * up. weight_grad is written * only when non-null; accumulate_weight_grad adds to it instead of overwriting it. * + * grad_recv_topk_weights is summed in a fixed order by default (layer_cfg->allow_nondeterministic + * == 0): bitwise reproducible, at the cost of workspace for one float per row and 256 ffn columns + * and a reduce kernel after the call's GEMMs. Nonzero allow_nondeterministic adds into it + * atomically instead. + * * Schedule (backward dispatch leads, dY tiles; dispatch_bwd_num_sms; time --->): * bwd dispatch |--- deliver tiles ---| * dGLU |--- head ------------|--- tail ---| @@ -253,8 +260,9 @@ void nvte_ep_dispatch_gemm_bwd(NVTETensor handle_mem, const NVTETensor grad_gemm NVTETensor workspace, const NVTEEpLayerConfig* layer_cfg, cudaStream_t stream); -/*! \brief Compile the group's overlapped GEMMs and return the bytes of a workspace that fits every - * call of the group. Queryable once the EP group is bootstrapped; call it at warmup. +/*! \brief Return the bytes of a workspace that fits every call of the group. Queryable once the EP + * group is bootstrapped. It only queries the GEMM workspace layouts: the first call of + * each op still compiles its GEMM, so run each at warmup, outside CUDA graph capture. * * \param[in] hidden_dim Hidden size. * \param[in] ffn_dim Expert FFN size. @@ -262,7 +270,8 @@ void nvte_ep_dispatch_gemm_bwd(NVTETensor handle_mem, const NVTETensor grad_gemm * \param[in] recv_capacity Rows of the receive buffers. * \param[in] with_weight_grad Nonzero to fit the backward weight-gradient workspace. * \param[in] mxfp8 Nonzero for MXFP8 operands instead of bfloat16. - * \param[in] layer_cfg Per-layer EP configuration. + * \param[in] layer_cfg Per-layer EP configuration; allow_nondeterministic selects the GEMM + * kernels sized, and the size fits either mode. * \return Required workspace size in bytes. */ size_t nvte_ep_overlap_prepare(size_t hidden_dim, size_t ffn_dim, size_t num_local_experts, diff --git a/transformer_engine/pytorch/csrc/extensions/ep.cpp b/transformer_engine/pytorch/csrc/extensions/ep.cpp index 653b0eacd9d..427c5afeb4b 100644 --- a/transformer_engine/pytorch/csrc/extensions/ep.cpp +++ b/transformer_engine/pytorch/csrc/extensions/ep.cpp @@ -228,6 +228,8 @@ TensorWrapper weight_operand(const py::object& weight, size_t num_experts, size_ if (!is_mxfp8_object(weight)) { return t; } + NVTE_CHECK(num_experts > 0 && in_features > 0, + "MXFP8 weight needs at least one expert and input"); for (const bool columnwise : {false, true}) { const NVTEBasicTensor data = nvte_get_tensor_param(t.data(), columnwise ? kNVTEColumnwiseData : kNVTERowwiseData); @@ -298,6 +300,13 @@ void check_dense_cuda(const at::Tensor& t, const char* name) { name, " must be a contiguous tensor on the current CUDA device"); } +// Experts of expert_token_offsets [num_experts + 1]. +size_t num_experts_of(const at::Tensor& expert_token_offsets) { + NVTE_CHECK(expert_token_offsets.numel() >= 2, + "expert_token_offsets must have num_experts + 1 entries"); + return static_cast(expert_token_offsets.numel() - 1); +} + using NamedOperand = std::pair; const at::Tensor* operand(const at::Tensor& t) { return &t; } @@ -416,13 +425,15 @@ void ep_finalize() { namespace { NVTEEpLayerConfig make_layer_cfg(int64_t top_k, int64_t dispatch_output_per_expert_alignment, - DType topk_idx_dtype = DType::kInt32) { + DType topk_idx_dtype = DType::kInt32, + bool allow_nondeterministic = false) { return NVTEEpLayerConfig{ .struct_size = sizeof(NVTEEpLayerConfig), .top_k = static_cast(top_k), .dispatch_output_per_expert_alignment = static_cast(dispatch_output_per_expert_alignment), .topk_idx_dtype = static_cast(topk_idx_dtype), + .allow_nondeterministic = allow_nondeterministic ? 1 : 0, }; } @@ -470,6 +481,7 @@ void ep_prepare(at::Tensor handle_mem, at::Tensor topk_idx, at::Tensor tokens_pe expert_offsets->numel() == tokens_per_expert.numel() && expert_offsets->is_contiguous(), "expert_offsets must be contiguous with the dtype and size of tokens_per_expert"); + check_dense_cuda(*expert_offsets, "expert_offsets"); expert_offsets_te = makeTransformerEngineTensor( expert_offsets->data_ptr(), Shape{static_cast(expert_offsets->numel())}, count_dtype); @@ -951,6 +963,7 @@ void ep_dispatch_gemm_fwd(at::Tensor handle_mem, at::Tensor topk_idx, py::object "total_recv_tokens must be pinned host memory or on the current CUDA device"); NVTE_CHECK(gemm_out.is_contiguous(), "gemm_out must be contiguous"); auto tokens_te = compact_scales_operand(tokens); + NVTE_CHECK(tokens_te.shape().ndim == 2, "tokens must be [num_tokens, hidden]"); auto weight_te = weight_operand(weight, tokens_per_expert.numel(), tokens_te.shape().data[1]); auto recv_tokens_te = operand_tensor(recv_tokens); auto act_out_te = operand_tensor(act_out); @@ -974,6 +987,7 @@ void ep_dispatch_gemm_fwd(at::Tensor handle_mem, at::Tensor topk_idx, py::object "recv buffer and the hidden, 2 * ffn and ffn columns of the operands"); check_dense_cuda(tokens_per_expert, "tokens_per_expert"); check_dense_cuda(expert_token_offsets, "expert_token_offsets"); + check_dense_cuda(topk_weights, "topk_weights"); check_dense_cuda(recv_topk_weights, "recv_topk_weights"); auto handle_mem_te = makeTransformerEngineTensor(handle_mem); auto topk_idx_te = makeTransformerEngineTensor(topk_idx); @@ -1024,8 +1038,9 @@ void ep_combine_gemm_fwd(at::Tensor handle_mem, py::object gemm_in, at::Tensor e "pass gemm_in and weight as MXFP8 tensors, or both as torch tensors"); NVTE_CHECK(expert_out.is_contiguous() && result.is_contiguous(), "operands must be contiguous"); auto gemm_in_te = operand_tensor(gemm_in); + NVTE_CHECK(gemm_in_te.shape().ndim == 2, "gemm_in must be [rows, ffn]"); auto weight_te = - weight_operand(weight, expert_token_offsets.numel() - 1, gemm_in_te.shape().data[1]); + weight_operand(weight, num_experts_of(expert_token_offsets), gemm_in_te.shape().data[1]); const NVTEShape gemm_in_shape = gemm_in_te.shape(); const NVTEShape weight_shape = weight_te.shape(); NVTE_CHECK(gemm_in_shape.ndim == 2 && weight_shape.ndim == 3 && @@ -1061,7 +1076,8 @@ void ep_combine_gemm_fwd(at::Tensor handle_mem, py::object gemm_in, at::Tensor e // MXFP8: the weight and act_out are columnwise with GEMM-swizzled scales; grad_result is rowwise // with compact scales, grad_expert_out rowwise with compact scales and columnwise when the weight // gradient is computed, and grad_gemm_out rowwise with swizzled scales. The columnwise -// grad_gemm_out and act_out, the weight gradient operands, are written when given. +// grad_gemm_out and act_out, the weight gradient operands, are written when given. deterministic +// reduces the routing-weight gradient in a fixed order. void ep_combine_gemm_bwd(at::Tensor handle_mem, py::object grad_result, at::Tensor gemm_out, at::Tensor recv_topk_weights, at::Tensor expert_token_offsets, py::object weight, py::object grad_expert_out, py::object grad_gemm_out, @@ -1070,7 +1086,7 @@ void ep_combine_gemm_bwd(at::Tensor handle_mem, py::object grad_result, at::Tens at::ScalarType topk_idx_dtype, std::optional act_out, std::optional wgrad_input, std::optional weight_grad, bool accumulate_weight_grad, - bool symm_input) { + bool symm_input, bool deterministic) { check_cuda_operands({{"handle_mem", operand(handle_mem)}, {"gemm_out", operand(gemm_out)}, {"recv_topk_weights", operand(recv_topk_weights)}, @@ -1106,12 +1122,14 @@ void ep_combine_gemm_bwd(at::Tensor handle_mem, py::object grad_result, at::Tens act_out_te = operand_tensor(*act_out); } // The weight is [experts, hidden, ffn], and grad_gemm_out is [rows, 2 * ffn]. - auto weight_te = weight_operand(weight, expert_token_offsets.numel() - 1, + NVTE_CHECK(grad_gemm_out_te.shape().ndim == 2, "grad_gemm_out must be [rows, 2 * ffn]"); + auto weight_te = weight_operand(weight, num_experts_of(expert_token_offsets), mxfp8 ? grad_gemm_out_te.shape().data[1] / 2 : 0); WeightGradTensors wgrad(wgrad_input, weight_grad); const NVTECommWindow grad_result_win = symm_input ? make_input_window(grad_result) : kNoWindow; auto layer_cfg = make_layer_cfg(top_k, dispatch_output_per_expert_alignment, - get_topk_idx_te_dtype(topk_idx_dtype)); + get_topk_idx_te_dtype(topk_idx_dtype), + /*allow_nondeterministic=*/!deterministic); // FC2 weight is [experts, hidden, ffn]; size the wgrad region when a weight gradient is written. const NVTEShape weight_shape = weight_te.shape(); auto workspace_t = @@ -1161,8 +1179,9 @@ void ep_dispatch_gemm_bwd(at::Tensor handle_mem, py::object grad_gemm_out, auto grad_gemm_out_te = operand_tensor(grad_gemm_out); auto grad_recv_topk_weights_te = makeTransformerEngineTensor(grad_recv_topk_weights); auto expert_token_offsets_te = makeTransformerEngineTensor(expert_token_offsets); + NVTE_CHECK(grad_recv_tokens.dim() == 2, "grad_recv_tokens must be [rows, hidden]"); auto weight_te = - weight_operand(weight, expert_token_offsets.numel() - 1, grad_recv_tokens.size(1)); + weight_operand(weight, num_experts_of(expert_token_offsets), grad_recv_tokens.size(1)); auto grad_recv_tokens_te = makeTransformerEngineTensor(grad_recv_tokens); auto grad_tokens_te = makeTransformerEngineTensor(grad_tokens); auto grad_topk_weights_te = makeTransformerEngineTensor(grad_topk_weights); @@ -1243,7 +1262,8 @@ void register_ep_bindings(pybind11::module_& m) { py::arg("top_k"), py::arg("dispatch_output_per_expert_alignment"), py::arg("topk_idx_dtype"), py::arg("act_out") = std::nullopt, py::arg("wgrad_input") = std::nullopt, py::arg("weight_grad") = std::nullopt, - py::arg("accumulate_weight_grad") = false, py::arg("symm_input") = false); + py::arg("accumulate_weight_grad") = false, py::arg("symm_input") = false, + py::arg("deterministic") = true); m.def("ep_dispatch_gemm_bwd", &ep_dispatch_gemm_bwd, "Backward of the first GEMM and the dispatch", py::arg("handle_mem"), py::arg("grad_gemm_out"), py::arg("grad_recv_topk_weights"), diff --git a/transformer_engine/pytorch/ep.py b/transformer_engine/pytorch/ep.py index 2b2830bd023..ec85400b91c 100644 --- a/transformer_engine/pytorch/ep.py +++ b/transformer_engine/pytorch/ep.py @@ -9,7 +9,7 @@ import math import os import warnings -from dataclasses import dataclass +from dataclasses import dataclass, fields from typing import Optional, TYPE_CHECKING import torch @@ -62,6 +62,16 @@ _MIN_NCCL_VERSION = (2, 30, 4) +def _check_non_negative_ints(config) -> None: + """Raise if a field of a dataclass of SM or chunk settings is not a non-negative int.""" + for field in fields(config): + value = getattr(config, field.name) + if isinstance(value, bool) or not isinstance(value, int) or value < 0: + raise ValueError( + f"{type(config).__name__}.{field.name} must be a non-negative int (got {value!r})." + ) + + def _check_nccl_runtime_version() -> None: """Raise with a clear message if the loaded libnccl is too old for NCCL EP.""" import ctypes @@ -240,6 +250,8 @@ def ep_bootstrap( max_num_sms = _OVERLAP_COMM_SMS sm_config = sm_config or EpSmConfig() overlap_config = overlap_config or EpOverlapConfig() + _check_non_negative_ints(sm_config) + _check_non_negative_ints(overlap_config) if _BOOTSTRAPPED: raise RuntimeError("ep_bootstrap was already called in this process") if ep_group.size() < 2: @@ -329,15 +341,21 @@ def get_ep_drop_on_overflow() -> Optional[bool]: def _moe_overlap_available() -> bool: """Whether the overlapped MoE GEMMs can run: SM 10.0, 10.3 or 10.7 (tcgen05 kernels), the - CuTeDSL backend built and on, and the GEMM path set.""" + CuTeDSL backend built and on, the GEMM path set, and cuDNN FE grouped kernels that take int64 + expert offsets.""" if not torch.cuda.is_available(): return False - return ( + if not ( get_device_compute_capability() in ((10, 0), (10, 3), (10, 7)) and os.environ.get("NVTE_ENABLE_CUTEDSL_BACKEND", "0") != "0" and os.environ.get("NVTE_MOE_OVERLAP", "0") != "0" and cutedsl_backend_built() - ) + ): + return False + # pylint: disable-next=import-outside-toplevel + from .ops.fused.grouped_mlp import _cudnn_frontend_supports_int64_offsets + + return _cudnn_frontend_supports_int64_offsets() def _ep_is_eager() -> bool: @@ -1176,13 +1194,13 @@ def _sym_dispatch_buffers(device, quantizer: "Quantizer") -> Optional[MXFP8Tenso symm-mem support. Allocated collectively on first use and shared by every layer and direction, so the EP calls of the group must share one stream.""" global _SYM_DISPATCH_BUFFERS - if _SYM_DISPATCH_BUFFERS is None: - from .tensor.mxfp8_tensor import MXFP8Quantizer + from .tensor.mxfp8_tensor import MXFP8Quantizer - if not isinstance(quantizer, MXFP8Quantizer): - raise NotImplementedError( - f"The EP dispatch buffers support only MXFP8; got {type(quantizer).__name__}." - ) + if not isinstance(quantizer, MXFP8Quantizer): + raise NotImplementedError( + f"The EP dispatch buffers support only MXFP8; got {type(quantizer).__name__}." + ) + if _SYM_DISPATCH_BUFFERS is None: if not tex.ep_zero_copy_supported(): return None if torch.cuda.is_current_stream_capturing(): diff --git a/transformer_engine/pytorch/ops/fused/grouped_mlp.py b/transformer_engine/pytorch/ops/fused/grouped_mlp.py index c53c7f1ab5c..9b04f00d1bf 100644 --- a/transformer_engine/pytorch/ops/fused/grouped_mlp.py +++ b/transformer_engine/pytorch/ops/fused/grouped_mlp.py @@ -79,22 +79,17 @@ def _cudnn_frontend_version_at_least(min_version: str) -> bool: def _cudnn_frontend_version_supported() -> bool: """Check the minimum cuDNN frontend version for block-scaled grouped MLP.""" - return _cudnn_frontend_version_at_least("1.31.0") + return _cudnn_frontend_version_at_least("1.31.0") and _cudnn_frontend_supports_int64_offsets() @functools.lru_cache(maxsize=None) def _cudnn_frontend_supports_int64_offsets() -> bool: - """Whether the cuDNN FE grouped GEMMs take int64 offsets as well as int32 ones.""" + """Whether the cuDNN FE grouped GEMMs take the int64 expert offsets passed to them.""" try: from cudnn.gemm.cutedsl import grouped # pylint: disable=import-outside-toplevel except ImportError: return False - return getattr(grouped, "INT64_OFFSETS", False) - - -def _cudnn_offsets_dtype() -> torch.dtype: - """Dtype of the expert offsets passed to the cuDNN FE grouped GEMMs.""" - return torch.int64 if _cudnn_frontend_supports_int64_offsets() else torch.int32 + return bool(getattr(grouped, "INT64_OFFSETS", False)) @functools.lru_cache(maxsize=None) @@ -952,8 +947,6 @@ def _compute_grad_params( accumulate=accumulate_into_main_grad, ) elif cudnn_wgrad_kernel_fn is not None: - if offsets.dtype != torch.int32 and not _cudnn_frontend_supports_int64_offsets(): - offsets = offsets.to(dtype=torch.int32) gemm_fn = functools.partial( _cudnn_compute_wgrad, weight_shape=weight_shape, @@ -1405,14 +1398,9 @@ def fuser_forward( # Prepare split metadata if use_offsetless_metadata: # The use_single_group_runtime_offsets specialization never loads - # the pointer. This aliases the live caller-owned [M] int64 tensor - # (an int32 view where cuDNN takes only int32 offsets), has value M, - # and requires no allocation or CUDA kernel. - split_points = ( - split_sizes[:1] - if _cudnn_frontend_supports_int64_offsets() - else split_sizes.view(torch.int32)[:1] - ) + # the pointer. This aliases the live caller-owned [M] int64 tensor, + # has value M, and requires no allocation or CUDA kernel. + split_points = split_sizes[:1] # Backward saves this slot for the generic path. The optimized # shared-expert path never consumes it. base_split_offsets = split_sizes @@ -1444,7 +1432,7 @@ def fuser_forward( ], include_leading_zero=[False, True, True, True, True, True], dtypes=[ - _cudnn_offsets_dtype(), + torch.int64, torch.int64, torch.int64, torch.int64, @@ -3710,7 +3698,10 @@ def is_supported(cls) -> bool: if not (device_arch[0] == 10 and device_arch[1] < 7): return False # Canonical layouts and device-only offsets need cuDNN frontend PR #1602. - if not _cudnn_frontend_version_at_least(_BF16_MIN_CUDNN_FRONTEND_VERSION): + if not ( + _cudnn_frontend_version_at_least(_BF16_MIN_CUDNN_FRONTEND_VERSION) + and _cudnn_frontend_supports_int64_offsets() + ): return False try: kernels = ( @@ -3858,7 +3849,7 @@ def fuser_forward( device, strides=[1, 1], include_leading_zero=[False, True], - dtypes=[_cudnn_offsets_dtype(), torch.int64], + dtypes=[torch.int64, torch.int64], bulk_allocate=True, split_alignment=_BF16_M_ALIGNMENT, ) diff --git a/transformer_engine/pytorch/ops/fused/moe_overlap.py b/transformer_engine/pytorch/ops/fused/moe_overlap.py index 0bb9f3ebb7f..71590a0dc55 100644 --- a/transformer_engine/pytorch/ops/fused/moe_overlap.py +++ b/transformer_engine/pytorch/ops/fused/moe_overlap.py @@ -29,7 +29,6 @@ ) from ...distributed_weight import is_distributed_weight from ...quantization import Recipe -from ...tensor.grouped_tensor import GroupedTensor from ...tensor.mxfp8_tensor import MXFP8Quantizer from ...tensor.storage.grouped_tensor_storage import GroupedTensorStorage from ...tensor.storage.mxfp8_tensor_storage import MXFP8TensorStorage @@ -101,7 +100,6 @@ class FusedMoE(FusedOperation): @classmethod def is_supported(cls) -> bool: """Whether this fused operation can run on the current system.""" - # TODO(phuonguyen): gate on the cuDNN FE minimum version once the kernels are upstreamed. return _moe_overlap_available() def __init__( @@ -122,6 +120,7 @@ def __init__( raise RuntimeError(f"FusedMoE is not supported: {reason}.") self._mxfp8 = recipe is not None self._operands = _Mxfp8Operands() if self._mxfp8 else _Bf16Operands() + self._weight_quantizers = {1: {}, 3: {}} # The dispatch and combine share one EpBuffer (see _unsupported_reason); FusedMoE reads it # from self.basic_ops[0].buffer at each forward. @@ -145,7 +144,13 @@ def fuser_forward( fc2_op = self.basic_ops[3] topk_idx, topk_weights = basic_op_extra_inputs[0] + backward = any(ctx.requires_grad for ctx in basic_op_ctxs) + self._check_runtime_support(backward) buffer = validate_ep_buffer("FusedMoE", self.basic_ops[0].config, self.basic_ops[0].buffer) + if buffer.tokens_per_expert.dtype != torch.int64: + raise TypeError( + f"FusedMoE needs int64 tokens_per_expert, got {buffer.tokens_per_expert.dtype}." + ) input_shape = _validate_dispatch_input(input_, buffer) _validate_routing_inputs(topk_idx, topk_weights, device=buffer.device) if topk_idx.dtype not in (torch.int32, torch.int64): @@ -162,19 +167,21 @@ def fuser_forward( device = buffer.device hidden = buffer.hidden_dim ffn = fc2_op.in_features - backward = any(ctx.requires_grad for ctx in basic_op_ctxs) - self._check_runtime_support(backward) topk_idx = _require_contiguous(topk_idx, "topk_idx") topk_weights = _require_contiguous(topk_weights, "topk_weights") tokens_per_expert = buffer.tokens_per_expert - # The expert layout the GEMMs read, in the counts' dtype: expert 0's start (0), then each - # expert's padded row end. Front-pad so the row ends (expert_token_offsets[1:]) start - # 16-byte aligned. - pad = 16 // tokens_per_expert.element_size() - 1 + # The int64 expert layout the GEMMs read: expert 0's start (0), then each expert's padded + # row end. Front-pad one element so the row ends (expert_token_offsets[1:]) start 16-byte + # aligned. expert_token_offsets = torch.empty( - buffer.num_local_experts + 1 + pad, dtype=tokens_per_expert.dtype, device=device - )[pad:] + buffer.num_local_experts + 2, dtype=torch.int64, device=device + )[1:] if buffer.eager: + if torch.cuda.is_current_stream_capturing(): + raise RuntimeError( + "Eager FusedMoE reads the recv total on the host and cannot be captured in a" + " CUDA graph; bootstrap EP with recv_capacity_per_rank." + ) # The prepare writes the recv total to pinned host memory, and the expert starts. # Launch it first and mark its completion with an event, so the weight and input # preparation below overlaps it; only the total read waits. @@ -221,13 +228,6 @@ def fuser_forward( def _check_runtime_support(self, backward: bool) -> None: """Raise for a setting that can change between calls and the GEMMs do not support.""" - # TODO(phuonguyen): drop the deterministic gate once the routing-weight gradient is - # reworked to avoid the atomic reduction, which makes it reproducible. - if _deterministic_algorithms_required(): - raise RuntimeError( - "FusedMoE does not support deterministic execution: the routing-weight gradient is" - " reduced with atomics." - ) # TODO(phuonguyen): revisit once non-BF16 compute dtypes are supported. if torch.is_autocast_enabled() and torch.get_autocast_dtype("cuda") != torch.bfloat16: raise RuntimeError("FusedMoE computes in BF16; keep the autocast dtype BF16.") @@ -302,16 +302,18 @@ def _weight_operands(self, idx, columnwise): or the BF16 weight. Prepared fresh at each forward.""" fc_op = self.basic_ops[idx] if self._mxfp8: - return _mxfp8_weight_operands(fc_op, fc_op.num_groups, columnwise) + return _mxfp8_weight_operands( + fc_op, fc_op.num_groups, columnwise, self._weight_quantizers[idx] + ) return _bf16_weight(fc_op, fc_op.num_groups) - def fuser_backward( + def fuser_backward( # pylint: disable=unused-argument self, basic_op_ctxs: list[OperationContext], grad_output: torch.Tensor, *, basic_op_grad_extra_outputs: list[tuple[Optional[torch.Tensor], ...]], - **unused, # pylint: disable=unused-argument + **unused, ): # A later op that also reads the dispatch's routing weights delivers their gradient here; # fold it into the routing-weight gradient the dispatch backward scatters to topk_weights. @@ -346,7 +348,7 @@ def fuser_backward( tex.ep_combine_gemm_bwd( buffer.handle_mem, grad_result, gemm_out, recv_weights, expert_token_offsets, w2, grad_expert_out, grad_gemm, grad_recv_weights, buffer.top_k, buffer.alignment, - buffer.topk_idx_dtype, **fc2_wgrad, + buffer.topk_idx_dtype, deterministic=_deterministic_algorithms_required(), **fc2_wgrad, ) # fmt: skip if fc2_grads is None: fc2_grads = grad_params(fc2_op, fc2_ctx, act_out, grad_expert_out, "FC2") @@ -507,7 +509,8 @@ def fc1_grad_params(wgrad_args=None): tex.ep_combine_gemm_bwd( buffer.handle_mem, grad_result, gemm_out, recv_weights, expert_token_offsets, w2, grad_expert_out, grad_gemm, grad_recv_weights, buffer.top_k, buffer.alignment, - buffer.topk_idx_dtype, act_out=act_col, symm_input=symm_input, **fc2_wgrad, + buffer.topk_idx_dtype, act_out=act_col, symm_input=symm_input, + deterministic=_deterministic_algorithms_required(), **fc2_wgrad, ) # fmt: skip grad_tokens = grad_topk = fc1_grads = None @@ -556,7 +559,8 @@ def forward_weight(weight): @staticmethod def recv_buffers(rows, hidden, ffn, device): - """Receive buffers of a fixed capacity: recv tokens, GEMM output and activation output.""" + """Receive buffers of ``rows`` rows (the recv capacity, or the bucketed total in eager + mode): recv tokens, GEMM output and activation output.""" return ( torch.empty(rows, hidden, dtype=torch.bfloat16, device=device), torch.empty(rows, 2 * ffn, dtype=torch.bfloat16, device=device), @@ -648,9 +652,7 @@ def _require_contiguous(tensor: torch.Tensor, name: str) -> torch.Tensor: def _bf16_grad_output(grad_output) -> torch.Tensor: - """Contiguous BF16 gradient of the combine output.""" - if isinstance(grad_output, GroupedTensor): - raise RuntimeError("FusedMoE does not accept a quantized grad output.") + """Contiguous BF16 gradient of the combine output; a quantized gradient is dequantized.""" return maybe_dequantize(grad_output, torch.bfloat16).contiguous() @@ -738,12 +740,14 @@ def _with_columnwise_data(recv_tokens, first_dims, expert_token_offsets, operand def _mxfp8_weight_operands( - fc_op: GroupedLinear, num_groups: int, columnwise: bool + fc_op: GroupedLinear, num_groups: int, columnwise: bool, quantizer_cache: dict ) -> _MxFp8WeightOperands: """GEMM operands of the weight quantized to MXFP8, with the columnwise ones when asked; data is flat; the bindings shape it as [num_groups, out_features, in_features]. BF16 weights are quantized with GEMM-swizzled scales; the scales of MXFP8 weight parameters - are swizzled into a copy. Each direction is swizzled along its own scaling axis.""" + are swizzled into a copy. Each direction is swizzled along its own scaling axis. + ``quantizer_cache`` keeps the quantizer copy of BF16 weights per direction; a new quantizer of + the op, as after a recipe change, replaces it.""" weight = fc_op.weight if weight.quantizer is not None: # Only add usages, never drop: later weight updates keep what this op needs. @@ -753,9 +757,14 @@ def _mxfp8_weight_operands( weight = weight.copy() tex.grouped_swizzle_for_gemm(weight, rowwise=True, columnwise=columnwise) else: - quantizer = fc_op.get_quantizer("forward", 1).copy() - quantizer.set_usage(rowwise=True, columnwise=columnwise) - quantizer.optimize_for_gemm = True + base = fc_op.get_quantizer("forward", 1) + cached = quantizer_cache.get(columnwise) + if cached is None or cached[0] is not base: + quantizer = base.copy() + quantizer.set_usage(rowwise=True, columnwise=columnwise) + quantizer.optimize_for_gemm = True + cached = quantizer_cache[columnwise] = (base, quantizer) + quantizer = cached[1] weight = tex.group_quantize( weight.rowwise_data.view(weight.logical_shape), quantizer, num_groups, None ) @@ -837,7 +846,11 @@ def _moe_overlap_unsupported_reason( They must be MXFP8 and need the ``MXFP8BlockScaling`` recipe. """ if not FusedMoE.is_supported(): - return "needs SM 10.0, 10.3 or 10.7, NVTE_ENABLE_CUTEDSL_BACKEND=1 and NVTE_MOE_OVERLAP=1" + return ( + "needs SM 10.0, 10.3 or 10.7, TE built with NVTE_WITH_CUTEDSL=1, " + "NVTE_ENABLE_CUTEDSL_BACKEND=1, NVTE_MOE_OVERLAP=1 and a cuDNN frontend whose " + "grouped kernels take int64 expert offsets (INT64_OFFSETS)" + ) if config.payload_dtype is not torch.bfloat16: return "needs a BF16 payload" if config.alignment != _TILE: @@ -959,11 +972,11 @@ def _unsupported_reason(dispatch, fc1, activation, fc2, combine, recipe=None) -> ) -def fuse_moe_overlap_ops( +def fuse_moe_overlap_ops( # pylint: disable=unused-argument ops: list[FusibleOperation], *, recipe=None, - **unused, # pylint: disable=unused-argument + **unused, ) -> list[FusibleOperation]: """Fuse dispatch, grouped MLP and combine. A window that cannot be fused raises when the overlap is enabled and keeps the unfused ops otherwise.""" From 70e6cb50d742df1286f87b27c7c5d44ee1582ad5 Mon Sep 17 00:00:00 2001 From: Phuong Nguyen Date: Wed, 2 Dec 2026 23:41:47 -0800 Subject: [PATCH 40/67] [Common][PyTorch] Derive the EP overlap combine chunk schedule from group settings only, check TVM-FFI before layout queries, release the GIL for sizing and rename the workspace size query Signed-off-by: Phuong Nguyen --- docs/api/pytorch.rst | 5 +- docs/envvars.rst | 7 +- transformer_engine/common/ep/ep_gemm_api.cpp | 83 +++++++++++-------- transformer_engine/common/ep/ep_gemm_config.h | 4 + .../common/ep/ep_overlap_workspace.cu | 12 ++- .../common/ep/ep_overlap_workspace.h | 3 + .../include/transformer_engine/ep_gemm.h | 35 +++++--- .../pytorch/csrc/extensions/ep.cpp | 13 ++- 8 files changed, 105 insertions(+), 57 deletions(-) diff --git a/docs/api/pytorch.rst b/docs/api/pytorch.rst index faeb4bcea19..491b5cc3755 100644 --- a/docs/api/pytorch.rst +++ b/docs/api/pytorch.rst @@ -151,8 +151,9 @@ NCCL-based dispatch and combine for experts sharded across ranks. See an ``EpBuffer``. A buffer holds the routing state of one call until its backward has run, so several calls in flight (for example pipeline microbatches) each need their own ``EpBuffer`` and op instance. The guide shows how to connect the per-expert counts and routing weights through the -sequence's extra-tensor channels. With the overlap enabled (``NVTE_MOE_OVERLAP=1``) such a sequence -fuses into one op. If its settings are unsupported, an error names the reason. +sequence's extra-tensor channels. With the overlap enabled (``NVTE_MOE_OVERLAP=1``), a dispatch, +grouped MLP and combine sequence runs as one fused op, and a setting the fused op does not support +raises an error that names the reason. .. autoapiclass:: transformer_engine.pytorch.ops.MoeDispatch diff --git a/docs/envvars.rst b/docs/envvars.rst index 051c1f7f9ab..e6f9c61b57c 100644 --- a/docs/envvars.rst +++ b/docs/envvars.rst @@ -168,9 +168,10 @@ General :Description: Set to ``1`` to overlap the NCCL EP dispatch and combine with the expert grouped GEMMs (``ep_gemm.h``, used by the fused :class:`transformer_engine.pytorch.ops.MoeDispatch` expert MLP). Requires a - Transformer Engine build with ``NVTE_WITH_CUTEDSL=1``, ``NVTE_ENABLE_CUTEDSL_BACKEND=1``, - an SM 10.0, 10.3 or 10.7 GPU and a cuDNN frontend package whose CuTeDSL grouped - GEMMs take int64 expert offsets. If ``0``, the unfused ops run; if ``1``, a + Transformer Engine build with ``NVTE_WITH_CUTEDSL=1``, + ``NVTE_ENABLE_CUTEDSL_BACKEND=1``, an SM 10.0, 10.3 or 10.7 GPU and a cuDNN + frontend package whose CuTeDSL grouped GEMMs take int64 expert offsets. If + ``0``, the unfused ops run; if ``1``, a dispatch, grouped MLP and combine sequence that cannot run fused raises an error. With ``NVTE_ALLOW_NONDETERMINISTIC_ALGO=0`` or ``torch.use_deterministic_algorithms(True)``, the fused backward reduces the diff --git a/transformer_engine/common/ep/ep_gemm_api.cpp b/transformer_engine/common/ep/ep_gemm_api.cpp index ec225221c5d..92bdc21758e 100644 --- a/transformer_engine/common/ep/ep_gemm_api.cpp +++ b/transformer_engine/common/ep/ep_gemm_api.cpp @@ -58,12 +58,6 @@ size_t align_up(size_t value) { return (value + kWorkspaceAlign - 1) / kWorkspaceAlign * kWorkspaceAlign; } -// Columns of one combine flag over the whole row: the row rounded up to whole NCCL EP push tiles -// (1024 bfloat16 elements, or the row when shorter). NCCL EP takes a chunk past the row as one. -size_t whole_row_chunk(size_t n) { - return transformer_engine::DIVUP_TO_MULTIPLE(n, std::min(n, 1024)); -} - // Hidden columns per combine flag. configured overrides the default of one NCCL EP push tile // (1024 bfloat16 elements, or the row when shorter); the last chunk of a row the width does not // divide is the shorter remainder. @@ -181,7 +175,7 @@ ep::EpCombineGemmConfig combine_fwd_config(const EpGemmContext& ctx, size_t rows } // Per-call scratch for the GEMM's readiness flags and state, sliced from the caller's workspace. -// ScratchLayout is the byte layout; nvte_ep_overlap_prepare uses it to size the workspace +// ScratchLayout is the byte layout; nvte_ep_overlap_workspace_size uses it to size the workspace // without a buffer, and claim_scratch uses it to resolve the pointers in GemmScratch. struct ScratchLayout { size_t alpha; // [num_experts] float32 per-expert output scale, set to 1 (reused as norm_const) @@ -189,18 +183,21 @@ struct ScratchLayout { size_t offsets; // [num_experts + 1] int64 element offsets of the MXFP8 requant grouped tensor size_t wgrad; // backward weight-gradient accumulation workspace, empty when no weight gradient size_t dprob_slots; // [rows, slots per row] float32 of a deterministic routing-weight gradient + size_t flags; // int32 chunk flags of a combine the GEMM does not publish, all ready size_t total; // end offset: the bytes the caller must provide }; ScratchLayout scratch_layout(size_t gemm_bytes, size_t num_experts, size_t rows, bool unit_probs, - size_t wgrad_bytes, size_t dprob_slots_bytes = 0) { + size_t wgrad_bytes, size_t dprob_slots_bytes = 0, + size_t flag_words = 0) { ScratchLayout l; l.alpha = align_up(gemm_bytes); l.ones = l.alpha + align_up(sizeof(float) * num_experts); l.offsets = l.ones + (unit_probs ? align_up(sizeof(float) * rows) : 0); l.wgrad = l.offsets + align_up(sizeof(int64_t) * (num_experts + 1)); l.dprob_slots = l.wgrad + align_up(wgrad_bytes); - l.total = l.dprob_slots + align_up(dprob_slots_bytes); + l.flags = l.dprob_slots + align_up(dprob_slots_bytes); + l.total = l.flags + align_up(sizeof(int32_t) * flag_words); return l; } @@ -215,6 +212,7 @@ struct GemmScratch { float* dprob_slots = nullptr; // [rows * slots per row] deterministic routing-weight gradient int64_t* offsets = nullptr; // [num_experts + 1] requant grouped-tensor element offsets int32_t* signal = nullptr; // [signal_capacity] readiness flags + int32_t* flags = nullptr; // [flag words] chunk flags the GEMM does not publish int signal_capacity = 0; int num_experts = 0; ep::WorkspaceReset reset; @@ -222,11 +220,11 @@ struct GemmScratch { GemmScratch claim_scratch(uint8_t* base, size_t workspace_bytes, size_t gemm_bytes, size_t num_experts, size_t rows, bool unit_probs, size_t wgrad_bytes, - size_t dprob_slots_bytes = 0) { - const ScratchLayout l = - scratch_layout(gemm_bytes, num_experts, rows, unit_probs, wgrad_bytes, dprob_slots_bytes); + size_t dprob_slots_bytes = 0, size_t flag_words = 0) { + const ScratchLayout l = scratch_layout(gemm_bytes, num_experts, rows, unit_probs, wgrad_bytes, + dprob_slots_bytes, flag_words); NVTE_CHECK(l.total <= workspace_bytes, "the EP overlap workspace needs ", l.total, " bytes, got ", - workspace_bytes, "; size it with nvte_ep_overlap_prepare"); + workspace_bytes, "; size it with nvte_ep_overlap_workspace_size"); GemmScratch scratch{base}; if (wgrad_bytes > 0) { scratch.wgrad = base + l.wgrad; @@ -234,6 +232,9 @@ GemmScratch claim_scratch(uint8_t* base, size_t workspace_bytes, size_t gemm_byt if (dprob_slots_bytes > 0) { scratch.dprob_slots = reinterpret_cast(base + l.dprob_slots); } + if (flag_words > 0) { + scratch.flags = reinterpret_cast(base + l.flags); + } scratch.alpha = reinterpret_cast(base + l.alpha); scratch.offsets = reinterpret_cast(base + l.offsets); scratch.num_experts = static_cast(num_experts); @@ -277,6 +278,15 @@ void set_chunk_words(GemmScratch& scratch, const ep::WorkspaceLayout& layout, si scratch.reset.fill(scratch.signal, scratch.signal_capacity, ep::kFillMinusOne); } +// Words of a GEMM that publishes nothing: its first gemm_bytes (zero at entry), and the chunk flags +// of the combine behind it, all ready. +void set_published_chunk_words(GemmScratch& scratch, size_t gemm_bytes, size_t chunks) { + scratch.signal = scratch.flags; + scratch.signal_capacity = static_cast(chunks); + scratch.reset.fill(scratch.base, gemm_bytes / 4, ep::kFillZero); + scratch.reset.fill_iota(scratch.flags, scratch.signal_capacity); +} + // The caller's expert layout the GEMMs read, checked by check_ep_expert_token_offsets. void set_layout(GemmScratch& scratch, NVTETensor expert_token_offsets) { scratch.layout = static_cast(nvte_tensor_data(expert_token_offsets)); @@ -521,10 +531,10 @@ extern "C" { // Returns the max scratch over every op of the group, not per op: the scratch is small, so one // size that fits any call lets a caller size one workspace instead of querying each op. -size_t nvte_ep_overlap_prepare(size_t hidden_dim, size_t ffn_dim, size_t num_local_experts, - size_t recv_capacity, int with_weight_grad, int mxfp8, - const NVTEEpLayerConfig* layer_cfg) { - NVTE_API_CALL(nvte_ep_overlap_prepare); +size_t nvte_ep_overlap_workspace_size(size_t hidden_dim, size_t ffn_dim, size_t num_local_experts, + size_t recv_capacity, int with_weight_grad, int mxfp8, + const NVTEEpLayerConfig* layer_cfg) { + NVTE_API_CALL(nvte_ep_overlap_workspace_size); using namespace transformer_engine; const size_t ne = num_local_experts; const size_t rows = recv_capacity; @@ -534,9 +544,9 @@ size_t nvte_ep_overlap_prepare(size_t hidden_dim, size_t ffn_dim, size_t num_loc // Largest scratch of a call whose GEMM uses `config`; unit_probs sizes the per-row ones buffer // and wgrad the weight-gradient workspace. const auto consider = [&](const auto& config, bool unit_probs, size_t wgrad, - size_t dprob_slots_bytes = 0) { + size_t dprob_slots_bytes = 0, size_t flag_words = 0) { need = std::max(need, scratch_layout(gemm_workspace_bytes(config), ne, rows, unit_probs, wgrad, - dprob_slots_bytes) + dprob_slots_bytes, flag_words) .total); }; @@ -568,13 +578,12 @@ size_t nvte_ep_overlap_prepare(size_t hidden_dim, size_t ffn_dim, size_t num_loc { const EpGemmContext ctx = make_context(layer_cfg, &NVTEEpSmConfig::combine_bwd_num_sms); const bool plain = wg && ctx.num_clusters > 0; - const size_t n_chunk = - plain ? 0 : combine_chunk(hidden_dim, ctx.group.overlap_config.combine_chunk_hidden); + const size_t chunk = combine_chunk(hidden_dim, ctx.group.overlap_config.combine_chunk_hidden); const size_t wgrad = wg ? wgrad_workspace_bytes(ctx, rows, 2 * ffn_dim, hidden_dim, ne, mx) : 0; consider(ep::EpCombineGemmConfig{rows, 2 * ffn_dim, hidden_dim, ne, - wg ? ctx.all_clusters : ctx.num_clusters, n_chunk, !plain, - true, mx, ctx.alignment()}, - true, wgrad); + wg ? ctx.all_clusters : ctx.num_clusters, plain ? 0 : chunk, + !plain, true, mx, ctx.alignment()}, + true, wgrad, 0, plain ? DIVUP(hidden_dim, chunk) : 0); } return need; } @@ -1041,9 +1050,11 @@ void nvte_ep_dispatch_gemm_bwd(NVTETensor handle_mem, const NVTETensor grad_gemm // waits for the GEMM to complete: the GEMM publishes nothing and runs in the stock tile order, // and the one flag of the whole row is reset to 0, published. const bool plain = wgrad && ctx.num_clusters > 0; - const size_t n_chunk = - plain ? 0 : combine_chunk(hidden, ctx.group.overlap_config.combine_chunk_hidden); - const size_t chunk = plain ? whole_row_chunk(hidden) : n_chunk; + // The combine's chunk schedule is the group's on every rank, whether or not this rank computes a + // weight gradient; peers must agree on it. + const size_t chunk = combine_chunk(hidden, ctx.group.overlap_config.combine_chunk_hidden); + const size_t n_chunk = plain ? 0 : chunk; + const size_t num_chunks = DIVUP(hidden, chunk); // With the weight gradient the GEMM runs alone on every SM, and the weight gradient beside the // dispatch backward. @@ -1052,10 +1063,14 @@ void nvte_ep_dispatch_gemm_bwd(NVTETensor handle_mem, const NVTETensor grad_gemm rows, k, hidden, num_experts, wgrad ? ctx.all_clusters : ctx.num_clusters, n_chunk, !plain, true, scaling_mode, ctx.alignment()}; const tvm::ffi::Function gemm = get_gemm(config, &layout); - GemmScratch scratch = claim_scratch(ws_base, ws_bytes, layout.total_bytes, num_experts, rows, - true, wgrad ? wgrad->layout.total_bytes : 0); - set_chunk_words(scratch, layout, plain ? 0 : DIVUP(hidden, chunk), - plain ? layout.total_bytes : layout.signal); + GemmScratch scratch = + claim_scratch(ws_base, ws_bytes, layout.total_bytes, num_experts, rows, true, + wgrad ? wgrad->layout.total_bytes : 0, 0, plain ? num_chunks : 0); + if (plain) { + set_published_chunk_words(scratch, layout.total_bytes, num_chunks); + } else { + set_chunk_words(scratch, layout, num_chunks, layout.signal); + } if (wgrad) { scratch.reset.fill(scratch.wgrad + wgrad->layout.counter, 1, ep::kFillZero); } @@ -1095,8 +1110,7 @@ void nvte_ep_dispatch_gemm_bwd(NVTETensor handle_mem, const NVTETensor grad_gemm } NVTECommWindow no_window{}; - TensorWrapper signal(scratch.base + layout.signal, std::vector{DIVUP(hidden, chunk)}, - DType::kInt32); + TensorWrapper signal(scratch.signal, std::vector{num_chunks}, DType::kInt32); const ep::EpSignal combine_signal{signal.data(), chunk}; ctx.backend.dispatch_bwd(handle_mem, grad_recv_tokens, no_window, grad_recv_topk_weights, no_window, grad_tokens, grad_topk_weights, &combine_signal, @@ -1117,7 +1131,8 @@ namespace { extern "C" { -size_t nvte_ep_overlap_prepare(size_t, size_t, size_t, size_t, int, int, const NVTEEpLayerConfig*) { +size_t nvte_ep_overlap_workspace_size(size_t, size_t, size_t, size_t, int, int, + const NVTEEpLayerConfig*) { ep_gemm_not_built(); } diff --git a/transformer_engine/common/ep/ep_gemm_config.h b/transformer_engine/common/ep/ep_gemm_config.h index 33ff6e52bb5..7761c29958d 100644 --- a/transformer_engine/common/ep/ep_gemm_config.h +++ b/transformer_engine/common/ep/ep_gemm_config.h @@ -122,6 +122,10 @@ std::optional get_cached_kernel(const Config &config) { template std::optional call_entry(const char *name, const Config &config, const Prefix &...prefix) { + // Without TVM-FFI the bridge's lookup function pointer is null. + if (!tvm_ffi_bridge::TVMFFICentral::getInstance().get_tvm_ffi_available()) { + return std::nullopt; + } auto fn = tvm::ffi::Function::GetGlobal(name); if (!fn.has_value()) { return std::nullopt; diff --git a/transformer_engine/common/ep/ep_overlap_workspace.cu b/transformer_engine/common/ep/ep_overlap_workspace.cu index 8799dd2f03a..a8373ca34bc 100644 --- a/transformer_engine/common/ep/ep_overlap_workspace.cu +++ b/transformer_engine/common/ep/ep_overlap_workspace.cu @@ -24,7 +24,7 @@ __global__ void reset_workspace_kernel(WorkspaceReset reset) { for (int f = 0; f < WorkspaceReset::kMaxFills; ++f) { if (f < reset.num_fills) { for (int i = index; i < reset.fills[f].count; i += stride) { - reset.fills[f].words[i] = reset.fills[f].value; + reset.fills[f].words[i] = reset.fills[f].iota ? i : reset.fills[f].value; } } } @@ -65,7 +65,15 @@ void WorkspaceReset::fill(void* words, int count, int32_t value) { return; } NVTE_CHECK(num_fills < kMaxFills, "too many workspace fills"); - fills[num_fills++] = {static_cast(words), count, value}; + fills[num_fills++] = {static_cast(words), count, value, false}; +} + +void WorkspaceReset::fill_iota(void* words, int count) { + if (count == 0) { + return; + } + NVTE_CHECK(num_fills < kMaxFills, "too many workspace fills"); + fills[num_fills++] = {static_cast(words), count, 0, true}; } void reset_workspace(const WorkspaceReset& reset, cudaStream_t stream) { diff --git a/transformer_engine/common/ep/ep_overlap_workspace.h b/transformer_engine/common/ep/ep_overlap_workspace.h index e391358785e..ce907e0d23f 100644 --- a/transformer_engine/common/ep/ep_overlap_workspace.h +++ b/transformer_engine/common/ep/ep_overlap_workspace.h @@ -27,6 +27,7 @@ struct WorkspaceReset { int32_t* words; int count; int32_t value; + bool iota; // word i is set to i instead of value }; Fill fills[kMaxFills]; int num_fills = 0; @@ -43,6 +44,8 @@ struct WorkspaceReset { // Fill count words from words with value (a kFill* pattern); a zero count adds nothing. void fill(void* words, int count, int32_t value); + // Fill count words with 0, 1, ... count - 1: the flags of chunks that are all ready. + void fill_iota(void* words, int count); }; // One launch performing every fill and the layout writes of reset. diff --git a/transformer_engine/common/include/transformer_engine/ep_gemm.h b/transformer_engine/common/include/transformer_engine/ep_gemm.h index 2b058400baf..c02aadc2fcd 100644 --- a/transformer_engine/common/include/transformer_engine/ep_gemm.h +++ b/transformer_engine/common/include/transformer_engine/ep_gemm.h @@ -39,7 +39,7 @@ * outputs. * * SM budgets: NVTEEpGroupConfig *_num_sms fields (ep.h), set at nvte_ep_initialize, not layer_cfg. - * Workspace: caller-owned uint8 of the size nvte_ep_overlap_prepare returns. Each call resets it + * Workspace: caller-owned uint8 of the size nvte_ep_overlap_workspace_size returns. Each call resets it * before use, so one buffer can be reused across the group's calls. */ @@ -63,9 +63,13 @@ extern "C" { * gemm_out. MXFP8 tokens: tokens, recv_tokens, weight and act_out are MXFP8 and act_out is * silu(gate) * up, the routing weights left to nvte_ep_combine_gemm_fwd. * + * Requirements: see the file overview. + * * Schedule (dispatch leads, row tiles; dispatch_fwd_num_sms; time --->): * dispatch |--- deliver tiles ---| * FC1+SwiGLU |--- head ------------|--- tail ---| + * Head tiles run beside the EP call on the SMs it leaves; the tail runs the remaining tiles on all + * SMs once the EP call has freed its own. * * \param[in,out] handle_mem uint8 routing-state buffer. * \param[in] topk_idx [T, top_k] int32 or int64 routing indices. @@ -96,7 +100,7 @@ extern "C" { * expert_token_offsets instead (no drops), it is * expert_token_offsets[-1], the padded total of the kept * rows. - * \param[in,out] workspace uint8 scratch of the size nvte_ep_overlap_prepare returns. + * \param[in,out] workspace uint8 scratch of the size nvte_ep_overlap_workspace_size returns. * \param[in] activation Activation between the grouped GEMMs; only * NVTE_Activation_Type::SWIGLU is supported. * \param[in] layer_cfg Per-layer EP configuration. @@ -119,9 +123,11 @@ void nvte_ep_dispatch_gemm_fwd(NVTETensor handle_mem, const NVTETensor topk_idx, * activation, so recv_topk_weights is null here; MXFP8 leaves them off the activation and applies * them to this FC2 output. * + * Requirements: see the file overview. + * * Schedule (FC2 leads, hidden chunks; combine_fwd_num_sms; time --->): * FC2 |--- head ---------------| - * combine |--- push chunks ---------------| + * combine |--- push chunks -----------| * * \param[in,out] handle_mem uint8 routing-state buffer. * \param[in] gemm_in [recv_capacity, ffn_dim] act_out of @@ -134,7 +140,7 @@ void nvte_ep_dispatch_gemm_fwd(NVTETensor handle_mem, const NVTETensor topk_idx, * \param[in] weight [num_local_experts, hidden_dim, ffn_dim] weights. * \param[out] expert_out [recv_capacity, hidden_dim] GEMM output. * \param[out] result [T, hidden_dim] combined output. - * \param[in,out] workspace uint8 scratch of the size nvte_ep_overlap_prepare returns. + * \param[in,out] workspace uint8 scratch of the size nvte_ep_overlap_workspace_size returns. * \param[in] layer_cfg Per-layer EP configuration. * \param[in] stream CUDA stream. */ @@ -163,6 +169,8 @@ void nvte_ep_combine_gemm_fwd(NVTETensor handle_mem, const NVTETensor gemm_in, * and a reduce kernel after the call's GEMMs. Nonzero allow_nondeterministic adds into it * atomically instead. * + * Requirements: see the file overview. + * * Schedule (backward dispatch leads, dY tiles; dispatch_bwd_num_sms; time --->): * bwd dispatch |--- deliver tiles ---| * dGLU |--- head ------------|--- tail ---| @@ -196,7 +204,7 @@ void nvte_ep_combine_gemm_fwd(NVTETensor handle_mem, const NVTETensor gemm_in, * \param[in,out] weight_grad [num_local_experts, hidden_dim, ffn_dim] bfloat16 or * float32 gradient of weight, or null. * \param[in] accumulate_weight_grad Add to weight_grad instead of writing it. - * \param[in,out] workspace uint8 scratch of the size nvte_ep_overlap_prepare returns. + * \param[in,out] workspace uint8 scratch of the size nvte_ep_overlap_workspace_size returns. * \param[in] activation Activation whose backward runs between the grouped GEMMs; * only NVTE_Activation_Type::SWIGLU is supported. * \param[in] layer_cfg Per-layer EP configuration. @@ -222,6 +230,8 @@ void nvte_ep_combine_gemm_bwd( * grad_recv_topk_weights into grad_topk_weights. weight_grad is written only when non-null; * accumulate_weight_grad adds to it instead of overwriting it. * + * Requirements: see the file overview. + * * Schedule (FC1 dgrad, then unsignaled combine overlaps wgrad; combine_bwd_num_sms; time --->): * FC1 dgrad |--- all SMs ---| * combine | |--- return dX, dprob ---| @@ -247,7 +257,7 @@ void nvte_ep_combine_gemm_bwd( * \param[in,out] weight_grad [num_local_experts, 2 * ffn_dim, hidden_dim] bfloat16 or * float32 gradient of weight, or null. * \param[in] accumulate_weight_grad Add to weight_grad instead of writing it. - * \param[in,out] workspace uint8 scratch of the size nvte_ep_overlap_prepare returns. + * \param[in,out] workspace uint8 scratch of the size nvte_ep_overlap_workspace_size returns. * \param[in] layer_cfg Per-layer EP configuration. * \param[in] stream CUDA stream. */ @@ -260,9 +270,10 @@ void nvte_ep_dispatch_gemm_bwd(NVTETensor handle_mem, const NVTETensor grad_gemm NVTETensor workspace, const NVTEEpLayerConfig* layer_cfg, cudaStream_t stream); -/*! \brief Return the bytes of a workspace that fits every call of the group. Queryable once the EP - * group is bootstrapped. It only queries the GEMM workspace layouts: the first call of - * each op still compiles its GEMM, so run each at warmup, outside CUDA graph capture. +/*! \brief Return the byte size of the caller-owned workspace that fits every call of the group. + * Queryable once the EP group is bootstrapped. It only queries the GEMM workspace + * layouts and compiles nothing: the first call of each op still compiles its GEMM, so run + * each at warmup, outside CUDA graph capture. * * \param[in] hidden_dim Hidden size. * \param[in] ffn_dim Expert FFN size. @@ -274,9 +285,9 @@ void nvte_ep_dispatch_gemm_bwd(NVTETensor handle_mem, const NVTETensor grad_gemm * kernels sized, and the size fits either mode. * \return Required workspace size in bytes. */ -size_t nvte_ep_overlap_prepare(size_t hidden_dim, size_t ffn_dim, size_t num_local_experts, - size_t recv_capacity, int with_weight_grad, int mxfp8, - const NVTEEpLayerConfig* layer_cfg); +size_t nvte_ep_overlap_workspace_size(size_t hidden_dim, size_t ffn_dim, size_t num_local_experts, + size_t recv_capacity, int with_weight_grad, int mxfp8, + const NVTEEpLayerConfig* layer_cfg); #ifdef __cplusplus } diff --git a/transformer_engine/pytorch/csrc/extensions/ep.cpp b/transformer_engine/pytorch/csrc/extensions/ep.cpp index 427c5afeb4b..529d9fe7d6b 100644 --- a/transformer_engine/pytorch/csrc/extensions/ep.cpp +++ b/transformer_engine/pytorch/csrc/extensions/ep.cpp @@ -921,15 +921,20 @@ void ep_combine_bwd(at::Tensor handle_mem, at::Tensor grad, at::Tensor grad_expe } // Fresh per-call scratch for the overlapped GEMMs, sized for the group by -// nvte_ep_overlap_prepare. Allocated per call like the op's other IO tensors and kept alive +// nvte_ep_overlap_workspace_size. Allocated per call like the op's other IO tensors and kept alive // by the stream until the async GEMM completes; under graph capture it is served from the graph // pool, as those IO tensors are. at::Tensor overlap_workspace(int64_t hidden_dim, int64_t ffn_dim, int64_t num_local_experts, int64_t rows, bool with_weight_grad, bool mxfp8, const NVTEEpLayerConfig& layer_cfg, const at::Tensor& like) { - const int64_t bytes = static_cast(nvte_ep_overlap_prepare( - hidden_dim, ffn_dim, num_local_experts, rows, with_weight_grad, mxfp8, &layer_cfg)); - return at::empty({bytes}, like.options().dtype(at::kByte)); + size_t bytes = 0; + { + // The sizing queries the CuTeDSL layouts through Python, which takes the GIL itself. + py::gil_scoped_release release; + bytes = nvte_ep_overlap_workspace_size(hidden_dim, ffn_dim, num_local_experts, rows, + with_weight_grad, mxfp8, &layer_cfg); + } + return at::empty({static_cast(bytes)}, like.options().dtype(at::kByte)); } // MXFP8 operands are MXFP8 tensors (their data, scales and scale layout travel with them), BF16 From fd58e856d1d2d573944dd5cb1c0e4c7be99b689c Mon Sep 17 00:00:00 2001 From: Phuong Nguyen Date: Wed, 2 Dec 2026 23:41:47 -0800 Subject: [PATCH 41/67] [Common] Match the SM 10.7 EP overlap kernel launches to the FE Rubin classes Signed-off-by: Phuong Nguyen --- .../common/CuTeDSL/ep_gemm/combine_gemm.py | 23 +++++++++++----- .../common/CuTeDSL/ep_gemm/dispatch_gemm.py | 27 +++++++++++++++++-- 2 files changed, 41 insertions(+), 9 deletions(-) diff --git a/transformer_engine/common/CuTeDSL/ep_gemm/combine_gemm.py b/transformer_engine/common/CuTeDSL/ep_gemm/combine_gemm.py index db54333fb11..4751156caff 100644 --- a/transformer_engine/common/CuTeDSL/ep_gemm/combine_gemm.py +++ b/transformer_engine/common/CuTeDSL/ep_gemm/combine_gemm.py @@ -82,20 +82,29 @@ def build_kernel(cfg: CombineGemmConfig): caller_reset=True, clusters_beside_consumer=cfg.num_clusters, ) + if cfg.mxfp8 and is_sm107(): + if notify is not None or cfg.dependents_at_entry: + raise NotImplementedError( + "The SM 10.7 MXFP8 grouped GEMM (cuDNN FE moe_blockscaled_grouped_gemm_quant_rubin)" + " has no streaming_output_notify or launch_pdl_dependents_at_entry option, which" + " the overlapped MXFP8 combine needs." + ) + module = import_gemm_modules("moe_blockscaled_grouped_gemm_quant_rubin")[0] + return module.BlockScaledMoEGroupedGemmQuantKernel( + generate_sfd=False, + discrete_col_sfd=False, + generate_c=False, + enable_bias=False, + **blockscaled_kwargs(cfg.num_experts), + ) if cfg.mxfp8: - rubin = is_sm107() - module = import_gemm_modules( - "moe_blockscaled_grouped_gemm_quant_rubin" - if rubin - else "moe_blockscaled_grouped_gemm_quant_sm100" - )[0] + module = import_gemm_modules("moe_blockscaled_grouped_gemm_quant_sm100")[0] return module.BlockScaledMoEGroupedGemmQuantKernel( generate_sfd=False, discrete_col_sfd=False, enable_bias=False, streaming_output_notify=notify, launch_pdl_dependents_at_entry=cfg.dependents_at_entry, - **({"generate_c": False} if rubin else {}), **blockscaled_kwargs(cfg.num_experts), ) kernel_class, _ = import_bf16_kernel("combine") diff --git a/transformer_engine/common/CuTeDSL/ep_gemm/dispatch_gemm.py b/transformer_engine/common/CuTeDSL/ep_gemm/dispatch_gemm.py index 8c0418f1814..a6180abe614 100644 --- a/transformer_engine/common/CuTeDSL/ep_gemm/dispatch_gemm.py +++ b/transformer_engine/common/CuTeDSL/ep_gemm/dispatch_gemm.py @@ -142,6 +142,7 @@ def build_kernel(cfg: DispatchGemmConfig): return _backward_kernel_class(True)( discrete_col_sfd=True, act_func=backward_activation, + launch_pdl_dependents_at_entry=True, **deterministic, **common, ) @@ -166,7 +167,6 @@ def build_kernel(cfg: DispatchGemmConfig): act_func=cfg.activation, enable_bias=False, generate_c=True, - generate_sfd_col=False, device_layout=cfg.device_layout, **_tail_trigger(), **{**common, "vectorized_f32": True}, @@ -339,6 +339,11 @@ def _optional_rows_view(t, rows, cols): def _compile_backward_mxfp8(cfg: DispatchGemmConfig): """MXFP8 FC2 data gradient with the columnwise forward weight [experts, k, n] read N-major, SwiGLU backward in the epilogue, and the forward activation recomputed columnwise.""" + if cfg.h and is_sm107(): + raise NotImplementedError( + "The SM 10.7 MXFP8 dGLU kernel (cuDNN FE moe_blockscaled_grouped_gemm_dglu_rubin) has" + " no h output, the recomputed columnwise forward activation." + ) kernel, (rows, k, n, experts, num_clusters), tail = _prologue(cfg) n_slots = dprob_n_slots(n) if cfg.deterministic else 1 @@ -360,9 +365,27 @@ def launch( h_tensor=_optional_rows_view(h, rows, n), sfh_col_tensor=sfh_col, ) # fmt: skip + @cute.jit + def launch_rubin( + a, b, sfb, sfa, c, d, d_col, sfd_row, sfd_col, h, sfh_col, dprob, expert_row_ends, alpha, + prob, norm_const, workspace, stream, + ): # fmt: skip # pylint: disable=unused-argument + # The SM 10.7 kernel takes the SwiGLU linear offset ahead of dbias and has no h output. + weight = weight_view(b, n, k, experts, n_major=True) + dprob_out = ( + slots_view(dprob, rows, n_slots) if cfg.deterministic else prob_view(dprob, rows) + ) + kernel( + rows_view(a, rows, k), weight, sfb, cutlass.Int32(0), cutlass.Int32(0), + cutlass.Int64(0), OperandMajorMode.K, workspace.iterator, rows_view(c, rows, 2 * n), + rows_view(d, rows, 2 * n), _optional_rows_view(d_col, rows, 2 * n), sfa, sfd_row, + sfd_col, None, norm_const, expert_row_ends, alpha, alpha, prob_view(prob, rows), + dprob_out, cutlass.Float32(0.0), None, num_clusters, stream, + ) # fmt: skip + row_ends, alpha, prob, workspace = tail return compile_launch( - launch, + launch_rubin if is_sm107() else launch, fp8_fake((rows, k), (1, 0)), fp8_fake((experts, k, n), (2, 1, 0)), scale_fake(experts * n, k), From 71d8563d53a4d4649744a0fe0a437cecc566f786 Mon Sep 17 00:00:00 2001 From: Phuong Nguyen Date: Wed, 2 Dec 2026 23:51:24 -0800 Subject: [PATCH 42/67] [PyTorch] Test that the native EP overlap calls name a disabled CuTeDSL backend and align the native call helper Signed-off-by: Phuong Nguyen --- tests/pytorch/distributed/run_ep.py | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/tests/pytorch/distributed/run_ep.py b/tests/pytorch/distributed/run_ep.py index 5dabdd6a607..6b70e26a6ab 100644 --- a/tests/pytorch/distributed/run_ep.py +++ b/tests/pytorch/distributed/run_ep.py @@ -5,6 +5,7 @@ from dataclasses import replace import contextlib +import ctypes from contextlib import nullcontext import itertools import os @@ -2382,7 +2383,7 @@ def _native_dispatch_gemm_fwd(self, alignment, offsets_dtype=torch.int64): torch.zeros(rows, HIDDEN_DIM, dtype=torch.bfloat16, device=device), torch.zeros(rows, dtype=torch.float32, device=device), torch.zeros(NUM_LOCAL_EXPERTS, dtype=torch.int64, device=device), - torch.zeros(NUM_LOCAL_EXPERTS + 1, dtype=offsets_dtype, device=device), + torch.zeros(NUM_LOCAL_EXPERTS + 2, dtype=offsets_dtype, device=device)[1:], torch.zeros(rows, 2 * ffn, dtype=torch.bfloat16, device=device), torch.zeros(rows, ffn, dtype=torch.bfloat16, device=device), TOP_K, @@ -2406,6 +2407,22 @@ def test_moe_overlap_rejects_int32_expert_offsets(self): with self.assertRaisesRegex(RuntimeError, "(?i)int64"): self._native_dispatch_gemm_fwd(OVERLAP_ALIGNMENT, offsets_dtype=torch.int32) + @_mxfp8_align_test + @_overlap_test + def test_moe_overlap_names_disabled_cutedsl(self): + """With the CuTeDSL backend switched off at run time, the native overlapped calls name the + missing backend instead of failing inside the workspace layout query.""" + self._require_moe_overlap() + from transformer_engine.common import _get_shared_object_file + + core_lib = ctypes.CDLL(str(_get_shared_object_file("core"))) + core_lib.nvte_set_cutedsl_backend(0) + try: + with self.assertRaisesRegex(RuntimeError, "NVTE_ENABLE_CUTEDSL_BACKEND"): + self._native_dispatch_gemm_fwd(OVERLAP_ALIGNMENT) + finally: + core_lib.nvte_set_cutedsl_backend(1) + @_mxfp8_align_test @_overlap_test def test_moe_overlap_rejects_dispatch_chunk(self): From 905a6c8e7a5b2ce6b395f55189971a41e393b7e0 Mon Sep 17 00:00:00 2001 From: Phuong Nguyen Date: Thu, 3 Dec 2026 08:34:46 -0800 Subject: [PATCH 43/67] [PyTorch] Require MXFP8 EP transport recipes for MXFP8 FusedMoE and give each transport direction its own quantizer Signed-off-by: Phuong Nguyen --- tests/pytorch/distributed/run_ep.py | 19 +++--- .../pytorch/ops/fused/moe_overlap.py | 66 ++++++++++++------- 2 files changed, 52 insertions(+), 33 deletions(-) diff --git a/tests/pytorch/distributed/run_ep.py b/tests/pytorch/distributed/run_ep.py index 6b70e26a6ab..9e7b4363fc9 100644 --- a/tests/pytorch/distributed/run_ep.py +++ b/tests/pytorch/distributed/run_ep.py @@ -1840,7 +1840,8 @@ def test_moe_overlap_op(self): def test_moe_overlap_op_mxfp8(self): """Under MXFP8 with MXFP8 EP transport the fused op matches the unfused ops, with weight scales that differ across blocks in both directions. The fused op dispatches x and dY in - place from the EP dispatch window. An unset config transport runs MXFP8.""" + place from the EP dispatch window. A config whose dispatch or combine transport is not + MXFP8 is rejected.""" self._require_mxfp8_shapes() recipe = MXFP8BlockScaling() with mock.patch.object( @@ -1851,13 +1852,15 @@ def test_moe_overlap_op_mxfp8(self): self._check_moe_overlap_op(recipe, recipe) for call in fwd.call_args_list + bwd.call_args_list: self.assertEqual(call.kwargs["symm_input"], tex.ep_zero_copy_supported()) - # MXFP8 FusedMoE quantizes the EP transport itself, so an unset config transport fuses. - config = self._overlap_config() - model = te_ops.Sequential(*self._moe_ops(config, self._make_buffer_from_config(config))) - topk_idx, tokens, w = _make_identity_inputs(self.cfg.rank, self.cfg.ep_size) - with te.autocast(recipe=recipe): - model(tokens, topk_idx, w, topk_idx) - self._assert_fusion(model, True) + # An EP transport other than MXFP8 with MXFP8 GEMMs is rejected, per direction. + for name in ("dispatch_fwd_quant_recipe", "combine_bwd_quant_recipe"): + with self.subTest(unset=name): + config = replace(self._overlap_config(recipe), **{name: None}) + reason = _moe_overlap_unsupported_reason( + config, HIDDEN_DIM, params_dtype=torch.bfloat16, glu_interleave_size=32, + single_grouped_weight=True, recipe=recipe, + ) # fmt: skip + self.assertIn(name, reason or "") @_eager_test_include @_overflow_test_include diff --git a/transformer_engine/pytorch/ops/fused/moe_overlap.py b/transformer_engine/pytorch/ops/fused/moe_overlap.py index 71590a0dc55..76912904d2f 100644 --- a/transformer_engine/pytorch/ops/fused/moe_overlap.py +++ b/transformer_engine/pytorch/ops/fused/moe_overlap.py @@ -91,7 +91,8 @@ class FusedMoE(FusedOperation): with eager receive sizing (no ``recv_capacity_per_rank``) the host is synchronized and it cannot be captured. - Without a recipe the routing weights are applied in the activation; under - ``MXFP8BlockScaling`` the GEMMs and the EP transport run in MXFP8 and the routing weights + ``MXFP8BlockScaling`` the GEMMs and the EP transport run in MXFP8 (the config's dispatch + and combine transport recipes must both be ``MXFP8BlockScaling``) and the routing weights are applied to the second GEMM's output. Either way their gradient goes to the dispatch's ``topk_weights``. - The weights are prepared for the GEMMs (quantized to MXFP8) at each forward. @@ -446,14 +447,18 @@ def _backward_mxfp8(self, basic_op_ctxs, grad_output, grad_recv_weights_extra=No expert_token_offsets = fc1_ctx.expert_token_offsets grad_result = _bf16_grad_output(grad_output) num_tokens = grad_result.shape[0] - grad_result, symm_input = operands.dispatch_input(grad_result, device) + grad_result, symm_input = operands.grad_input(grad_result, device) def empty(quantizer, cols): return quantizer.make_empty((rows, cols), dtype=torch.bfloat16, device=device) # The call writes the columnwise grad_expert_out for the FC2 weight gradient. grad_expert_out = empty( - operands.transport_columnwise if fc2_ctx.weight_requires_grad else operands.transport, + ( + operands.combine_bwd_transport_columnwise + if fc2_ctx.weight_requires_grad + else operands.combine_bwd_transport + ), hidden, ) # The columnwise grad_gemm_out feeds the FC1 weight gradient and act_out the FC2 one, so @@ -472,7 +477,7 @@ def grouped(cols, data, scale, col_data, col_scale): # Expert slabs of a row-sized MXFP8 tensor with GEMM-swizzled scales. return GroupedTensorStorage( shape=(rows, cols), dtype=torch.bfloat16, num_tensors=num_groups, - quantizer=operands.transport, data=data, columnwise_data=col_data.view(-1), + quantizer=operands.gemm_both, data=data, columnwise_data=col_data.view(-1), scale_inv=scale, columnwise_scale_inv=col_scale, first_dims=first_dims, tensor_offsets=expert_token_offsets.long() * cols, with_gemm_swizzled_scales=True, ) # fmt: skip @@ -589,19 +594,33 @@ class _Mxfp8Operands: offload_slots = (0, 1, 2) def __init__(self) -> None: - # Transport tensors have compact scales, GEMM operands GEMM-swizzled ones. - self.transport = _mxfp8_quantizer(rowwise=True, columnwise=False, swizzled=False) - self.transport_columnwise = _mxfp8_quantizer(rowwise=True, columnwise=True, swizzled=False) + # Transport tensors have compact scales, GEMM operands GEMM-swizzled ones. Each direction + # has its own transport quantizer, independent of the GEMM operands'. + self.dispatch_transport = _mxfp8_quantizer(rowwise=True, columnwise=False, swizzled=False) + self.combine_bwd_transport = _mxfp8_quantizer( + rowwise=True, columnwise=False, swizzled=False + ) + self.combine_bwd_transport_columnwise = _mxfp8_quantizer( + rowwise=True, columnwise=True, swizzled=False + ) self.gemm_rowwise = _mxfp8_quantizer(rowwise=True, columnwise=False, swizzled=True) self.gemm_both = _mxfp8_quantizer(rowwise=True, columnwise=True, swizzled=True) self.gemm_columnwise = _mxfp8_quantizer(rowwise=False, columnwise=True, swizzled=True) def dispatch_input(self, input_, device): - """Dispatch input quantized to MXFP8, and whether the dispatch reads it in place from a - symm-mem window: the quantized rows are in the window whenever it exists, alike on every - rank.""" - window = _sym_dispatch_buffers(device, self.transport) - quantized, _ = quantize_for_ep(input_, self.transport, window) + """Forward dispatch input quantized to MXFP8, and whether the dispatch reads it in place + from a symm-mem window: the quantized rows are in the window whenever it exists, alike on + every rank.""" + return self._transport_input(input_, self.dispatch_transport, device) + + def grad_input(self, grad, device): + """Backward combine input (the result gradient), as ``dispatch_input``.""" + return self._transport_input(grad, self.combine_bwd_transport, device) + + @staticmethod + def _transport_input(input_, quantizer, device): + window = _sym_dispatch_buffers(device, quantizer) + quantized, _ = quantize_for_ep(input_, quantizer, window) return quantized, window is not None @staticmethod @@ -612,7 +631,7 @@ def forward_weight(weight): def recv_buffers(self, rows, hidden, ffn, device): """MXFP8 recv tokens, BF16 GEMM output and MXFP8 activation output.""" return ( - self.transport.make_empty((rows, hidden), dtype=torch.bfloat16, device=device), + self.dispatch_transport.make_empty((rows, hidden), dtype=torch.bfloat16, device=device), torch.empty(rows, 2 * ffn, dtype=torch.bfloat16, device=device), self.gemm_rowwise.make_empty((rows, ffn), dtype=torch.bfloat16, device=device), ) @@ -728,7 +747,7 @@ def _with_columnwise_data(recv_tokens, first_dims, expert_token_offsets, operand rows, hidden = recv_tokens._rowwise_data.shape grouped = GroupedTensorStorage( shape=(rows, hidden), dtype=torch.bfloat16, num_tensors=first_dims.numel(), - quantizer=operands.transport, data=recv_tokens._rowwise_data.view(-1), + quantizer=operands.dispatch_transport, data=recv_tokens._rowwise_data.view(-1), scale_inv=recv_tokens._rowwise_scale_inv.view(-1), first_dims=first_dims, tensor_offsets=expert_token_offsets.long() * hidden, ) # fmt: skip @@ -840,7 +859,8 @@ def _moe_overlap_unsupported_reason( ``single_grouped_weight`` of the GroupedLinear ops. recipe : Recipe, optional Quantization recipe the ops run under, ``None`` for BF16. Under ``MXFP8BlockScaling`` the - EP transport is MXFP8; ``config``'s transport recipes must be MXFP8BlockScaling or unset. + EP transport of each direction is MXFP8, so ``config``'s ``dispatch_fwd_quant_recipe`` and + ``combine_bwd_quant_recipe`` must both be MXFP8BlockScaling. primary_weights_in_fp8 : bool, default = ``False`` Whether the GroupedLinear weights are quantized parameters (``quantized_model_init``). They must be MXFP8 and need the ``MXFP8BlockScaling`` recipe. @@ -862,16 +882,12 @@ def _moe_overlap_unsupported_reason( return "quantized GEMMs other than MXFP8BlockScaling are not supported" if recipe.fp8_format != Format.E4M3 or recipe.backward_override is not None: return "MXFP8 needs fp8_format E4M3 and no backward_override" - # MXFP8 FusedMoE quantizes the EP transport itself, so the transport recipes need not be - # set; if set they must be MXFP8, not a different recipe. - if any( - r is not None and not isinstance(r, MXFP8BlockScaling) - for r in (config.dispatch_fwd_quant_recipe, config.combine_bwd_quant_recipe) - ): - return ( - "MXFP8 FusedMoE uses MXFP8 EP transport; dispatch_fwd_quant_recipe and" - " combine_bwd_quant_recipe must be MXFP8BlockScaling or unset" - ) + for name in ("dispatch_fwd_quant_recipe", "combine_bwd_quant_recipe"): + if not isinstance(getattr(config, name), MXFP8BlockScaling): + return ( + f"MXFP8 FusedMoE needs {name} to be MXFP8BlockScaling; an EP transport" + " other than MXFP8 with MXFP8 GEMMs is not supported yet" + ) if config.hidden_dim % 512 != 0 or ffn_hidden_size % _TILE != 0: return f"MXFP8 needs hidden_dim a multiple of 512 and ffn_hidden_size of {_TILE}" elif ( From 1c2acf326f4b4edcff6d18d11173a01e6b0a9b51 Mon Sep 17 00:00:00 2001 From: Phuong Nguyen Date: Thu, 3 Dec 2026 08:39:10 -0800 Subject: [PATCH 44/67] [PyTorch] Default the EP transport of MXFP8 FusedMoE to MXFP8 when the config leaves it unset Signed-off-by: Phuong Nguyen --- tests/pytorch/distributed/run_ep.py | 19 +++++++++++++------ .../pytorch/ops/fused/moe_overlap.py | 18 ++++++++++-------- 2 files changed, 23 insertions(+), 14 deletions(-) diff --git a/tests/pytorch/distributed/run_ep.py b/tests/pytorch/distributed/run_ep.py index 9e7b4363fc9..667493af9c8 100644 --- a/tests/pytorch/distributed/run_ep.py +++ b/tests/pytorch/distributed/run_ep.py @@ -21,7 +21,7 @@ import transformer_engine.pytorch as te from transformer_engine.pytorch import ops as te_ops from transformer_engine.pytorch.ops.fused.moe_overlap import _moe_overlap_unsupported_reason -from transformer_engine.common.recipe import MXFP8BlockScaling +from transformer_engine.common.recipe import Float8CurrentScaling, MXFP8BlockScaling from transformer_engine.pytorch.ep import ( EpBuffer, EpConfig, @@ -1840,8 +1840,8 @@ def test_moe_overlap_op(self): def test_moe_overlap_op_mxfp8(self): """Under MXFP8 with MXFP8 EP transport the fused op matches the unfused ops, with weight scales that differ across blocks in both directions. The fused op dispatches x and dY in - place from the EP dispatch window. A config whose dispatch or combine transport is not - MXFP8 is rejected.""" + place from the EP dispatch window. An unset config transport runs MXFP8; another + transport recipe is rejected.""" self._require_mxfp8_shapes() recipe = MXFP8BlockScaling() with mock.patch.object( @@ -1852,10 +1852,17 @@ def test_moe_overlap_op_mxfp8(self): self._check_moe_overlap_op(recipe, recipe) for call in fwd.call_args_list + bwd.call_args_list: self.assertEqual(call.kwargs["symm_input"], tex.ep_zero_copy_supported()) - # An EP transport other than MXFP8 with MXFP8 GEMMs is rejected, per direction. + # An unset config transport defaults to MXFP8, so it fuses. + config = self._overlap_config() + model = te_ops.Sequential(*self._moe_ops(config, self._make_buffer_from_config(config))) + topk_idx, tokens, w = _make_identity_inputs(self.cfg.rank, self.cfg.ep_size) + with te.autocast(recipe=recipe): + model(tokens, topk_idx, w, topk_idx) + self._assert_fusion(model, True) + # A transport recipe other than MXFP8 with MXFP8 GEMMs is rejected, per direction. for name in ("dispatch_fwd_quant_recipe", "combine_bwd_quant_recipe"): - with self.subTest(unset=name): - config = replace(self._overlap_config(recipe), **{name: None}) + with self.subTest(other_recipe=name): + config = replace(self._overlap_config(recipe), **{name: Float8CurrentScaling()}) reason = _moe_overlap_unsupported_reason( config, HIDDEN_DIM, params_dtype=torch.bfloat16, glu_interleave_size=32, single_grouped_weight=True, recipe=recipe, diff --git a/transformer_engine/pytorch/ops/fused/moe_overlap.py b/transformer_engine/pytorch/ops/fused/moe_overlap.py index 76912904d2f..f4a4fd515be 100644 --- a/transformer_engine/pytorch/ops/fused/moe_overlap.py +++ b/transformer_engine/pytorch/ops/fused/moe_overlap.py @@ -91,9 +91,9 @@ class FusedMoE(FusedOperation): with eager receive sizing (no ``recv_capacity_per_rank``) the host is synchronized and it cannot be captured. - Without a recipe the routing weights are applied in the activation; under - ``MXFP8BlockScaling`` the GEMMs and the EP transport run in MXFP8 (the config's dispatch - and combine transport recipes must both be ``MXFP8BlockScaling``) and the routing weights - are applied to the second GEMM's output. Either way their gradient goes to the dispatch's + ``MXFP8BlockScaling`` the GEMMs and the EP transport run in MXFP8 (an unset transport + recipe of the config defaults to MXFP8; another recipe is not supported yet) and the + routing weights are applied to the second GEMM's output. Either way their gradient goes to the dispatch's ``topk_weights``. - The weights are prepared for the GEMMs (quantized to MXFP8) at each forward. """ @@ -859,8 +859,8 @@ def _moe_overlap_unsupported_reason( ``single_grouped_weight`` of the GroupedLinear ops. recipe : Recipe, optional Quantization recipe the ops run under, ``None`` for BF16. Under ``MXFP8BlockScaling`` the - EP transport of each direction is MXFP8, so ``config``'s ``dispatch_fwd_quant_recipe`` and - ``combine_bwd_quant_recipe`` must both be MXFP8BlockScaling. + EP transport of each direction is MXFP8: ``config``'s ``dispatch_fwd_quant_recipe`` and + ``combine_bwd_quant_recipe`` must be MXFP8BlockScaling or unset, which defaults to MXFP8. primary_weights_in_fp8 : bool, default = ``False`` Whether the GroupedLinear weights are quantized parameters (``quantized_model_init``). They must be MXFP8 and need the ``MXFP8BlockScaling`` recipe. @@ -882,11 +882,13 @@ def _moe_overlap_unsupported_reason( return "quantized GEMMs other than MXFP8BlockScaling are not supported" if recipe.fp8_format != Format.E4M3 or recipe.backward_override is not None: return "MXFP8 needs fp8_format E4M3 and no backward_override" + # An unset transport recipe defaults to MXFP8; another recipe is not supported yet. for name in ("dispatch_fwd_quant_recipe", "combine_bwd_quant_recipe"): - if not isinstance(getattr(config, name), MXFP8BlockScaling): + transport_recipe = getattr(config, name) + if transport_recipe is not None and not isinstance(transport_recipe, MXFP8BlockScaling): return ( - f"MXFP8 FusedMoE needs {name} to be MXFP8BlockScaling; an EP transport" - " other than MXFP8 with MXFP8 GEMMs is not supported yet" + f"MXFP8 FusedMoE needs {name} to be MXFP8BlockScaling or unset; an EP" + " transport other than MXFP8 with MXFP8 GEMMs is not supported yet" ) if config.hidden_dim % 512 != 0 or ffn_hidden_size % _TILE != 0: return f"MXFP8 needs hidden_dim a multiple of 512 and ffn_hidden_size of {_TILE}" From 1c0bd1427539fe430ce98113abecff40d631553f Mon Sep 17 00:00:00 2001 From: Phuong Nguyen Date: Thu, 3 Dec 2026 09:04:35 -0800 Subject: [PATCH 45/67] [Common] Build the EP overlap GEMM configs of workspace sizing and launches with shared per-direction helpers Signed-off-by: Phuong Nguyen --- transformer_engine/common/ep/ep_gemm_api.cpp | 96 +++++++++++++------- 1 file changed, 64 insertions(+), 32 deletions(-) diff --git a/transformer_engine/common/ep/ep_gemm_api.cpp b/transformer_engine/common/ep/ep_gemm_api.cpp index 92bdc21758e..6ea0dad4347 100644 --- a/transformer_engine/common/ep/ep_gemm_api.cpp +++ b/transformer_engine/common/ep/ep_gemm_api.cpp @@ -174,6 +174,53 @@ ep::EpCombineGemmConfig combine_fwd_config(const EpGemmContext& ctx, size_t rows ctx.all_clusters}; } +// The forward dispatch_gemm GEMM of [rows, hidden] tokens and n output columns. +ep::EpDispatchGemmConfig dispatch_fwd_config(const EpGemmContext& ctx, size_t rows, size_t hidden, + size_t n, size_t num_experts, + NVTEScalingMode scaling_mode) { + return ep::EpDispatchGemmConfig{ + rows, hidden, n, + num_experts, ctx.num_clusters, false, + scaling_mode, ctx.alignment(), dispatch_writes_layout(ctx, num_experts)}; +} + +// The backward combine_gemm GEMM: the data gradient of [rows, hidden] inputs and ffn output columns. +// The routing-weight gradient is summed in a fixed order unless the layer allows atomics. +ep::EpDispatchGemmConfig combine_bwd_config(const EpGemmContext& ctx, size_t rows, size_t hidden, + size_t ffn, size_t num_experts, + NVTEScalingMode scaling_mode) { + ep::EpDispatchGemmConfig config{ + rows, hidden, ffn, num_experts, ctx.num_clusters, true, scaling_mode, ctx.alignment()}; + config.deterministic = ctx.layer_cfg.allow_nondeterministic == 0; + return config; +} + +// With the weight gradient the dispatch backward starts behind the weight gradient's base, which +// waits for the GEMM to complete: the GEMM publishes nothing and runs in the stock tile order. +bool dispatch_bwd_plain(const EpGemmContext& ctx, bool with_wgrad) { + return with_wgrad && ctx.num_clusters > 0; +} + +// The backward dispatch_gemm GEMM of [rows, k] inputs and hidden output columns. With the weight +// gradient it runs alone on every SM. The combine's chunk schedule is the group's, so peers agree +// on it whether or not this rank computes a weight gradient. +ep::EpCombineGemmConfig dispatch_bwd_config(const EpGemmContext& ctx, size_t rows, size_t k, + size_t hidden, size_t num_experts, + NVTEScalingMode scaling_mode, bool with_wgrad) { + const bool plain = dispatch_bwd_plain(ctx, with_wgrad); + const size_t chunk = combine_chunk(hidden, ctx.group.overlap_config.combine_chunk_hidden); + return ep::EpCombineGemmConfig{rows, + k, + hidden, + num_experts, + with_wgrad ? ctx.all_clusters : ctx.num_clusters, + plain ? 0 : chunk, + !plain, + true, + scaling_mode, + ctx.alignment()}; +} + // Per-call scratch for the GEMM's readiness flags and state, sliced from the caller's workspace. // ScratchLayout is the byte layout; nvte_ep_overlap_workspace_size uses it to size the workspace // without a buffer, and claim_scratch uses it to resolve the pointers in GemmScratch. @@ -553,9 +600,7 @@ size_t nvte_ep_overlap_workspace_size(size_t hidden_dim, size_t ffn_dim, size_t // Forward dispatch: FC1 + SwiGLU, no weight gradient. { const EpGemmContext ctx = make_context(layer_cfg, &NVTEEpSmConfig::dispatch_fwd_num_sms); - consider(ep::EpDispatchGemmConfig{rows, hidden_dim, 2 * ffn_dim, ne, ctx.num_clusters, false, - mx, ctx.alignment(), dispatch_writes_layout(ctx, ne)}, - false, 0); + consider(dispatch_fwd_config(ctx, rows, hidden_dim, 2 * ffn_dim, ne, mx), false, 0); } // Forward combine: FC2. Size the unit-probs row buffer, which the MXFP8 path omits. { @@ -568,22 +613,19 @@ size_t nvte_ep_overlap_workspace_size(size_t hidden_dim, size_t ffn_dim, size_t const size_t wgrad = wg ? wgrad_workspace_bytes(ctx, rows, hidden_dim, ffn_dim, ne, mx) : 0; // The slots of a deterministic routing-weight gradient are sized for every call, so the // workspace fits either mode. - ep::EpDispatchGemmConfig config{rows, hidden_dim, ffn_dim, ne, ctx.num_clusters, - true, mx, ctx.alignment()}; - config.deterministic = ctx.layer_cfg.allow_nondeterministic == 0; + const ep::EpDispatchGemmConfig config = + combine_bwd_config(ctx, rows, hidden_dim, ffn_dim, ne, mx); const size_t slots_bytes = rows * ep::dprob_slots_per_row(ffn_dim) * sizeof(float); consider(config, false, wgrad, slots_bytes); } // Backward dispatch: FC1 dgrad, with the FC1 weight gradient [2 * ffn, hidden]. { const EpGemmContext ctx = make_context(layer_cfg, &NVTEEpSmConfig::combine_bwd_num_sms); - const bool plain = wg && ctx.num_clusters > 0; + const bool plain = dispatch_bwd_plain(ctx, wg); const size_t chunk = combine_chunk(hidden_dim, ctx.group.overlap_config.combine_chunk_hidden); const size_t wgrad = wg ? wgrad_workspace_bytes(ctx, rows, 2 * ffn_dim, hidden_dim, ne, mx) : 0; - consider(ep::EpCombineGemmConfig{rows, 2 * ffn_dim, hidden_dim, ne, - wg ? ctx.all_clusters : ctx.num_clusters, plain ? 0 : chunk, - !plain, true, mx, ctx.alignment()}, - true, wgrad, 0, plain ? DIVUP(hidden_dim, chunk) : 0); + consider(dispatch_bwd_config(ctx, rows, 2 * ffn_dim, hidden_dim, ne, mx, wg), true, wgrad, 0, + plain ? DIVUP(hidden_dim, chunk) : 0); } return need; } @@ -643,15 +685,13 @@ void nvte_ep_dispatch_gemm_fwd(NVTETensor handle_mem, const NVTETensor topk_idx, "tokens and weight must be bfloat16 or MXFP8"); } - // No count exchange before the dispatch when the dispatch writes the GEMM's expert layout. - const bool device_layout = dispatch_writes_layout(ctx, num_experts); - // The GEMM runs beside the dispatch, and its tail on the SMs the dispatch frees. Both launches // claim tiles from one workspace. ep::WorkspaceLayout layout; - ep::EpDispatchGemmConfig config{rows, hidden, n, - num_experts, ctx.num_clusters, false, - scaling_mode, ctx.alignment(), device_layout}; + const ep::EpDispatchGemmConfig config = + dispatch_fwd_config(ctx, rows, hidden, n, num_experts, scaling_mode); + // No count exchange before the dispatch when the dispatch writes the GEMM's expert layout. + const bool device_layout = config.device_layout; std::vector gemms{get_gemm(config, &layout)}; const int tail_clusters = ctx.all_clusters - ctx.num_clusters; if (tail_clusters > 0) { @@ -875,15 +915,14 @@ void nvte_ep_combine_gemm_bwd( num_experts, scaling_mode, wgrad_signal_tokens); ep::WorkspaceLayout layout; - ep::EpDispatchGemmConfig config{ - rows, hidden, ffn, num_experts, ctx.num_clusters, true, scaling_mode, ctx.alignment()}; + ep::EpDispatchGemmConfig config = + combine_bwd_config(ctx, rows, hidden, ffn, num_experts, scaling_mode); // MXFP8: the columnwise grad_gemm_out and act_out are written when set. config.d_col = mxfp8 && nvte_get_tensor_param(grad_gemm_out, kNVTEColumnwiseData).data_ptr != nullptr; config.h = act_out != nullptr; // The GEMM writes each row's routing-weight gradient into one slot per output tile, which a // kernel after the weight gradient sums in a fixed order; or adds it atomically. - config.deterministic = ctx.layer_cfg.allow_nondeterministic == 0; const size_t dprob_slots_per_row = ep::dprob_slots_per_row(ffn); NVTE_CHECK(rows * dprob_slots_per_row <= static_cast(INT_MAX), "too many routing-weight gradient slots: ", rows, " x ", dprob_slots_per_row); @@ -1046,22 +1085,15 @@ void nvte_ep_dispatch_gemm_bwd(NVTETensor handle_mem, const NVTETensor grad_gemm // MXFP8: the call writes the columnwise wgrad_input from its rowwise data when that is set. const bool requant = wgrad && mxfp8 && nvte_get_tensor_param(wgrad_input, kNVTERowwiseData).data_ptr != nullptr; - // With the weight gradient the dispatch backward starts behind the weight gradient's base, which - // waits for the GEMM to complete: the GEMM publishes nothing and runs in the stock tile order, - // and the one flag of the whole row is reset to 0, published. - const bool plain = wgrad && ctx.num_clusters > 0; - // The combine's chunk schedule is the group's on every rank, whether or not this rank computes a - // weight gradient; peers must agree on it. + // The one flag of the whole row of a plain GEMM is reset to 0, published. + const bool plain = dispatch_bwd_plain(ctx, wgrad.has_value()); const size_t chunk = combine_chunk(hidden, ctx.group.overlap_config.combine_chunk_hidden); - const size_t n_chunk = plain ? 0 : chunk; const size_t num_chunks = DIVUP(hidden, chunk); - // With the weight gradient the GEMM runs alone on every SM, and the weight gradient beside the - // dispatch backward. + // With the weight gradient the weight gradient runs beside the dispatch backward. ep::WorkspaceLayout layout; - ep::EpCombineGemmConfig config{ - rows, k, hidden, num_experts, wgrad ? ctx.all_clusters : ctx.num_clusters, - n_chunk, !plain, true, scaling_mode, ctx.alignment()}; + const ep::EpCombineGemmConfig config = + dispatch_bwd_config(ctx, rows, k, hidden, num_experts, scaling_mode, wgrad.has_value()); const tvm::ffi::Function gemm = get_gemm(config, &layout); GemmScratch scratch = claim_scratch(ws_base, ws_bytes, layout.total_bytes, num_experts, rows, true, From 7a918bca6aed1e099b9233d2cf791f523e27f676 Mon Sep 17 00:00:00 2001 From: Phuong Nguyen Date: Thu, 3 Dec 2026 09:47:23 -0800 Subject: [PATCH 46/67] [PyTorch] Test that the cold EP overlap workspace sizing from two host threads completes Signed-off-by: Phuong Nguyen --- tests/pytorch/distributed/run_ep.py | 39 +++++++++++++++++++++++++++-- 1 file changed, 37 insertions(+), 2 deletions(-) diff --git a/tests/pytorch/distributed/run_ep.py b/tests/pytorch/distributed/run_ep.py index 667493af9c8..7f61f934277 100644 --- a/tests/pytorch/distributed/run_ep.py +++ b/tests/pytorch/distributed/run_ep.py @@ -10,6 +10,7 @@ import itertools import os import sys +import threading import unittest from unittest import mock @@ -2376,11 +2377,10 @@ def test_moe_overlap_rejects_int32_counts(self): with self.assertRaisesRegex(TypeError, "int64"): self._moe_call(model, tokens, topk_idx, w, grad) - def _native_dispatch_gemm_fwd(self, alignment, offsets_dtype=torch.int64): + def _native_dispatch_gemm_fwd(self, alignment, offsets_dtype=torch.int64, ffn=256): """tex.ep_dispatch_gemm_fwd on zero operands, as a caller that bypasses FusedMoE.""" device = self.cfg.device buffer = self._make_buffer_from_config(self._overlap_config()) - ffn = 256 rows = buffer.recv_capacity_per_rank or 2 * OVERLAP_ALIGNMENT return tex.ep_dispatch_gemm_fwd( buffer.handle_mem, @@ -2417,6 +2417,41 @@ def test_moe_overlap_rejects_int32_expert_offsets(self): with self.assertRaisesRegex(RuntimeError, "(?i)int64"): self._native_dispatch_gemm_fwd(OVERLAP_ALIGNMENT, offsets_dtype=torch.int32) + @_mxfp8_align_test + @_overlap_test + def test_moe_overlap_cold_sizing_from_two_threads(self): + """The first workspace sizing of a shape queries the CuTeDSL layouts through Python. Two + host threads sizing the same cold shape, and two different ones, both finish.""" + self._require_moe_overlap() + for ffns in ((320, 320), (384, 448)): + with self.subTest(ffns=ffns): + barrier = threading.Barrier(2) + errors = [None, None] + + def size(idx, ffn): + torch.cuda.set_device(self.cfg.device) + barrier.wait() + # The int32 offsets fail the call after its sizing, before any launch. + try: + self._native_dispatch_gemm_fwd( + OVERLAP_ALIGNMENT, offsets_dtype=torch.int32, ffn=ffn + ) + except RuntimeError as err: + errors[idx] = err + + threads = [ + threading.Thread(target=size, args=(idx, ffn), daemon=True) + for idx, ffn in enumerate(ffns) + ] + for thread in threads: + thread.start() + for thread in threads: + thread.join(timeout=120) + self.assertFalse(any(t.is_alive() for t in threads), "the cold sizing hangs") + for err in errors: + self.assertIsNotNone(err) + self.assertRegex(str(err), "(?i)int64") + @_mxfp8_align_test @_overlap_test def test_moe_overlap_names_disabled_cutedsl(self): From 07862d1024628cc5fe0b2a5bc9668b0df49f32bb Mon Sep 17 00:00:00 2001 From: Phuong Nguyen Date: Thu, 3 Dec 2026 10:31:18 -0800 Subject: [PATCH 47/67] [Common] Size the EP overlap backward combine workspace for both determinism modes Signed-off-by: Phuong Nguyen --- transformer_engine/common/ep/ep_gemm_api.cpp | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/transformer_engine/common/ep/ep_gemm_api.cpp b/transformer_engine/common/ep/ep_gemm_api.cpp index 6ea0dad4347..3199b72973b 100644 --- a/transformer_engine/common/ep/ep_gemm_api.cpp +++ b/transformer_engine/common/ep/ep_gemm_api.cpp @@ -184,7 +184,8 @@ ep::EpDispatchGemmConfig dispatch_fwd_config(const EpGemmContext& ctx, size_t ro scaling_mode, ctx.alignment(), dispatch_writes_layout(ctx, num_experts)}; } -// The backward combine_gemm GEMM: the data gradient of [rows, hidden] inputs and ffn output columns. +// The backward combine_gemm GEMM: the data gradient of [rows, hidden] inputs and ffn output +// columns. // The routing-weight gradient is summed in a fixed order unless the layer allows atomics. ep::EpDispatchGemmConfig combine_bwd_config(const EpGemmContext& ctx, size_t rows, size_t hidden, size_t ffn, size_t num_experts, @@ -611,12 +612,14 @@ size_t nvte_ep_overlap_workspace_size(size_t hidden_dim, size_t ffn_dim, size_t { const EpGemmContext ctx = make_context(layer_cfg, &NVTEEpSmConfig::dispatch_bwd_num_sms); const size_t wgrad = wg ? wgrad_workspace_bytes(ctx, rows, hidden_dim, ffn_dim, ne, mx) : 0; - // The slots of a deterministic routing-weight gradient are sized for every call, so the - // workspace fits either mode. - const ep::EpDispatchGemmConfig config = - combine_bwd_config(ctx, rows, hidden_dim, ffn_dim, ne, mx); + // The call's mode is not known here, so size both the atomic and the deterministic + // routing-weight gradient. + ep::EpDispatchGemmConfig config = combine_bwd_config(ctx, rows, hidden_dim, ffn_dim, ne, mx); const size_t slots_bytes = rows * ep::dprob_slots_per_row(ffn_dim) * sizeof(float); - consider(config, false, wgrad, slots_bytes); + for (const bool deterministic : {false, true}) { + config.deterministic = deterministic; + consider(config, false, wgrad, deterministic ? slots_bytes : 0); + } } // Backward dispatch: FC1 dgrad, with the FC1 weight gradient [2 * ffn, hidden]. { From 27d683cfffcafb9dbe0136ec82f24081a4de7154 Mon Sep 17 00:00:00 2001 From: Phuong Nguyen Date: Thu, 3 Dec 2026 10:31:18 -0800 Subject: [PATCH 48/67] [PyTorch][Common] Test the EP prepare expert offsets output and the MXFP8 branches of the FusedMoE support reasons Signed-off-by: Phuong Nguyen --- tests/cpp_distributed/test_ep.cu | 40 +++++++++++++++++++++++++ tests/pytorch/test_nccl_ep_discovery.py | 33 ++++++++++++++++++++ 2 files changed, 73 insertions(+) diff --git a/tests/cpp_distributed/test_ep.cu b/tests/cpp_distributed/test_ep.cu index b94043c02f1..5de9abdd016 100644 --- a/tests/cpp_distributed/test_ep.cu +++ b/tests/cpp_distributed/test_ep.cu @@ -391,6 +391,46 @@ TYPED_TEST(EPDispatchTest, PrepareAndDispatch) { NVTE_CHECK_CUDA(cudaStreamDestroy(stream)); } +// nvte_ep_prepare writes the padded start row of each local expert to expert_offsets. +TYPED_TEST(EPDispatchTest, PrepareExpertOffsets) { + using Tok = TypeParam; + EP_PULL_FIXTURE(); + for (const size_t alignment : {size_t{0}, size_t{16}}) { + EPBuffers buf; + buf.alloc(num_tokens_, top_k_, hidden_dim_, num_local_experts_, + ep_size_, max_tokens_per_rank_, alignment); + this->template upload_inputs(buf); + EPTensors t(buf, num_tokens_, top_k_, hidden_dim_, num_local_experts_); + DevBuf d_offsets; + d_offsets.alloc(num_local_experts_); + NVTE_CHECK_CUDA(cudaMemset(d_offsets.get(), 0xFF, d_offsets.bytes())); // -1: unwritten + TensorWrapper offsets(d_offsets.get(), std::vector{(size_t)num_local_experts_}, + DType::kInt32); + + cudaStream_t stream; + NVTE_CHECK_CUDA(cudaStreamCreate(&stream)); + ASSERT_NO_THROW(nvte_ep_prepare(t.handle_mem.data(), t.topk_idx.data(), + t.recv_tokens_per_expert.data(), nullptr, offsets.data(), + &t.layer_cfg_, stream)); + NVTE_CHECK_CUDA(cudaStreamSynchronize(stream)); + + std::vector counts(num_local_experts_), starts(num_local_experts_); + NVTE_CHECK_CUDA(cudaMemcpy(counts.data(), buf.recv_tokens_per_expert.get(), + counts.size() * sizeof(int32_t), cudaMemcpyDeviceToHost)); + NVTE_CHECK_CUDA(cudaMemcpy(starts.data(), d_offsets.get(), starts.size() * sizeof(int32_t), + cudaMemcpyDeviceToHost)); + int32_t expected_start = 0; + for (int e = 0; e < num_local_experts_; ++e) { + EXPECT_EQ(starts[e], expected_start) << "alignment " << alignment << ", local expert " << e; + const int32_t align = static_cast(alignment); + expected_start += align > 1 ? (counts[e] + align - 1) / align * align : counts[e]; + } + ASSERT_LE(expected_start, static_cast(buf.recv_capacity)); + NVTE_CHECK_CUDA(cudaStreamDestroy(stream)); + } + if (g_process_id == 0) printf(" PrepareExpertOffsets: passed (starts follow the counts)\n"); +} + // ============================================================================= // EPDispatchScaledTest: MXFP8 dispatch routes each token's e8m0 scale row in // lockstep with its e4m3 data row. diff --git a/tests/pytorch/test_nccl_ep_discovery.py b/tests/pytorch/test_nccl_ep_discovery.py index e2d40a75561..2ea66763cf6 100644 --- a/tests/pytorch/test_nccl_ep_discovery.py +++ b/tests/pytorch/test_nccl_ep_discovery.py @@ -5,6 +5,12 @@ import pytest import transformer_engine +from transformer_engine.common.recipe import ( + DelayedScaling, + Float8CurrentScaling, + Format, + MXFP8BlockScaling, +) def _hide_packaged_library(monkeypatch): @@ -125,6 +131,33 @@ def _overlap_ep_config(**overrides): ({}, {"activation": "ScaledGeGLU"}, "SwiGLU"), ({}, {"glu_interleave_size": 16}, "glu_interleave_size 32"), ({}, {"glu_interleave_size": None}, "glu_interleave_size 32"), + ({}, {"recipe": MXFP8BlockScaling()}, None), + ( + { + "dispatch_fwd_quant_recipe": MXFP8BlockScaling(), + "combine_bwd_quant_recipe": MXFP8BlockScaling(), + }, + {"recipe": MXFP8BlockScaling()}, + None, + ), + ( + {"dispatch_fwd_quant_recipe": Float8CurrentScaling()}, + {"recipe": MXFP8BlockScaling()}, + "dispatch_fwd_quant_recipe", + ), + ( + {"combine_bwd_quant_recipe": Float8CurrentScaling()}, + {"recipe": MXFP8BlockScaling()}, + "combine_bwd_quant_recipe", + ), + ({}, {"recipe": DelayedScaling()}, "other than MXFP8BlockScaling"), + ({}, {"recipe": MXFP8BlockScaling(fp8_format=Format.HYBRID)}, "E4M3"), + ({"hidden_dim": 768}, {"recipe": MXFP8BlockScaling()}, "multiple of 512"), + ( + {"dispatch_fwd_quant_recipe": MXFP8BlockScaling()}, + {}, + "BF16 FusedMoE cannot use a quantized EP transport recipe", + ), ], ) def test_moe_overlap_unsupported_reason(monkeypatch, config_overrides, reason_overrides, expected): From f869ceadbef13134f44c32b8eaa281fe95cc604e Mon Sep 17 00:00:00 2001 From: Phuong Nguyen Date: Thu, 3 Dec 2026 10:37:15 -0800 Subject: [PATCH 49/67] [PyTorch] Drop the cuDNN frontend int64 offsets probe and rely on the cuDNN version guard Signed-off-by: Phuong Nguyen --- tests/pytorch/test_grouped_mlp.py | 34 ------------------- transformer_engine/pytorch/ep.py | 8 ++--- .../pytorch/ops/fused/grouped_mlp.py | 17 ++-------- .../pytorch/ops/fused/moe_overlap.py | 3 +- 4 files changed, 5 insertions(+), 57 deletions(-) diff --git a/tests/pytorch/test_grouped_mlp.py b/tests/pytorch/test_grouped_mlp.py index cf9555e7975..055598a0c2d 100644 --- a/tests/pytorch/test_grouped_mlp.py +++ b/tests/pytorch/test_grouped_mlp.py @@ -1837,10 +1837,7 @@ def test_grouped_mlp_mxfp8_offsets_dtype(self, monkeypatch) -> None: if not device_is_blackwell: pytest.skip("Requires Blackwell") import cudnn - from cudnn.gemm.cutedsl import grouped - if not getattr(grouped, "INT64_OFFSETS", False): - pytest.skip("The cuDNN frontend takes only int32 offsets") offsets_dtypes = {} for name, key in ( ("grouped_gemm_glu_wrapper_sm100", "padded_offsets"), @@ -4871,37 +4868,6 @@ def test_distributed_weight_dispatch(self) -> None: shard.main_grad.bfloat16(), ref_grad[: shard.shape[0]], rtol=0, atol=0 ) - def test_int64_offsets(self, monkeypatch) -> None: - """int64 cuDNN offsets give the results of int32 ones.""" - self._skip_unless_bf16_fusion() - if not grouped_mlp_module._cudnn_frontend_supports_int64_offsets(): - pytest.skip("The cuDNN frontend takes only int32 offsets") - fused_cls = grouped_mlp_module.GroupedMLP_CuTeGEMMGLUBf16 - num_groups = 2 - ops = _bf16_mlp_ops(num_groups=num_groups, single_grouped_weight=True) - split_sizes, x_ref, probs_ref = _bf16_mlp_inputs(ops, num_groups) - dy = torch.randn(x_ref.shape[0], ops[2].out_features, dtype=torch.bfloat16, device="cuda") - outs = [] - for int64_offsets in (False, True): - monkeypatch.setattr( - grouped_mlp_module, - "_cudnn_frontend_supports_int64_offsets", - lambda value=int64_offsets: value, - ) - model = te.ops.Sequential(*ops) - x = x_ref.clone().requires_grad_(True) - probs = probs_ref.clone().requires_grad_(True) - for p in model.parameters(): - p.grad = None - y = model(x, split_sizes, probs, split_sizes) - y.backward(dy) - assert isinstance(model._module_groups[0]._forward_ops[0][0], fused_cls) - outs.append((probs.grad, y, x.grad, *(p.grad for p in model.parameters()))) - # dprob is summed with atomics. - torch.testing.assert_close(outs[1][0], outs[0][0], **dtype_tols(torch.bfloat16)) - for got, want in zip(outs[1][1:], outs[0][1:]): - torch.testing.assert_close(got, want, rtol=0, atol=0) - @pytest.mark.parametrize( "fc1_scale_bias,fc2_scale_bias,should_fuse", ((False, True, True), (True, False, False), (True, True, False)), diff --git a/transformer_engine/pytorch/ep.py b/transformer_engine/pytorch/ep.py index ec85400b91c..e6306330317 100644 --- a/transformer_engine/pytorch/ep.py +++ b/transformer_engine/pytorch/ep.py @@ -341,8 +341,7 @@ def get_ep_drop_on_overflow() -> Optional[bool]: def _moe_overlap_available() -> bool: """Whether the overlapped MoE GEMMs can run: SM 10.0, 10.3 or 10.7 (tcgen05 kernels), the - CuTeDSL backend built and on, the GEMM path set, and cuDNN FE grouped kernels that take int64 - expert offsets.""" + CuTeDSL backend built and on, and the GEMM path set.""" if not torch.cuda.is_available(): return False if not ( @@ -352,10 +351,7 @@ def _moe_overlap_available() -> bool: and cutedsl_backend_built() ): return False - # pylint: disable-next=import-outside-toplevel - from .ops.fused.grouped_mlp import _cudnn_frontend_supports_int64_offsets - - return _cudnn_frontend_supports_int64_offsets() + return True def _ep_is_eager() -> bool: diff --git a/transformer_engine/pytorch/ops/fused/grouped_mlp.py b/transformer_engine/pytorch/ops/fused/grouped_mlp.py index 9b04f00d1bf..94f7d587938 100644 --- a/transformer_engine/pytorch/ops/fused/grouped_mlp.py +++ b/transformer_engine/pytorch/ops/fused/grouped_mlp.py @@ -79,17 +79,7 @@ def _cudnn_frontend_version_at_least(min_version: str) -> bool: def _cudnn_frontend_version_supported() -> bool: """Check the minimum cuDNN frontend version for block-scaled grouped MLP.""" - return _cudnn_frontend_version_at_least("1.31.0") and _cudnn_frontend_supports_int64_offsets() - - -@functools.lru_cache(maxsize=None) -def _cudnn_frontend_supports_int64_offsets() -> bool: - """Whether the cuDNN FE grouped GEMMs take the int64 expert offsets passed to them.""" - try: - from cudnn.gemm.cutedsl import grouped # pylint: disable=import-outside-toplevel - except ImportError: - return False - return bool(getattr(grouped, "INT64_OFFSETS", False)) + return _cudnn_frontend_version_at_least("1.31.0") @functools.lru_cache(maxsize=None) @@ -3698,10 +3688,7 @@ def is_supported(cls) -> bool: if not (device_arch[0] == 10 and device_arch[1] < 7): return False # Canonical layouts and device-only offsets need cuDNN frontend PR #1602. - if not ( - _cudnn_frontend_version_at_least(_BF16_MIN_CUDNN_FRONTEND_VERSION) - and _cudnn_frontend_supports_int64_offsets() - ): + if not _cudnn_frontend_version_at_least(_BF16_MIN_CUDNN_FRONTEND_VERSION): return False try: kernels = ( diff --git a/transformer_engine/pytorch/ops/fused/moe_overlap.py b/transformer_engine/pytorch/ops/fused/moe_overlap.py index f4a4fd515be..4bc30696765 100644 --- a/transformer_engine/pytorch/ops/fused/moe_overlap.py +++ b/transformer_engine/pytorch/ops/fused/moe_overlap.py @@ -868,8 +868,7 @@ def _moe_overlap_unsupported_reason( if not FusedMoE.is_supported(): return ( "needs SM 10.0, 10.3 or 10.7, TE built with NVTE_WITH_CUTEDSL=1, " - "NVTE_ENABLE_CUTEDSL_BACKEND=1, NVTE_MOE_OVERLAP=1 and a cuDNN frontend whose " - "grouped kernels take int64 expert offsets (INT64_OFFSETS)" + "NVTE_ENABLE_CUTEDSL_BACKEND=1 and NVTE_MOE_OVERLAP=1" ) if config.payload_dtype is not torch.bfloat16: return "needs a BF16 payload" From ea6b7acee78fdffa61a07132b779adf22dcf3439 Mon Sep 17 00:00:00 2001 From: Phuong Nguyen Date: Thu, 3 Dec 2026 11:30:31 -0800 Subject: [PATCH 50/67] [PyTorch] Reject strided gradient and routing-weight tensors in the native EP overlap calls Signed-off-by: Phuong Nguyen --- tests/pytorch/distributed/run_ep.py | 57 +++++++++++++++++++ .../pytorch/csrc/extensions/ep.cpp | 3 + 2 files changed, 60 insertions(+) diff --git a/tests/pytorch/distributed/run_ep.py b/tests/pytorch/distributed/run_ep.py index 7f61f934277..df0f4c821c4 100644 --- a/tests/pytorch/distributed/run_ep.py +++ b/tests/pytorch/distributed/run_ep.py @@ -2400,6 +2400,63 @@ def _native_dispatch_gemm_fwd(self, alignment, offsets_dtype=torch.int64, ffn=25 alignment, ) + @_mxfp8_align_test + @_overlap_test + def test_moe_overlap_rejects_strided_outputs(self): + """The native overlapped calls reject strided tensors they read or write through a raw + pointer, for callers that bypass FusedMoE.""" + self._require_moe_overlap() + device = self.cfg.device + buffer = self._make_buffer_from_config(self._overlap_config()) + rows = buffer.recv_capacity_per_rank or 2 * OVERLAP_ALIGNMENT + ffn = 256 + bf16 = {"dtype": torch.bfloat16, "device": device} + offsets = torch.zeros(NUM_LOCAL_EXPERTS + 2, dtype=torch.int64, device=device)[1:] + + def strided(*shape, dtype): + return torch.zeros(*shape, 2, dtype=dtype, device=device)[..., 0] + + with self.assertRaisesRegex(RuntimeError, "recv_topk_weights must be a contiguous"): + tex.ep_combine_gemm_fwd( + buffer.handle_mem, + torch.zeros(rows, ffn, **bf16), + offsets, + torch.zeros(NUM_LOCAL_EXPERTS, HIDDEN_DIM, ffn, **bf16), + torch.zeros(rows, HIDDEN_DIM, **bf16), + torch.zeros(TOKENS_PER_RANK, HIDDEN_DIM, **bf16), + TOP_K, + OVERLAP_ALIGNMENT, + torch.int64, + strided(rows, dtype=torch.float32), + ) + for name, grad_tokens, grad_topk in ( + ( + "grad_tokens", + strided(TOKENS_PER_RANK, HIDDEN_DIM, dtype=torch.bfloat16), + torch.zeros(TOKENS_PER_RANK, TOP_K, dtype=torch.float32, device=device), + ), + ( + "grad_topk_weights", + torch.zeros(TOKENS_PER_RANK, HIDDEN_DIM, **bf16), + strided(TOKENS_PER_RANK, TOP_K, dtype=torch.float32), + ), + ): + with self.subTest(strided=name): + with self.assertRaisesRegex(RuntimeError, f"{name} must be a contiguous"): + tex.ep_dispatch_gemm_bwd( + buffer.handle_mem, + torch.zeros(rows, 2 * ffn, **bf16), + torch.zeros(rows, dtype=torch.float32, device=device), + offsets, + torch.zeros(NUM_LOCAL_EXPERTS, 2 * ffn, HIDDEN_DIM, **bf16), + torch.zeros(rows, HIDDEN_DIM, **bf16), + grad_tokens, + grad_topk, + TOP_K, + OVERLAP_ALIGNMENT, + torch.int64, + ) + @_mxfp8_align_test @_overlap_test def test_moe_overlap_rejects_other_alignment(self): diff --git a/transformer_engine/pytorch/csrc/extensions/ep.cpp b/transformer_engine/pytorch/csrc/extensions/ep.cpp index 529d9fe7d6b..de6edb8dfc4 100644 --- a/transformer_engine/pytorch/csrc/extensions/ep.cpp +++ b/transformer_engine/pytorch/csrc/extensions/ep.cpp @@ -1059,6 +1059,7 @@ void ep_combine_gemm_fwd(at::Tensor handle_mem, py::object gemm_in, at::Tensor e auto handle_mem_te = makeTransformerEngineTensor(handle_mem); TensorWrapper recv_topk_weights_te; if (recv_topk_weights.has_value()) { + check_dense_cuda(*recv_topk_weights, "recv_topk_weights"); recv_topk_weights_te = makeTransformerEngineTensor(*recv_topk_weights); } auto expert_token_offsets_te = makeTransformerEngineTensor(expert_token_offsets); @@ -1176,6 +1177,8 @@ void ep_dispatch_gemm_bwd(at::Tensor handle_mem, py::object grad_gemm_out, NVTE_CHECK(grad_recv_tokens.is_contiguous(), "grad_recv_tokens must be contiguous"); check_dense_cuda(expert_token_offsets, "expert_token_offsets"); check_dense_cuda(grad_recv_topk_weights, "grad_recv_topk_weights"); + check_dense_cuda(grad_tokens, "grad_tokens"); + check_dense_cuda(grad_topk_weights, "grad_topk_weights"); const bool mxfp8 = is_mxfp8_object(grad_gemm_out); NVTE_CHECK(is_mxfp8_object(weight) == mxfp8 && (!wgrad_input.has_value() || is_mxfp8_object(*wgrad_input) == mxfp8), From 109d46976da8c94033097de022cf08d864cd0884 Mon Sep 17 00:00:00 2001 From: Phuong Nguyen Date: Thu, 3 Dec 2026 11:30:31 -0800 Subject: [PATCH 51/67] [Common] Correct the EP overlap header, bench and env var docs on the stream rule, workspace alignment and SM support Signed-off-by: Phuong Nguyen --- docs/envvars.rst | 1 + examples/pytorch/ep/bench/bench_moe_overlap.py | 2 +- .../common/include/transformer_engine/ep_gemm.h | 7 ++++--- 3 files changed, 6 insertions(+), 4 deletions(-) diff --git a/docs/envvars.rst b/docs/envvars.rst index e6f9c61b57c..a61f4a9a9a4 100644 --- a/docs/envvars.rst +++ b/docs/envvars.rst @@ -173,6 +173,7 @@ General frontend package whose CuTeDSL grouped GEMMs take int64 expert offsets. If ``0``, the unfused ops run; if ``1``, a dispatch, grouped MLP and combine sequence that cannot run fused raises an error. + With it set, ``ep_bootstrap`` defaults ``max_num_sms`` to 24 unless ``zero_copy`` is on. With ``NVTE_ALLOW_NONDETERMINISTIC_ALGO=0`` or ``torch.use_deterministic_algorithms(True)``, the fused backward reduces the routing-weight gradient in a fixed order. This needs a per-token scratch of one diff --git a/examples/pytorch/ep/bench/bench_moe_overlap.py b/examples/pytorch/ep/bench/bench_moe_overlap.py index 580799f4f9c..e2f7b381e3c 100644 --- a/examples/pytorch/ep/bench/bench_moe_overlap.py +++ b/examples/pytorch/ep/bench/bench_moe_overlap.py @@ -8,7 +8,7 @@ torchrun --standalone --nproc-per-node=4 bench_moe_overlap.py --precision bf16 The op fuses an MoE MLP (dispatch, GroupedLinear, ScaledSwiGLU, GroupedLinear, combine) so the -NCCL EP dispatch and combine overlap the expert GEMMs. Requires SM 10.0 or 10.3, an EP group +NCCL EP dispatch and combine overlap the expert GEMMs. Requires SM 10.0, 10.3 or 10.7, an EP group within one NVLink domain, NVTE_ENABLE_CUTEDSL_BACKEND=1 and NVTE_MOE_OVERLAP=1. The defaults match the DeepSeek-V3 EP4 shape. """ diff --git a/transformer_engine/common/include/transformer_engine/ep_gemm.h b/transformer_engine/common/include/transformer_engine/ep_gemm.h index c02aadc2fcd..34161b7a80e 100644 --- a/transformer_engine/common/include/transformer_engine/ep_gemm.h +++ b/transformer_engine/common/include/transformer_engine/ep_gemm.h @@ -34,13 +34,14 @@ * - recv_tokens_per_expert, expert_token_offsets and total_recv_tokens are int64. * - MXFP8: hidden_dim a multiple of 512, ffn_dim a multiple of 256. * - First call per shape compiles its GEMM: run it at warmup, outside CUDA graph capture. - * - A group's calls on one stream, same order on every rank. A call throws otherwise. + * - A group's calls on one stream, same order on every rank. This is not checked: a call on + * another stream, or in another order on some rank, can corrupt data or hang. * - A PDL kernel launched after nvte_ep_dispatch_gemm_bwd must wait before it reads the call's * outputs. * * SM budgets: NVTEEpGroupConfig *_num_sms fields (ep.h), set at nvte_ep_initialize, not layer_cfg. - * Workspace: caller-owned uint8 of the size nvte_ep_overlap_workspace_size returns. Each call resets it - * before use, so one buffer can be reused across the group's calls. + * Workspace: caller-owned uint8 of the size nvte_ep_overlap_workspace_size returns, 128-byte + * aligned. Each call resets it before use, so one buffer can be reused across the group's calls. */ #ifndef TRANSFORMER_ENGINE_EP_GEMM_H_ From 970f41fed9dd95804da78ad07d08e8d377bab372 Mon Sep 17 00:00:00 2001 From: Phuong Nguyen Date: Thu, 3 Dec 2026 12:04:37 -0800 Subject: [PATCH 52/67] [Common] Reject dispatch flags for an MXFP8 EP weight gradient configuration Signed-off-by: Phuong Nguyen --- tests/pytorch/test_ep_gemm.py | 14 ++++++++++++++ .../common/CuTeDSL/ep_gemm/wgrad_gemm.py | 7 +++++++ 2 files changed, 21 insertions(+) diff --git a/tests/pytorch/test_ep_gemm.py b/tests/pytorch/test_ep_gemm.py index f43f1a9101a..71a0e901179 100644 --- a/tests/pytorch/test_ep_gemm.py +++ b/tests/pytorch/test_ep_gemm.py @@ -353,6 +353,20 @@ def _dispatch_gemm_fwd_args(tokens_shape=(8, 1024)): ) +def test_mxfp8_wgrad_rejects_dispatch_flags(): + """An MXFP8 weight gradient waits on the GEMM before it, not on the dispatch flags.""" + with pytest.raises(ValueError, match="takes no dispatch flags"): + wgrad_gemm.WgradConfig( + rows=2 * TILE, + m=256, + n=256, + num_experts=2, + num_clusters=1, + scaling_mode=wgrad_gemm.MXFP8_1D_SCALING, + signal_unit_tokens=TILE, + ) + + def test_dispatch_gemm_fwd_rejects_flat_tokens(): """Tokens that are not [num_tokens, hidden] raise an error before any GEMM work.""" with pytest.raises(RuntimeError, match="tokens must be"): diff --git a/transformer_engine/common/CuTeDSL/ep_gemm/wgrad_gemm.py b/transformer_engine/common/CuTeDSL/ep_gemm/wgrad_gemm.py index bfae7f7c24f..479cc85cecd 100644 --- a/transformer_engine/common/CuTeDSL/ep_gemm/wgrad_gemm.py +++ b/transformer_engine/common/CuTeDSL/ep_gemm/wgrad_gemm.py @@ -56,6 +56,13 @@ class WgradConfig: # Kernels, workspace layouts and compiled functions are specific to the device architecture. capability: tuple = field(default_factory=device_compute_capability) + def __post_init__(self): + if self.mxfp8 and self.signal_unit_tokens: + raise ValueError( + "An MXFP8 weight gradient takes no dispatch flags: it reads operands that the GEMM" + " before it writes." + ) + @property def mxfp8(self) -> bool: """Whether the operands are MXFP8 rather than BF16.""" From 02bc11c69e04dfb776efb47a9094d669e9f068ca Mon Sep 17 00:00:00 2001 From: Phuong Nguyen Date: Thu, 3 Dec 2026 12:04:37 -0800 Subject: [PATCH 53/67] [Common] Merge the duplicate MXFP8 backward kernel branches and share the dprob view in the EP dispatch GEMM Signed-off-by: Phuong Nguyen --- .../common/CuTeDSL/ep_gemm/dispatch_gemm.py | 27 ++++++------------- 1 file changed, 8 insertions(+), 19 deletions(-) diff --git a/transformer_engine/common/CuTeDSL/ep_gemm/dispatch_gemm.py b/transformer_engine/common/CuTeDSL/ep_gemm/dispatch_gemm.py index a6180abe614..b72f912e7f0 100644 --- a/transformer_engine/common/CuTeDSL/ep_gemm/dispatch_gemm.py +++ b/transformer_engine/common/CuTeDSL/ep_gemm/dispatch_gemm.py @@ -136,16 +136,6 @@ def build_kernel(cfg: DispatchGemmConfig): "compact_sfa_sf_warp": True, "use_pdl": True, } - if cfg.backward and rubin: - # 128-deep K tiles of one scale atom each: the TMA warp queues the compact scales ahead. - # TODO(phuonguyen): fp8_k_tile / compact_sfa_queue are computed internally by cuDNN FE. - return _backward_kernel_class(True)( - discrete_col_sfd=True, - act_func=backward_activation, - launch_pdl_dependents_at_entry=True, - **deterministic, - **common, - ) if cfg.backward: return _backward_kernel_class(True)( discrete_col_sfd=True, @@ -230,6 +220,11 @@ def _prologue(cfg: DispatchGemmConfig): return kernel, dims, tail +def _dprob_view(cfg: DispatchGemmConfig, dprob, rows, n_slots): + """The routing-weight gradient output: ``n_slots`` per row when deterministic, else one.""" + return slots_view(dprob, rows, n_slots) if cfg.deterministic else prob_view(dprob, rows) + + def _compile_forward(cfg: DispatchGemmConfig): """FC1: SwiGLU GEMM with the weight [experts, n, k], writing ``c`` and ``d``.""" kernel, (rows, k, n, experts, num_clusters), tail = _prologue(cfg) @@ -264,9 +259,7 @@ def _compile_backward(cfg: DispatchGemmConfig): @cute.jit def launch(a, b, c, d, dprob, expert_row_ends, alpha, prob, workspace, stream): weight = weight_view(b, n, k, experts, n_major=True) - dprob_out = ( - slots_view(dprob, rows, n_slots) if cfg.deterministic else prob_view(dprob, rows) - ) + dprob_out = _dprob_view(cfg, dprob, rows, n_slots) kernel( rows_view(a, rows, k), weight, cutlass.Int32(0), cutlass.Int32(0), cutlass.Int64(0), OperandMajorMode.K, workspace.iterator, rows_view(c, rows, 2 * n), @@ -353,9 +346,7 @@ def launch( prob, norm_const, workspace, stream, ): # fmt: skip weight = weight_view(b, n, k, experts, n_major=True) - dprob_out = ( - slots_view(dprob, rows, n_slots) if cfg.deterministic else prob_view(dprob, rows) - ) + dprob_out = _dprob_view(cfg, dprob, rows, n_slots) kernel( rows_view(a, rows, k), weight, sfb, cutlass.Int32(0), cutlass.Int32(0), cutlass.Int64(0), OperandMajorMode.K, workspace.iterator, rows_view(c, rows, 2 * n), @@ -372,9 +363,7 @@ def launch_rubin( ): # fmt: skip # pylint: disable=unused-argument # The SM 10.7 kernel takes the SwiGLU linear offset ahead of dbias and has no h output. weight = weight_view(b, n, k, experts, n_major=True) - dprob_out = ( - slots_view(dprob, rows, n_slots) if cfg.deterministic else prob_view(dprob, rows) - ) + dprob_out = _dprob_view(cfg, dprob, rows, n_slots) kernel( rows_view(a, rows, k), weight, sfb, cutlass.Int32(0), cutlass.Int32(0), cutlass.Int64(0), OperandMajorMode.K, workspace.iterator, rows_view(c, rows, 2 * n), From 3905403033963e004281558ecbab9ffba2438326 Mon Sep 17 00:00:00 2001 From: Phuong Nguyen Date: Thu, 3 Dec 2026 13:14:19 -0800 Subject: [PATCH 54/67] [PyTorch] Set main_grad on the weights in the EP overlap inference test Signed-off-by: Phuong Nguyen --- tests/pytorch/distributed/run_ep.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tests/pytorch/distributed/run_ep.py b/tests/pytorch/distributed/run_ep.py index df0f4c821c4..0fdb6047efb 100644 --- a/tests/pytorch/distributed/run_ep.py +++ b/tests/pytorch/distributed/run_ep.py @@ -2298,6 +2298,8 @@ def test_moe_overlap_inference(self): config = self._overlap_config(recipe) buffer = self._make_buffer_from_config(config) ops = self._moe_ops(config, buffer, accumulate_into_main_grad=True) + for p in (ops[1].weight, ops[3].weight): + p.main_grad = torch.zeros(p.size(), dtype=torch.float32, device=self.cfg.device) results = [] for fused in (False, True): # Each run publishes its own counts: a stale value would show. From 766412a6aa90bb5fb53e460cbcf0a0f0d2427a65 Mon Sep 17 00:00:00 2001 From: Phuong Nguyen Date: Thu, 3 Dec 2026 13:21:46 -0800 Subject: [PATCH 55/67] [Common] Pass the streaming output notify and dependents-at-entry options to the SM 10.7 MXFP8 combine GEMM Signed-off-by: Phuong Nguyen --- transformer_engine/common/CuTeDSL/ep_gemm/combine_gemm.py | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/transformer_engine/common/CuTeDSL/ep_gemm/combine_gemm.py b/transformer_engine/common/CuTeDSL/ep_gemm/combine_gemm.py index 4751156caff..633b33265c8 100644 --- a/transformer_engine/common/CuTeDSL/ep_gemm/combine_gemm.py +++ b/transformer_engine/common/CuTeDSL/ep_gemm/combine_gemm.py @@ -83,18 +83,14 @@ def build_kernel(cfg: CombineGemmConfig): clusters_beside_consumer=cfg.num_clusters, ) if cfg.mxfp8 and is_sm107(): - if notify is not None or cfg.dependents_at_entry: - raise NotImplementedError( - "The SM 10.7 MXFP8 grouped GEMM (cuDNN FE moe_blockscaled_grouped_gemm_quant_rubin)" - " has no streaming_output_notify or launch_pdl_dependents_at_entry option, which" - " the overlapped MXFP8 combine needs." - ) module = import_gemm_modules("moe_blockscaled_grouped_gemm_quant_rubin")[0] return module.BlockScaledMoEGroupedGemmQuantKernel( generate_sfd=False, discrete_col_sfd=False, generate_c=False, enable_bias=False, + streaming_output_notify=notify, + launch_pdl_dependents_at_entry=cfg.dependents_at_entry, **blockscaled_kwargs(cfg.num_experts), ) if cfg.mxfp8: From 7a59c7a733cd6527796c1e0d1f005f3801fc6e60 Mon Sep 17 00:00:00 2001 From: Phuong Nguyen Date: Thu, 3 Dec 2026 14:33:38 -0800 Subject: [PATCH 56/67] [Common] Skip the columnwise D and SFD in the SM 10.7 MXFP8 dispatch GEMM Signed-off-by: Phuong Nguyen --- .../common/CuTeDSL/ep_gemm/dispatch_gemm.py | 16 +--------------- 1 file changed, 1 insertion(+), 15 deletions(-) diff --git a/transformer_engine/common/CuTeDSL/ep_gemm/dispatch_gemm.py b/transformer_engine/common/CuTeDSL/ep_gemm/dispatch_gemm.py index b72f912e7f0..ae0468c7408 100644 --- a/transformer_engine/common/CuTeDSL/ep_gemm/dispatch_gemm.py +++ b/transformer_engine/common/CuTeDSL/ep_gemm/dispatch_gemm.py @@ -293,23 +293,9 @@ def launch(a, b, sfb, sfa, c, d, sfd, expert_row_ends, alpha, norm_const, worksp alpha, None, None, num_clusters, stream, ) # fmt: skip - @cute.jit - def launch_rubin( - a, b, sfb, sfa, c, d, sfd, expert_row_ends, alpha, norm_const, workspace, stream - ): - # The SM 10.7 kernel takes c ahead of d and no row scale. - weight = weight_view(b, n, k, experts, n_major=False) - d3 = rows_view(d, rows, d_cols) - kernel( - rows_view(a, rows, k), weight, sfb, cutlass.Int32(0), cutlass.Int32(0), - cutlass.Int64(0), OperandMajorMode.K, workspace.iterator, rows_view(c, rows, n), d3, - d3, sfa, sfd, None, None, norm_const, expert_row_ends, alpha, None, None, num_clusters, - stream, - ) # fmt: skip - row_ends, alpha, _, workspace = tail return compile_launch( - launch_rubin if is_sm107() else launch, + launch, fp8_fake((rows, k), (1, 0)), fp8_fake((experts, n, k), (2, 1, 0)), scale_fake(experts * n, k), From 8735d38be156e71ec702ba707f365bd009c24224 Mon Sep 17 00:00:00 2001 From: Phuong Nguyen Date: Thu, 3 Dec 2026 16:12:00 -0800 Subject: [PATCH 57/67] [PyTorch] Keep int32 expert offsets in the fused grouped MLP and pass int64 only on the MoE overlap path Signed-off-by: Phuong Nguyen --- .../pytorch/ops/fused/grouped_mlp.py | 21 ++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/transformer_engine/pytorch/ops/fused/grouped_mlp.py b/transformer_engine/pytorch/ops/fused/grouped_mlp.py index 94f7d587938..7eb7605f76e 100644 --- a/transformer_engine/pytorch/ops/fused/grouped_mlp.py +++ b/transformer_engine/pytorch/ops/fused/grouped_mlp.py @@ -937,6 +937,8 @@ def _compute_grad_params( accumulate=accumulate_into_main_grad, ) elif cudnn_wgrad_kernel_fn is not None: + # The MoE overlap path passes int64 offsets; the fused grouped MLP passes int32. + # TODO: move the fused grouped MLP to int64 offsets as well. gemm_fn = functools.partial( _cudnn_compute_wgrad, weight_shape=weight_shape, @@ -1387,10 +1389,11 @@ def fuser_forward( # Prepare split metadata if use_offsetless_metadata: - # The use_single_group_runtime_offsets specialization never loads - # the pointer. This aliases the live caller-owned [M] int64 tensor, + # cuDNN requires an int32 tensor descriptor, although its + # use_single_group_runtime_offsets specialization never loads the + # pointer. This view aliases the live caller-owned [M] int64 tensor, # has value M, and requires no allocation or CUDA kernel. - split_points = split_sizes[:1] + split_points = split_sizes.view(torch.int32)[:1] # Backward saves this slot for the generic path. The optimized # shared-expert path never consumes it. base_split_offsets = split_sizes @@ -1422,7 +1425,7 @@ def fuser_forward( ], include_leading_zero=[False, True, True, True, True, True], dtypes=[ - torch.int64, + torch.int32, torch.int64, torch.int64, torch.int64, @@ -3818,7 +3821,7 @@ def fuser_forward( fc1_weight_requires_grad = requires_grad and fc1_weight_param.requires_grad fc2_weight_requires_grad = requires_grad and fc2_weight_param.requires_grad - # cuDNN padded offsets and dbias offsets (int64, leading zero). + # cuDNN padded offsets (int32) and dbias offsets (int64, leading zero). fc1_split_sizes = basic_op_extra_inputs[0][0] fc2_split_sizes = basic_op_extra_inputs[2][0] if ( @@ -3836,7 +3839,7 @@ def fuser_forward( device, strides=[1, 1], include_leading_zero=[False, True], - dtypes=[torch.int64, torch.int64], + dtypes=[torch.int32, torch.int64], bulk_allocate=True, split_alignment=_BF16_M_ALIGNMENT, ) @@ -4102,7 +4105,11 @@ def fuser_backward( fc1_bias_grads = [fc1_dbias[idx] for idx in range(num_groups)] wgrad_kernel_fn = self.grouped_gemm_wgrad_kernel() - wgrad_offsets = split_points + wgrad_offsets = ( + split_points + if split_points.dtype == torch.int32 + else split_points.to(dtype=torch.int32) + ) # FC2 wgrad. fc2_grad_params = _compute_grad_params( From 92682b457b89564f61ee989b677be174e24bd7c2 Mon Sep 17 00:00:00 2001 From: Phuong Nguyen Date: Thu, 3 Dec 2026 17:24:52 -0800 Subject: [PATCH 58/67] [PyTorch] Run the FusedMoE reverse dispatch on every rank so a rank without input gradients cannot stall its peers Signed-off-by: Phuong Nguyen --- tests/pytorch/distributed/run_ep.py | 41 ++++++++++-- .../pytorch/ops/fused/moe_overlap.py | 67 ++++++++++--------- 2 files changed, 71 insertions(+), 37 deletions(-) diff --git a/tests/pytorch/distributed/run_ep.py b/tests/pytorch/distributed/run_ep.py index 0fdb6047efb..71ab8e407b3 100644 --- a/tests/pytorch/distributed/run_ep.py +++ b/tests/pytorch/distributed/run_ep.py @@ -1975,12 +1975,8 @@ def run(fused): ctx.enter_context(self._moe_fusion(False)) elif not fused: ctx = self._moe_fusion(False) - elif input_grad: - ctx = contextlib.nullcontext() else: - ctx = mock.patch.object( - moe_overlap.tex, "ep_dispatch_gemm_bwd", side_effect=AssertionError("called") - ) + ctx = contextlib.nullcontext() # Each run publishes its own counts: a stale value would show. buffer.tokens_per_expert.fill_(-1) buffer.total_recv_tokens.fill_(-1) @@ -2363,6 +2359,41 @@ def test_moe_overlap_rank_without_tokens(self): if has_tokens: self.assertGreater(int(per_expert[0].count_nonzero()), 0) + @_eager_test_include + @_mxfp8_align_test + @_overlap_test + def test_moe_overlap_rank_without_input_grad(self): + """Rank 0 needs neither the token nor the routing weight gradient, its peers do. Every + rank joins the reverse dispatch, and the peers' gradients match a run where all ranks + need them.""" + self._require_moe_overlap() + if self.cfg.ep_size < 2: + self.skipTest("needs a peer rank") + config = self._overlap_config() + ops = self._moe_ops(config, self._make_buffer_from_config(config)) + tokens, topk_idx, w, grad = self._moe_calls(1)[0] + detached = self.cfg.rank == 0 + with self._moe_fusion(True): + model = te_ops.Sequential(*ops) + _, ref_tokens_grad, ref_weights_grad = self._moe_call(model, tokens, topk_idx, w, grad) + _, tokens_grad, weights_grad = self._moe_call( + model, + tokens, + topk_idx, + w, + grad, + tokens_grad=not detached, + weights_grad=not detached, + ) + torch.cuda.synchronize() + self._assert_fusion(model, True) + if detached: + self.assertIsNone(tokens_grad) + self.assertIsNone(weights_grad) + else: + torch.testing.assert_close(tokens_grad, ref_tokens_grad) + torch.testing.assert_close(weights_grad, ref_weights_grad) + @_eager_test_include @_overflow_test_include @_mxfp8_align_test diff --git a/transformer_engine/pytorch/ops/fused/moe_overlap.py b/transformer_engine/pytorch/ops/fused/moe_overlap.py index 4bc30696765..ad4e2a3f87c 100644 --- a/transformer_engine/pytorch/ops/fused/moe_overlap.py +++ b/transformer_engine/pytorch/ops/fused/moe_overlap.py @@ -354,22 +354,23 @@ def fuser_backward( # pylint: disable=unused-argument if fc2_grads is None: fc2_grads = grad_params(fc2_op, fc2_ctx, act_out, grad_expert_out, "FC2") - # Neither the input nor the routing weights need a gradient: no dispatch backward. - grad_tokens = grad_topk = fc1_grads = None - if dispatch_ctx.requires_grad: - if grad_recv_weights_extra is not None: - grad_recv_weights.add_(grad_recv_weights_extra.to(torch.float32)) - fc1_wgrad = _CallWgrad() - if fc1_ctx.weight_requires_grad: - fc1_grads = grad_params(fc1_op, fc1_ctx, recv_tokens, None, "FC1", fc1_wgrad) - grad_recv = torch.empty(rows, hidden, dtype=torch.bfloat16, device=device) - grad_tokens = torch.empty(num_tokens, hidden, dtype=torch.bfloat16, device=device) - grad_topk = torch.empty(fc1_ctx.topk_weights_shape, dtype=torch.float32, device=device) - tex.ep_dispatch_gemm_bwd( - buffer.handle_mem, grad_gemm, grad_recv_weights, expert_token_offsets, w1, - grad_recv, grad_tokens, grad_topk, buffer.top_k, buffer.alignment, - buffer.topk_idx_dtype, **fc1_wgrad, - ) # fmt: skip + # The reverse dispatch is a collective: every rank runs it, as a peer may need its gradient. + fc1_grads = None + if grad_recv_weights_extra is not None: + grad_recv_weights.add_(grad_recv_weights_extra.to(torch.float32)) + fc1_wgrad = _CallWgrad() + if fc1_ctx.weight_requires_grad: + fc1_grads = grad_params(fc1_op, fc1_ctx, recv_tokens, None, "FC1", fc1_wgrad) + grad_recv = torch.empty(rows, hidden, dtype=torch.bfloat16, device=device) + grad_tokens = torch.empty(num_tokens, hidden, dtype=torch.bfloat16, device=device) + grad_topk = torch.empty(fc1_ctx.topk_weights_shape, dtype=torch.float32, device=device) + tex.ep_dispatch_gemm_bwd( + buffer.handle_mem, grad_gemm, grad_recv_weights, expert_token_offsets, w1, + grad_recv, grad_tokens, grad_topk, buffer.top_k, buffer.alignment, + buffer.topk_idx_dtype, **fc1_wgrad, + ) # fmt: skip + if not dispatch_ctx.requires_grad: + grad_tokens = grad_topk = None if fc1_grads is None: fc1_grads = grad_params(fc1_op, fc1_ctx, recv_tokens, grad_gemm, "FC1") @@ -518,22 +519,24 @@ def fc1_grad_params(wgrad_args=None): deterministic=_deterministic_algorithms_required(), **fc2_wgrad, ) # fmt: skip - grad_tokens = grad_topk = fc1_grads = None - if dispatch_ctx.requires_grad: - if grad_recv_weights_extra is not None: - grad_recv_weights.add_(grad_recv_weights_extra.to(torch.float32)) - fc1_wgrad = _CallWgrad() - if fc1_ctx.weight_requires_grad: - fc1_grads = fc1_grad_params(fc1_wgrad) - grad_recv = torch.empty(rows, hidden, dtype=torch.bfloat16, device=device) - grad_tokens = torch.empty(num_tokens, hidden, dtype=torch.bfloat16, device=device) - grad_topk = torch.empty(fc1_ctx.topk_weights_shape, dtype=torch.float32, device=device) - # The columnwise grad_gemm_out is read only by the in-call weight gradient. - tex.ep_dispatch_gemm_bwd( - buffer.handle_mem, grad_gemm if fc1_wgrad else _rowwise_only(grad_gemm), - grad_recv_weights, expert_token_offsets, w1, grad_recv, grad_tokens, grad_topk, - buffer.top_k, buffer.alignment, buffer.topk_idx_dtype, **fc1_wgrad, - ) # fmt: skip + # The reverse dispatch is a collective: every rank runs it, as a peer may need its gradient. + fc1_grads = None + if grad_recv_weights_extra is not None: + grad_recv_weights.add_(grad_recv_weights_extra.to(torch.float32)) + fc1_wgrad = _CallWgrad() + if fc1_ctx.weight_requires_grad: + fc1_grads = fc1_grad_params(fc1_wgrad) + grad_recv = torch.empty(rows, hidden, dtype=torch.bfloat16, device=device) + grad_tokens = torch.empty(num_tokens, hidden, dtype=torch.bfloat16, device=device) + grad_topk = torch.empty(fc1_ctx.topk_weights_shape, dtype=torch.float32, device=device) + # The columnwise grad_gemm_out is read only by the in-call weight gradient. + tex.ep_dispatch_gemm_bwd( + buffer.handle_mem, grad_gemm if fc1_wgrad else _rowwise_only(grad_gemm), + grad_recv_weights, expert_token_offsets, w1, grad_recv, grad_tokens, grad_topk, + buffer.top_k, buffer.alignment, buffer.topk_idx_dtype, **fc1_wgrad, + ) # fmt: skip + if not dispatch_ctx.requires_grad: + grad_tokens = grad_topk = None if fc1_grads is None: fc1_grads = fc1_grad_params() From c2effe95c2b2ffafce66d742a8663540a936be83 Mon Sep 17 00:00:00 2001 From: Phuong Nguyen Date: Thu, 3 Dec 2026 17:24:52 -0800 Subject: [PATCH 59/67] [PyTorch] Use combine chunk sizes that are multiples of the NCCL EP push tile in the EP overlap launcher Signed-off-by: Phuong Nguyen --- tests/pytorch/distributed/run_test_ep.sh | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/tests/pytorch/distributed/run_test_ep.sh b/tests/pytorch/distributed/run_test_ep.sh index 276044f8333..f8a7eedb072 100755 --- a/tests/pytorch/distributed/run_test_ep.sh +++ b/tests/pytorch/distributed/run_test_ep.sh @@ -180,12 +180,14 @@ else # Per-direction SM counts (dispatch fwd, combine fwd, dispatch bwd, combine bwd). The backward # split skips when Transformer Engine was built against an NCCL EP without backward SM budgets. # NVTE_EP_OVERLAP_CONFIG: combine_chunk_hidden,push_last_chunk_sms,reduce_last_chunk_sms, - # dispatch_chunk_tokens. Flags per 256 combine columns without splitting the last chunk here, - # three combine chunks per row with split last chunks in the hidden 1536 pass below. - NVTE_EP_OVERLAP_CONFIG=256,0,0,0 NVTE_EP_COMM_SMS=12,20,0,0 run_pass "overlap_split" 0 0 0 1 0 1 + # dispatch_chunk_tokens. The combine chunk is a multiple of the NCCL EP push tile (1024 columns + # for hidden sizes of 1024 and above). Two combine chunks per row without splitting the last + # chunk here, a full and a shorter last chunk with split last chunks in the hidden 1536 pass. + NVTE_EP_OVERLAP_CONFIG=1024,0,0,0 NVTE_EP_HIDDEN_DIM=2048 NVTE_EP_COMM_SMS=12,20,0,0 \ + run_pass "overlap_split" 0 0 0 1 0 1 NVTE_EP_COMM_SMS=12,20,24,16 run_pass "overlap_split_bwd" 0 0 0 1 0 1 # A hidden size that 1024 does not divide: the combine waits on whole rows. - NVTE_EP_OVERLAP_CONFIG=512,16,8,0 NVTE_EP_HIDDEN_DIM=1536 run_pass "overlap_h1536" 0 0 0 1 0 1 + NVTE_EP_OVERLAP_CONFIG=1024,16,8,0 NVTE_EP_HIDDEN_DIM=1536 run_pass "overlap_h1536" 0 0 0 1 0 1 # A dispatch chunk other than the alignment is rejected; only that test runs and it runs no # fused op. NVTE_EP_OVERLAP_CONFIG=0,0,0,128 NVTE_EP_TEST_FILTER=test_moe_overlap_rejects_dispatch_chunk \ From 1092c3efd28d8e1f11df810d8ee8484f309e3f2b Mon Sep 17 00:00:00 2001 From: Phuong Nguyen Date: Thu, 3 Dec 2026 17:32:16 -0800 Subject: [PATCH 60/67] [PyTorch] Restore the sub-tile combine chunk cases in the EP overlap launcher Signed-off-by: Phuong Nguyen --- tests/pytorch/distributed/run_test_ep.sh | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/tests/pytorch/distributed/run_test_ep.sh b/tests/pytorch/distributed/run_test_ep.sh index f8a7eedb072..276044f8333 100755 --- a/tests/pytorch/distributed/run_test_ep.sh +++ b/tests/pytorch/distributed/run_test_ep.sh @@ -180,14 +180,12 @@ else # Per-direction SM counts (dispatch fwd, combine fwd, dispatch bwd, combine bwd). The backward # split skips when Transformer Engine was built against an NCCL EP without backward SM budgets. # NVTE_EP_OVERLAP_CONFIG: combine_chunk_hidden,push_last_chunk_sms,reduce_last_chunk_sms, - # dispatch_chunk_tokens. The combine chunk is a multiple of the NCCL EP push tile (1024 columns - # for hidden sizes of 1024 and above). Two combine chunks per row without splitting the last - # chunk here, a full and a shorter last chunk with split last chunks in the hidden 1536 pass. - NVTE_EP_OVERLAP_CONFIG=1024,0,0,0 NVTE_EP_HIDDEN_DIM=2048 NVTE_EP_COMM_SMS=12,20,0,0 \ - run_pass "overlap_split" 0 0 0 1 0 1 + # dispatch_chunk_tokens. Flags per 256 combine columns without splitting the last chunk here, + # three combine chunks per row with split last chunks in the hidden 1536 pass below. + NVTE_EP_OVERLAP_CONFIG=256,0,0,0 NVTE_EP_COMM_SMS=12,20,0,0 run_pass "overlap_split" 0 0 0 1 0 1 NVTE_EP_COMM_SMS=12,20,24,16 run_pass "overlap_split_bwd" 0 0 0 1 0 1 # A hidden size that 1024 does not divide: the combine waits on whole rows. - NVTE_EP_OVERLAP_CONFIG=1024,16,8,0 NVTE_EP_HIDDEN_DIM=1536 run_pass "overlap_h1536" 0 0 0 1 0 1 + NVTE_EP_OVERLAP_CONFIG=512,16,8,0 NVTE_EP_HIDDEN_DIM=1536 run_pass "overlap_h1536" 0 0 0 1 0 1 # A dispatch chunk other than the alignment is rejected; only that test runs and it runs no # fused op. NVTE_EP_OVERLAP_CONFIG=0,0,0,128 NVTE_EP_TEST_FILTER=test_moe_overlap_rejects_dispatch_chunk \ From efa31a72ffefdfd43be21313fe540ac7bbed6297 Mon Sep 17 00:00:00 2001 From: Phuong Nguyen Date: Thu, 3 Dec 2026 17:59:18 -0800 Subject: [PATCH 61/67] [PyTorch] Tighten the EP overlap tests and fold the NCCL EP discovery tests into test_ep_gemm.py Signed-off-by: Phuong Nguyen --- qa/L0_pytorch_unittest/test.sh | 3 +- tests/pytorch/distributed/run_ep.py | 899 +++++------------------ tests/pytorch/distributed/run_test_ep.sh | 14 +- tests/pytorch/test_ep_gemm.py | 307 ++++++-- tests/pytorch/test_nccl_ep_discovery.py | 204 ----- 5 files changed, 420 insertions(+), 1007 deletions(-) delete mode 100644 tests/pytorch/test_nccl_ep_discovery.py diff --git a/qa/L0_pytorch_unittest/test.sh b/qa/L0_pytorch_unittest/test.sh index 31ee33dea27..f46eb78441c 100644 --- a/qa/L0_pytorch_unittest/test.sh +++ b/qa/L0_pytorch_unittest/test.sh @@ -103,8 +103,7 @@ PYTORCH_JIT=0 NVTE_TORCH_COMPILE=0 python3 -m pytest --tb=auto --junitxml=$XML_L PYTORCH_JIT=0 NVTE_TORCH_COMPILE=0 python3 -m pytest --tb=auto --junitxml=$XML_LOG_DIR/pytest_test_ops_grouped_linear_distributed_weight.xml $TE_PATH/tests/pytorch/test_ops_grouped_linear_distributed_weight.py || test_fail "test_ops_grouped_linear_distributed_weight.py" PYTORCH_JIT=0 NVTE_TORCH_COMPILE=0 python3 -m pytest --tb=auto --junitxml=$XML_LOG_DIR/pytest_test_module_grouped_linear_distributed_weight.xml $TE_PATH/tests/pytorch/test_module_grouped_linear_distributed_weight.py || test_fail "test_module_grouped_linear_distributed_weight.py" python3 -m pytest --tb=auto --junitxml=$XML_LOG_DIR/pytest_test_grouped_mlp.xml $TE_PATH/tests/pytorch/test_grouped_mlp.py || test_fail "test_grouped_mlp.py" -python3 -m pytest --tb=auto --junitxml=$XML_LOG_DIR/pytest_test_nccl_ep_discovery.xml $TE_PATH/tests/pytorch/test_nccl_ep_discovery.py || test_fail "test_nccl_ep_discovery.py" -# The EP overlap kernel tests skip the whole module unless NVTE_MOE_OVERLAP=1. +# The EP overlap kernel tests skip unless NVTE_MOE_OVERLAP=1; the CPU-only checks always run. # TODO(phuonguyen): set NVTE_ENABLE_CUTEDSL_BACKEND=1 NVTE_MOE_OVERLAP=1 once TE builds CuTeDSL by default. python3 -m pytest --tb=auto --junitxml=$XML_LOG_DIR/pytest_test_ep_gemm.xml $TE_PATH/tests/pytorch/test_ep_gemm.py || test_fail "test_ep_gemm.py" diff --git a/tests/pytorch/distributed/run_ep.py b/tests/pytorch/distributed/run_ep.py index 71ab8e407b3..b9e412bc930 100644 --- a/tests/pytorch/distributed/run_ep.py +++ b/tests/pytorch/distributed/run_ep.py @@ -3,14 +3,11 @@ # See LICENSE for license information. """Multi-process PyTorch EP tests, launched via torchrun (one process per GPU).""" -from dataclasses import replace -import contextlib -import ctypes from contextlib import nullcontext +from dataclasses import replace import itertools import os import sys -import threading import unittest from unittest import mock @@ -61,9 +58,9 @@ import transformer_engine_torch as tex # noqa: F401 # SM 10.7 has no BF16 grouped MLP fusion, so there the BF16 unfused ops never fuse into it. -_SM107 = (10, 7) -UNFUSED_BF16_MLP_REFERENCE = torch.cuda.is_available() and ( - torch.cuda.get_device_capability() == _SM107 +UNFUSED_BF16_MLP_REFERENCE = torch.cuda.is_available() and torch.cuda.get_device_capability() == ( + 10, + 7, ) NUM_LOCAL_EXPERTS = 2 @@ -81,18 +78,10 @@ raise ValueError(f"NVTE_EP_COMM_SMS needs 4 comma-separated counts, got {COMM_SMS}") # Overlap tuning of the group (NVTE_EP_OVERLAP_CONFIG=combine_chunk_hidden,push_last_chunk_sms, # reduce_last_chunk_sms,dispatch_chunk_tokens); unset keeps the ep_bootstrap defaults. -_OVERLAP_CONFIG_ENV = os.environ.get("NVTE_EP_OVERLAP_CONFIG") OVERLAP_CONFIG = None -if _OVERLAP_CONFIG_ENV: - _chunk_hidden, _push_sms, _reduce_sms, _dispatch_chunk = ( - int(value) for value in _OVERLAP_CONFIG_ENV.split(",") - ) - OVERLAP_CONFIG = EpOverlapConfig( - dispatch_chunk_tokens=_dispatch_chunk, - combine_chunk_hidden=_chunk_hidden, - combine_push_last_chunk_sms=_push_sms, - combine_reduce_last_chunk_sms=_reduce_sms, - ) +if os.environ.get("NVTE_EP_OVERLAP_CONFIG"): + _hidden, _push, _reduce, _dispatch = map(int, os.environ["NVTE_EP_OVERLAP_CONFIG"].split(",")) + OVERLAP_CONFIG = EpOverlapConfig(_dispatch, _hidden, _push, _reduce) def _zero_copy_test_include(fn): @@ -131,9 +120,10 @@ def _overlap_test(fn): return fn -def _mxfp8_overlap() -> bool: - """Whether the overlap tests run their MXFP8 cases: shapes FusedMoE takes.""" - return HIDDEN_DIM % 512 == 0 and TOKENS_PER_RANK % 32 == 0 +def _overlap_recipes(): + """Recipes of the overlap tests: BF16, and MXFP8 where the shapes allow FusedMoE to take it.""" + mxfp8 = HIDDEN_DIM % 512 == 0 and TOKENS_PER_RANK % 32 == 0 + return [None] + ([MXFP8BlockScaling()] if mxfp8 else []) class _StageToSymm(torch.autograd.Function): @@ -1340,30 +1330,6 @@ def _run_dispatch_combine_identity(self, *, mxfp8): torch.testing.assert_close(output, tokens, atol=5e-2, rtol=5e-2) self.assertEqual(tokens_per_expert.data_ptr(), buffer.tokens_per_expert.data_ptr()) - @_eager_test_include - @_mxfp8_align_test - @_overlap_test - def test_unfused_ops_on_overlap_group(self): - """On an overlap-pass group, MoeDispatch and MoeCombine run unfused and form an identity, - forward and backward.""" - config = self._overlap_config() - buffer = self._make_buffer_from_config(config) - dispatch = te_ops.MoeDispatch(config, buffer) - combine = te_ops.MoeCombine(config, buffer) - topk_idx, tokens, topk_weights = _make_identity_inputs(self.cfg.rank, self.cfg.ep_size) - x = tokens.clone().requires_grad_(True) - w = topk_weights.clone().requires_grad_(True) - recv_tokens, _tokens_per_expert, recv_weights = dispatch(x, topk_idx, w) - output = combine(recv_tokens * recv_weights.unsqueeze(-1).to(torch.bfloat16), topk_idx) - gen = torch.Generator(device=self.cfg.device).manual_seed(8) - grad_out = torch.randn(tokens.shape, device=self.cfg.device, generator=gen) - output.backward(grad_out.to(torch.bfloat16)) - torch.cuda.synchronize() - torch.testing.assert_close(output, tokens, atol=5e-2, rtol=5e-2) - torch.testing.assert_close(x.grad.float(), grad_out, atol=5e-2, rtol=5e-2) - grad_w_ref = (tokens.float() * grad_out).sum(-1, keepdim=True).expand_as(w) - torch.testing.assert_close(w.grad.float(), grad_w_ref, atol=5e-1, rtol=5e-2) - @_eager_test_include def test_dispatch_combine_identity_bf16(self): """MoeDispatch and MoeCombine basic ops form an identity in BF16.""" @@ -1779,21 +1745,11 @@ def _run_megamoe_vs_reference( ) def _moe_ops( - self, - config, - buffer, - glu_interleave_size=32, - accumulate_into_main_grad=False, - *, - ffn=HIDDEN_DIM, - activation=None, - fc_kwargs=({}, {}), - **linear_kwargs, + self, config, buffer, accumulate_into_main_grad=False, *, ffn=HIDDEN_DIM, **linear_kwargs ): - """MoeDispatch, GroupedLinear, ``activation`` (default ScaledSwiGLU), GroupedLinear and - MoeCombine over ``buffer``, with the routing channels connected and fixed weights (BF16 - unless ``linear_kwargs`` change the GroupedLinear settings; ``fc_kwargs`` adds settings - of the first and of the second GroupedLinear).""" + """MoeDispatch, GroupedLinear, ScaledSwiGLU, GroupedLinear and MoeCombine over ``buffer``, + with the routing channels connected and fixed weights (BF16 unless ``linear_kwargs`` + change the GroupedLinear settings).""" device = self.cfg.device gen = torch.Generator(device=device).manual_seed(5) linear_kwargs = { @@ -1806,12 +1762,12 @@ def _moe_ops( } dispatch = te_ops.MoeDispatch(config, buffer) fc1 = te_ops.GroupedLinear( - NUM_LOCAL_EXPERTS, HIDDEN_DIM, 2 * ffn, device=device, **linear_kwargs, **fc_kwargs[0] + NUM_LOCAL_EXPERTS, HIDDEN_DIM, 2 * ffn, device=device, **linear_kwargs ) fc2 = te_ops.GroupedLinear( - NUM_LOCAL_EXPERTS, ffn, HIDDEN_DIM, device=device, **linear_kwargs, **fc_kwargs[1] + NUM_LOCAL_EXPERTS, ffn, HIDDEN_DIM, device=device, **linear_kwargs ) - act = activation or te_ops.ScaledSwiGLU(glu_interleave_size=glu_interleave_size) + act = te_ops.ScaledSwiGLU(glu_interleave_size=32) combine = te_ops.MoeCombine(config, buffer) with torch.no_grad(): for fc in (fc1, fc2): @@ -1824,42 +1780,32 @@ def _moe_ops( fc2.set_extra_input_channel(0, "tokens_per_expert") return dispatch, fc1, act, fc2, combine + @staticmethod + def _scale_weights(ops): + """Give the GroupedLinear weights a power-of-two factor per row and column, so every MXFP8 + scale block has its own exponent.""" + gen = torch.Generator(device=ops[1].weight.device).manual_seed(6) + with torch.no_grad(): + for fc in (ops[1], ops[3]): + for w in fc.parameters(): + rows = torch.randint(-3, 4, (*w.shape[:-1], 1), device=w.device, generator=gen) + cols = torch.randint(-3, 4, w.shape[-1:], device=w.device, generator=gen) + values = torch.rand(w.shape, device=w.device, generator=gen) - 0.5 + w.copy_(values * 0.1 * torch.exp2((rows + cols).float())) + @_eager_test_include @_overflow_test_include @_mxfp8_align_test @_overlap_test def test_moe_overlap_op(self): - """The fused MoE op matches the same ops run unfused: output and every - gradient, also when tokens overflow the capacity and are dropped. Skipped where the + """The fused MoE op matches the same ops run unfused in output and every gradient, also + when tokens overflow the capacity, in BF16 and under MXFP8 transport. Skipped where the overlapped GEMMs cannot run.""" self._check_moe_overlap_op(None) - - @_eager_test_include - @_overflow_test_include - @_mxfp8_align_test - @_overlap_test - def test_moe_overlap_op_mxfp8(self): - """Under MXFP8 with MXFP8 EP transport the fused op matches the unfused ops, with weight - scales that differ across blocks in both directions. The fused op dispatches x and dY in - place from the EP dispatch window. An unset config transport runs MXFP8; another - transport recipe is rejected.""" - self._require_mxfp8_shapes() + if len(_overlap_recipes()) == 1: + return recipe = MXFP8BlockScaling() - with mock.patch.object( - tex, "ep_dispatch_gemm_fwd", wraps=tex.ep_dispatch_gemm_fwd - ) as fwd, mock.patch.object( - tex, "ep_combine_gemm_bwd", wraps=tex.ep_combine_gemm_bwd - ) as bwd: - self._check_moe_overlap_op(recipe, recipe) - for call in fwd.call_args_list + bwd.call_args_list: - self.assertEqual(call.kwargs["symm_input"], tex.ep_zero_copy_supported()) - # An unset config transport defaults to MXFP8, so it fuses. - config = self._overlap_config() - model = te_ops.Sequential(*self._moe_ops(config, self._make_buffer_from_config(config))) - topk_idx, tokens, w = _make_identity_inputs(self.cfg.rank, self.cfg.ep_size) - with te.autocast(recipe=recipe): - model(tokens, topk_idx, w, topk_idx) - self._assert_fusion(model, True) + self._check_moe_overlap_op(recipe, recipe) # A transport recipe other than MXFP8 with MXFP8 GEMMs is rejected, per direction. for name in ("dispatch_fwd_quant_recipe", "combine_bwd_quant_recipe"): with self.subTest(other_recipe=name): @@ -1875,47 +1821,39 @@ def test_moe_overlap_op_mxfp8(self): @_mxfp8_align_test @_overlap_test def test_moe_overlap_op_variants(self): - """The fused op matches the unfused ops, in BF16 and, where the overlap tests run MXFP8, in - MXFP8, also: without input and routing-weight gradients (no dispatch backward), with - MXFP8 weight parameters, with accumulate_into_main_grad, with an FFN size other than the - hidden size, and with FP32 weight parameters cast by - ``Module.to(torch.bfloat16)``.""" + """The fused op matches the unfused ops without input and routing-weight gradients, with + accumulate_into_main_grad (FP32 or BF16, accumulated or overwritten), with an FFN size other + than the hidden size, with frozen weights, and with FP32 or MXFP8 weight parameters.""" # (recipe, _check_moe_overlap_op settings) cases = [ (None, {"input_grad": False}), - # ffn != hidden, so a transposed weight layout cannot pass. - (None, {"ffn": HIDDEN_DIM // 2}), - (None, {"main_grad": True}), - (None, {"params_to_bf16": True}), - (None, {"params_to_bf16": True, "main_grad": True}), + (None, {"ffn": HIDDEN_DIM // 2}), # a transposed weight layout cannot pass + (None, {"params_to_bf16": True, "main_grad": torch.float32}), (None, {"frozen": (1,)}), (None, {"frozen": (3,)}), - (None, {"frozen": (1, 3), "main_grad": True}), + (None, {"frozen": (1, 3), "main_grad": torch.bfloat16, "overwrite": True}), ] - if _mxfp8_overlap(): + if len(_overlap_recipes()) > 1: recipe = MXFP8BlockScaling() cases += [ (recipe, {"input_grad": False}), (recipe, {"params_to_bf16": True}), - (recipe, {"quantized_weights": True}), + (recipe, {"quantized_weights": True, "main_grad": torch.float32}), (recipe, {"frozen": (1,)}), (recipe, {"frozen": (3,)}), - (recipe, {"frozen": (1, 3)}), ] - cases += [(recipe, {"quantized_weights": q, "main_grad": True}) for q in (False, True)] for recipe, settings in cases: with self.subTest(recipe=recipe, **settings): self._check_moe_overlap_op(recipe, recipe, **settings) def _check_moe_overlap_op( - self, recipe, transport=None, quantized_weights=False, main_grad=False, input_grad=True, - params_to_bf16=False, ffn=HIDDEN_DIM, frozen=(), + self, recipe, transport=None, quantized_weights=False, main_grad=None, overwrite=False, + input_grad=True, params_to_bf16=False, ffn=HIDDEN_DIM, frozen=(), ): # fmt: skip from transformer_engine.pytorch.ops.fused import moe_overlap device = self.cfg.device config = self._overlap_config(transport) - # Where FusedMoE cannot run, the overlap raises, so there is nothing to compare. if not moe_overlap.FusedMoE.is_supported() or ( recipe is not None and not (moe_overlap.GroupedMLP_CuTeGEMMGLU.is_supported() and transport is not None) @@ -1923,238 +1861,91 @@ def _check_moe_overlap_op( self.skipTest("FusedMoE is not supported here") # SM 10.7 runs the MXFP8 weight gradients into main_grad only above 256 receive rows. if ( - main_grad + main_grad is not None and len(frozen) < 2 and recipe is not None and torch.cuda.get_device_capability() == (10, 7) and config.recv_capacity_per_rank == 256 ): - self.skipTest( - "SM 10.7 MXFP8 main_grad weight gradients need more than 256 receive rows" - ) + self.skipTest("SM 10.7 MXFP8 main_grad weight gradients need more than 256 rows") with te.quantized_model_init(enabled=quantized_weights, recipe=recipe): buffer = self._make_buffer_from_config(config) ops = self._moe_ops( config, buffer, - accumulate_into_main_grad=main_grad, + accumulate_into_main_grad=main_grad is not None, ffn=ffn, dtype=torch.float32 if params_to_bf16 else torch.bfloat16, ) - gen = torch.Generator(device=device).manual_seed(6) if recipe is not None: - # Power-of-two factors per row and column give every scale block its own exponent. - with torch.no_grad(): - for fc in (ops[1], ops[3]): - for w in fc.parameters(): - rows = torch.randint( - -3, 4, (*w.shape[:-1], 1), device=device, generator=gen - ) - cols = torch.randint(-3, 4, w.shape[-1:], device=device, generator=gen) - values = torch.rand(w.shape, device=device, generator=gen) - 0.5 - w.copy_(values * 0.1 * torch.exp2((rows + cols).float())) + self._scale_weights(ops) if params_to_bf16: for op in ops: op.to(torch.bfloat16) # The weights of the GroupedLinear ops at these positions (1: FC1, 3: FC2) are frozen. for idx in frozen: ops[idx].weight.requires_grad_(False) - topk_idx, tokens, w = _make_identity_inputs(self.cfg.rank, self.cfg.ep_size) - grad_out = torch.randn(tokens.shape, device=device, generator=gen).to(torch.bfloat16) + tokens, topk_idx, w, grad_out = self._moe_calls(1)[0] def run(fused): - if not fused and params_to_bf16: - # The BF16 grouped MLP fusion reads the weight data as stored, so this reference - # runs the GroupedLinear ops, which cast it, and not FusedMoE. - ctx = contextlib.ExitStack() - ctx.enter_context( - mock.patch.object( - moe_overlap.GroupedMLP_CuTeGEMMGLUBf16, "is_supported", return_value=False - ) - ) - ctx.enter_context(self._moe_fusion(False)) - elif not fused: - ctx = self._moe_fusion(False) - else: - ctx = contextlib.nullcontext() + # The BF16 grouped MLP fusion reads the weight data as stored, so the reference runs + # the GroupedLinear ops, which cast it, and not FusedMoE. + cast_reference = mock.patch.object( + moe_overlap.GroupedMLP_CuTeGEMMGLUBf16, "is_supported", return_value=False + ) # Each run publishes its own counts: a stale value would show. buffer.tokens_per_expert.fill_(-1) buffer.total_recv_tokens.fill_(-1) - # Paged stashing pages the tensors that carry a token count. - stashable = [] - num_tokens = [] - - def pack(tensor): - if hasattr(tensor, "grouped_tensor_num_tokens"): - stashable.append((tensor.dtype, tensor.shape, tensor.nbytes)) - n = tensor.grouped_tensor_num_tokens - num_tokens.append(n.clone() if torch.is_tensor(n) else n) - return tensor - - combine_bwd = mock.patch.object( - moe_overlap.tex, "ep_combine_gemm_bwd", wraps=moe_overlap.tex.ep_combine_gemm_bwd - ) - with ctx, combine_bwd as combine_bwd_spy, te.autocast( - enabled=recipe is not None, recipe=recipe - ), torch.autograd.graph.saved_tensors_hooks(pack, lambda tensor: tensor): + with self._moe_fusion(fused), ( + cast_reference if (params_to_bf16 and not fused) else nullcontext() + ), te.autocast(enabled=recipe is not None, recipe=recipe): model = te_ops.Sequential(*ops) x = tokens.clone().requires_grad_(input_grad) topk_w = w.clone().requires_grad_(input_grad) for p in model.parameters(): p.grad = None - if main_grad: - p.main_grad = torch.full(p.shape, 0.5, dtype=torch.float32, device=device) + if main_grad is not None: + p.main_grad = torch.full(p.shape, 0.5, dtype=main_grad, device=device) + p.overwrite_main_grad = overwrite p.grad_added_to_main_grad = False y = model(x, topk_idx, topk_w, topk_idx) y.backward(grad_out) torch.cuda.synchronize() - fused_ops = self._moe_overlap_selected(model) + self._assert_fusion(model, fused) trained = [p for p in model.parameters() if p.requires_grad] - if main_grad: + if main_grad is not None: self.assertTrue(all(p.grad_added_to_main_grad for p in trained)) - grads = [(p.main_grad if main_grad else p.grad).clone() for p in trained] - counts = [int(n) for n in num_tokens] + grads = [(p.grad if main_grad is None else p.main_grad).clone() for p in trained] published = (buffer.tokens_per_expert.clone(), int(buffer.total_recv_tokens.item())) - # Whether the MXFP8 combine backward writes the columnwise grad_gemm_out and act_out. - columnwise_outputs = None - if recipe is not None and combine_bwd_spy.called: - args, kwargs = combine_bwd_spy.call_args - columnwise_outputs = ( - args[7]._columnwise_data is not None, - kwargs["act_out"] is not None, - ) - return ( - y.detach(), x.grad, topk_w.grad, grads, bool(fused_ops), stashable, counts, - published, columnwise_outputs, - ) # fmt: skip - - ref = run(False) - out = run(True) - self.assertFalse(ref[4]) - self.assertTrue(out[4], "fusion selection") - self._report_overlap_executed() - reason = _moe_overlap_unsupported_reason( - config, ffn, params_dtype=torch.bfloat16, - glu_interleave_size=32, single_grouped_weight=True, recipe=recipe, - primary_weights_in_fp8=quantized_weights, - ) # fmt: skip - self.assertIsNone(reason, "the fuser selects FusedMoE but the support check rejects it") - # Row tensors saved: recv tokens (and their scales), the FC1 output and the routing - # weights, plus the SwiGLU output in BF16. A frozen weight leaves out the input of its - # weight gradient: the recv tokens and scales for FC1, the SwiGLU output (BF16) for FC2. - fc1_inputs, fc2_inputs = (2, 0) if recipe is not None else (1, 1) - stashed = 4 - (fc1_inputs if 1 in frozen else 0) - (fc2_inputs if 3 in frozen else 0) - self.assertEqual(len(out[5]), stashed, "the fused op saves the stashable tensors") - # Their token count is the number of received rows kept. - kept = int(buffer.tokens_per_expert.sum()) - self.assertEqual(out[6], [kept] * stashed, "stashed token counts") + return (y.detach(), x.grad, topk_w.grad), grads, published + + (ref_outs, ref_grads, ref_published), (outs, grads, published) = run(False), run(True) # The fused op publishes the buffer counters as the unfused ops do: the kept tokens per # expert and the recv total before any drop, which exceeds the kept total on overflow. - self.assertTrue(torch.equal(out[7][0], ref[7][0]), "published per-expert counts") - self.assertEqual(out[7][1], ref[7][1], "published recv total") - self.assertEqual(int(out[7][0].sum()), kept, "published per-expert counts sum") + kept = int(published[0].sum()) + self.assertTrue(torch.equal(published[0], ref_published[0]), "per-expert counts") + self.assertEqual(published[1], ref_published[1], "recv total") if OVERFLOW: - self.assertGreater(out[7][1], config.recv_capacity_per_rank, "overflow recv total") - self.assertGreater(out[7][1], kept, "recv total counts the dropped tokens") - else: - self.assertGreaterEqual(out[7][1], kept) - if recipe is not None: - # The FC2 dgrad recomputes the SwiGLU output, so no [rows, ffn] tensor is saved: - # the recv tokens and scales, the FC1 output and the recv routing weights. - rows = next(shape[0] for dtype, shape, _ in out[5] if dtype == torch.float32) - saved = sum(nbytes for _, _, nbytes in out[5]) - ffn = ops[3].in_features - recv_bytes = 0 if 1 in frozen else HIDDEN_DIM + HIDDEN_DIM // 32 - self.assertEqual(saved, rows * (recv_bytes + 2 * ffn * 2 + 4), "saved bytes") - # A frozen weight's gradient operand is not written. - self.assertEqual( - out[8], (1 not in frozen, 3 not in frozen), "columnwise grad_gemm_out and act_out" - ) - # Where the unfused ops compute the SwiGLU output in their own kernel, single elements may - # round to another value, so those results are compared in norm. The unfused MXFP8 ops also - # round the FC2 dgrad and the SwiGLU backward output to BF16 before quantizing them, so - # outputs and weight gradients may differ by up to the E4M3 epsilon. + self.assertGreater(published[1], config.recv_capacity_per_rank) + self.assertGreater(published[1], kept) + # Single elements may round differently where the unfused ops compute the SwiGLU in their + # own kernel, and the unfused MXFP8 ops round to BF16 before quantizing, so compare in + # norm, within the E4M3 epsilon for MXFP8. norm_rtol = 2e-2 if recipe is None else 1 / 32 outputs_in_norm = (recipe is None and UNFUSED_BF16_MLP_REFERENCE) or params_to_bf16 if not input_grad: - self.assertTrue(all(g is None for g in out[1:3] + ref[1:3])) - for got, want in zip(out[: 3 if input_grad else 1], ref[:3]): + self.assertTrue(all(g is None for g in outs[1:] + ref_outs[1:])) + for got, want in zip(outs[: 3 if input_grad else 1], ref_outs): if outputs_in_norm: _assert_close_in_norm(got, want, rtol=norm_rtol) else: torch.testing.assert_close(got, want, rtol=2e-2, atol=2e-2) - for g, g_ref in zip(out[3], ref[3]): + for g, g_ref in zip(grads, ref_grads): if recipe is None and not (UNFUSED_BF16_MLP_REFERENCE or params_to_bf16): torch.testing.assert_close(g, g_ref, rtol=2e-2, atol=2e-2) else: _assert_close_in_norm(g, g_ref, rtol=norm_rtol) - @_eager_test_include - @_mxfp8_align_test - @_overlap_test - def test_moe_overlap_cpu_offload(self): - """Under CPU offload the tensors the fused op saves come back bitwise, and its output and - gradients match those without offload.""" - from transformer_engine.pytorch import cpu_offload - - self._require_moe_overlap() - tokens, topk_idx, w, grad_out = self._moe_calls(1)[0] - for recipe in [None] + ([MXFP8BlockScaling()] if _mxfp8_overlap() else []): - config = self._overlap_config(recipe) - ops = self._moe_ops(config, self._make_buffer_from_config(config)) - results = [] - for offload in (False, True): - saved = [] - for p in ops[1].parameters(): - p.grad = None - for p in ops[3].parameters(): - p.grad = None - with te.autocast(enabled=recipe is not None, recipe=recipe): - model = te_ops.Sequential(*ops) - x = tokens.clone().requires_grad_(True) - topk_w = w.clone().requires_grad_(True) - if offload: - ctx, sync, controller = cpu_offload.get_cpu_offload_context( - enabled=True, model_layers=1, manual_synchronization=True - ) - sync_state = ctx.offload_synchronizer - push, pop = sync_state.push_tensor, sync_state.pop_tensor - - def push_tensor(tensor, push=push): - saved.append([tensor.detach().reshape(-1).view(torch.uint8).cpu()]) - return len(saved) - 1, push(tensor) - - def pop_tensor(packed, pop=pop): - tensor = pop(packed[1]) - saved[packed[0]].append(tensor.detach().reshape(-1).view(torch.uint8)) - return tensor - - with mock.patch.object( - sync_state, "push_tensor", push_tensor - ), mock.patch.object(sync_state, "pop_tensor", pop_tensor): - with ctx: - y = model(x, topk_idx, topk_w, topk_idx) - y = sync(y) - controller.start_offload_layer(0) - controller.release_activation_forward_gpu_memory(0) - controller.start_reload_layer(0) - else: - y = model(x, topk_idx, topk_w, topk_idx) - y.backward(grad_out) - torch.cuda.synchronize() - self._assert_fusion(model, True) - self.assertEqual(bool(saved), offload, "offloaded tensors") - for before, after in saved: - self.assertTrue(torch.equal(before, after.cpu()), "a saved tensor changed") - grads = [p.grad.clone() for p in model.parameters()] - results.append([y.detach(), x.grad, topk_w.grad, *grads]) - with self.subTest(recipe=recipe): - for i, (got, want) in enumerate(zip(*results)): - if recipe is not None and i >= 3: - _assert_close_in_norm(got, want, rtol=1 / 32) - else: - torch.testing.assert_close(got, want, rtol=2e-2, atol=2e-2) - def _require_moe_overlap(self): from transformer_engine.pytorch.ops.fused import moe_overlap @@ -2170,31 +1961,22 @@ def _moe_fusion(fused): from transformer_engine.pytorch.ops.fused import moe_overlap if fused: - return contextlib.nullcontext() + return nullcontext() return mock.patch.object(moe_overlap, "_moe_overlap_available", return_value=False) - def _report_overlap_executed(self): - """Tell the launcher this test ran the fused overlap ops on this rank; an overlap pass - needs a minimum number of such tests on every rank.""" - print(f"OVERLAP_EXECUTED test={self._testMethodName} rank={self.cfg.rank}", flush=True) - def _assert_fusion(self, model, fused): - """Check that ``model`` ran FusedMoE exactly when ``fused``, and report it when it did.""" - self.assertEqual(bool(self._moe_overlap_selected(model)), fused) - if fused: - self._report_overlap_executed() - - @staticmethod - def _moe_overlap_selected(model): - """The FusedMoE ops of the plan ``model`` ran last.""" + """Check that ``model`` ran FusedMoE exactly when ``fused``. When it did, tell the + launcher: an overlap pass needs a minimum number of such tests on every rank.""" from transformer_engine.pytorch.ops.fused import moe_overlap - return [ - op + ran = any( + isinstance(op, moe_overlap.FusedMoE) for group in model._module_groups for op, _ in getattr(group, "_forward_ops", []) - if isinstance(op, moe_overlap.FusedMoE) - ] + ) + self.assertEqual(ran, fused) + if fused: + print(f"OVERLAP_EXECUTED test={self._testMethodName} rank={self.cfg.rank}", flush=True) def _moe_calls(self, num_calls): """(tokens, topk_idx, topk_weights, grad_output) of calls that each route differently.""" @@ -2242,37 +2024,6 @@ def _assert_moe_close( else: torch.testing.assert_close(got, ref, rtol=rtol, atol=rtol) - @_mxfp8_align_test - @_overlap_test - def test_moe_overlap_wgrad(self): - """With accumulate_into_main_grad, the fused op writes the weight gradients of two calls - into an FP32 or BF16 main_grad, accumulated or overwritten, as the unfused ops do.""" - self._require_moe_overlap() - config = self._overlap_config() - calls = self._moe_calls(2) - ops = self._moe_ops( - config, self._make_buffer_from_config(config), accumulate_into_main_grad=True - ) - weights = (ops[1].weight, ops[3].weight) - for dtype, overwrite in itertools.product((torch.float32, torch.bfloat16), (False, True)): - results = [] - for fused in (False, True): - for p in weights: - p.grad = None - p.main_grad = torch.full(p.size(), 0.5, dtype=dtype, device=self.cfg.device) - p.overwrite_main_grad = overwrite - p.grad_added_to_main_grad = False - with self._moe_fusion(fused): - model = te_ops.Sequential(*ops) - outs = [self._moe_call(model, *call) for call in calls] - torch.cuda.synchronize() - self._assert_fusion(model, fused) - for p in weights: - self.assertTrue(p.grad_added_to_main_grad) - results.append((outs, [p.main_grad.clone() for p in weights])) - with self.subTest(dtype=dtype, overwrite=overwrite): - self._assert_moe_close(results[1], results[0]) - @_eager_test_include @_overflow_test_include @_mxfp8_align_test @@ -2281,15 +2032,9 @@ def test_moe_overlap_inference(self): """Forward only, under no_grad, the fused op matches the unfused ops and publishes the same per-expert counts and recv total, also when tokens overflow the capacity. It is selected with accumulate_into_main_grad, as no weight gradient runs.""" - from transformer_engine.pytorch.ops.fused import moe_overlap - self._require_moe_overlap() topk_idx, tokens, w = _make_identity_inputs(self.cfg.rank, self.cfg.ep_size) - for recipe in (None, MXFP8BlockScaling()): - if recipe is not None and not ( - _mxfp8_overlap() and moe_overlap.GroupedMLP_CuTeGEMMGLU.is_supported() - ): - continue + for recipe in _overlap_recipes(): with self.subTest(recipe=recipe): config = self._overlap_config(recipe) buffer = self._make_buffer_from_config(config) @@ -2298,7 +2043,6 @@ def test_moe_overlap_inference(self): p.main_grad = torch.zeros(p.size(), dtype=torch.float32, device=self.cfg.device) results = [] for fused in (False, True): - # Each run publishes its own counts: a stale value would show. buffer.tokens_per_expert.fill_(-1) buffer.total_recv_tokens.fill_(-1) with self._moe_fusion(fused), torch.no_grad(), te.autocast( @@ -2309,18 +2053,13 @@ def test_moe_overlap_inference(self): torch.cuda.synchronize() self._assert_fusion(model, fused) results.append( - ( - out, - buffer.tokens_per_expert.clone(), - int(buffer.total_recv_tokens.item()), - ) + (out, buffer.tokens_per_expert.clone(), int(buffer.total_recv_tokens)) ) (ref_out, ref_counts, ref_total), (out, counts, total) = results _assert_close_in_norm(out, ref_out, rtol=2e-2 if recipe is None else 1 / 16) self.assertTrue(torch.equal(counts, ref_counts), "published per-expert counts") self.assertEqual(total, ref_total, "published recv total") if OVERFLOW: - self.assertGreater(total, config.recv_capacity_per_rank) self.assertGreater(total, int(counts.sum())) @_eager_test_include @@ -2341,9 +2080,7 @@ def test_moe_overlap_rank_without_tokens(self): ) results = [] for fused in (False, True): - for p in ops[1].parameters(): - p.grad = None - for p in ops[3].parameters(): + for p in (*ops[1].parameters(), *ops[3].parameters()): p.grad = None with self._moe_fusion(fused): model = te_ops.Sequential(*ops) @@ -2370,29 +2107,19 @@ def test_moe_overlap_rank_without_input_grad(self): if self.cfg.ep_size < 2: self.skipTest("needs a peer rank") config = self._overlap_config() - ops = self._moe_ops(config, self._make_buffer_from_config(config)) - tokens, topk_idx, w, grad = self._moe_calls(1)[0] - detached = self.cfg.rank == 0 - with self._moe_fusion(True): - model = te_ops.Sequential(*ops) - _, ref_tokens_grad, ref_weights_grad = self._moe_call(model, tokens, topk_idx, w, grad) - _, tokens_grad, weights_grad = self._moe_call( - model, - tokens, - topk_idx, - w, - grad, - tokens_grad=not detached, - weights_grad=not detached, - ) + model = te_ops.Sequential(*self._moe_ops(config, self._make_buffer_from_config(config))) + args = (model, *self._moe_calls(1)[0]) + needs_grad = self.cfg.rank != 0 + _, ref_x_grad, ref_w_grad = self._moe_call(*args) + _, x_grad, w_grad = self._moe_call(*args, tokens_grad=needs_grad, weights_grad=needs_grad) torch.cuda.synchronize() self._assert_fusion(model, True) - if detached: - self.assertIsNone(tokens_grad) - self.assertIsNone(weights_grad) + if needs_grad: + torch.testing.assert_close(x_grad, ref_x_grad) + torch.testing.assert_close(w_grad, ref_w_grad) else: - torch.testing.assert_close(tokens_grad, ref_tokens_grad) - torch.testing.assert_close(weights_grad, ref_weights_grad) + self.assertIsNone(x_grad) + self.assertIsNone(w_grad) @_eager_test_include @_overflow_test_include @@ -2403,160 +2130,10 @@ def test_moe_overlap_rejects_int32_counts(self): self._require_moe_overlap() config = self._overlap_config() buffer = self._make_buffer_from_config(config) - ops = self._moe_ops(config, buffer) + model = te_ops.Sequential(*self._moe_ops(config, buffer)) buffer.tokens_per_expert = buffer.tokens_per_expert.to(torch.int32) - model = te_ops.Sequential(*ops) - tokens, topk_idx, w, grad = self._moe_calls(1)[0] with self.assertRaisesRegex(TypeError, "int64"): - self._moe_call(model, tokens, topk_idx, w, grad) - - def _native_dispatch_gemm_fwd(self, alignment, offsets_dtype=torch.int64, ffn=256): - """tex.ep_dispatch_gemm_fwd on zero operands, as a caller that bypasses FusedMoE.""" - device = self.cfg.device - buffer = self._make_buffer_from_config(self._overlap_config()) - rows = buffer.recv_capacity_per_rank or 2 * OVERLAP_ALIGNMENT - return tex.ep_dispatch_gemm_fwd( - buffer.handle_mem, - torch.zeros(TOKENS_PER_RANK, TOP_K, dtype=torch.int64, device=device), - torch.zeros(TOKENS_PER_RANK, HIDDEN_DIM, dtype=torch.bfloat16, device=device), - torch.ones(TOKENS_PER_RANK, TOP_K, dtype=torch.float32, device=device), - torch.zeros( - NUM_LOCAL_EXPERTS, 2 * ffn, HIDDEN_DIM, dtype=torch.bfloat16, device=device - ), - torch.zeros(rows, HIDDEN_DIM, dtype=torch.bfloat16, device=device), - torch.zeros(rows, dtype=torch.float32, device=device), - torch.zeros(NUM_LOCAL_EXPERTS, dtype=torch.int64, device=device), - torch.zeros(NUM_LOCAL_EXPERTS + 2, dtype=offsets_dtype, device=device)[1:], - torch.zeros(rows, 2 * ffn, dtype=torch.bfloat16, device=device), - torch.zeros(rows, ffn, dtype=torch.bfloat16, device=device), - TOP_K, - alignment, - ) - - @_mxfp8_align_test - @_overlap_test - def test_moe_overlap_rejects_strided_outputs(self): - """The native overlapped calls reject strided tensors they read or write through a raw - pointer, for callers that bypass FusedMoE.""" - self._require_moe_overlap() - device = self.cfg.device - buffer = self._make_buffer_from_config(self._overlap_config()) - rows = buffer.recv_capacity_per_rank or 2 * OVERLAP_ALIGNMENT - ffn = 256 - bf16 = {"dtype": torch.bfloat16, "device": device} - offsets = torch.zeros(NUM_LOCAL_EXPERTS + 2, dtype=torch.int64, device=device)[1:] - - def strided(*shape, dtype): - return torch.zeros(*shape, 2, dtype=dtype, device=device)[..., 0] - - with self.assertRaisesRegex(RuntimeError, "recv_topk_weights must be a contiguous"): - tex.ep_combine_gemm_fwd( - buffer.handle_mem, - torch.zeros(rows, ffn, **bf16), - offsets, - torch.zeros(NUM_LOCAL_EXPERTS, HIDDEN_DIM, ffn, **bf16), - torch.zeros(rows, HIDDEN_DIM, **bf16), - torch.zeros(TOKENS_PER_RANK, HIDDEN_DIM, **bf16), - TOP_K, - OVERLAP_ALIGNMENT, - torch.int64, - strided(rows, dtype=torch.float32), - ) - for name, grad_tokens, grad_topk in ( - ( - "grad_tokens", - strided(TOKENS_PER_RANK, HIDDEN_DIM, dtype=torch.bfloat16), - torch.zeros(TOKENS_PER_RANK, TOP_K, dtype=torch.float32, device=device), - ), - ( - "grad_topk_weights", - torch.zeros(TOKENS_PER_RANK, HIDDEN_DIM, **bf16), - strided(TOKENS_PER_RANK, TOP_K, dtype=torch.float32), - ), - ): - with self.subTest(strided=name): - with self.assertRaisesRegex(RuntimeError, f"{name} must be a contiguous"): - tex.ep_dispatch_gemm_bwd( - buffer.handle_mem, - torch.zeros(rows, 2 * ffn, **bf16), - torch.zeros(rows, dtype=torch.float32, device=device), - offsets, - torch.zeros(NUM_LOCAL_EXPERTS, 2 * ffn, HIDDEN_DIM, **bf16), - torch.zeros(rows, HIDDEN_DIM, **bf16), - grad_tokens, - grad_topk, - TOP_K, - OVERLAP_ALIGNMENT, - torch.int64, - ) - - @_mxfp8_align_test - @_overlap_test - def test_moe_overlap_rejects_other_alignment(self): - """The native overlapped dispatch takes the alignment 256 only, for callers that bypass - FusedMoE.""" - self._require_moe_overlap() - with self.assertRaisesRegex(RuntimeError, "must be 256"): - self._native_dispatch_gemm_fwd(128) - - @_mxfp8_align_test - @_overlap_test - def test_moe_overlap_rejects_int32_expert_offsets(self): - """The expert layout the native overlapped GEMMs read is int64.""" - self._require_moe_overlap() - with self.assertRaisesRegex(RuntimeError, "(?i)int64"): - self._native_dispatch_gemm_fwd(OVERLAP_ALIGNMENT, offsets_dtype=torch.int32) - - @_mxfp8_align_test - @_overlap_test - def test_moe_overlap_cold_sizing_from_two_threads(self): - """The first workspace sizing of a shape queries the CuTeDSL layouts through Python. Two - host threads sizing the same cold shape, and two different ones, both finish.""" - self._require_moe_overlap() - for ffns in ((320, 320), (384, 448)): - with self.subTest(ffns=ffns): - barrier = threading.Barrier(2) - errors = [None, None] - - def size(idx, ffn): - torch.cuda.set_device(self.cfg.device) - barrier.wait() - # The int32 offsets fail the call after its sizing, before any launch. - try: - self._native_dispatch_gemm_fwd( - OVERLAP_ALIGNMENT, offsets_dtype=torch.int32, ffn=ffn - ) - except RuntimeError as err: - errors[idx] = err - - threads = [ - threading.Thread(target=size, args=(idx, ffn), daemon=True) - for idx, ffn in enumerate(ffns) - ] - for thread in threads: - thread.start() - for thread in threads: - thread.join(timeout=120) - self.assertFalse(any(t.is_alive() for t in threads), "the cold sizing hangs") - for err in errors: - self.assertIsNotNone(err) - self.assertRegex(str(err), "(?i)int64") - - @_mxfp8_align_test - @_overlap_test - def test_moe_overlap_names_disabled_cutedsl(self): - """With the CuTeDSL backend switched off at run time, the native overlapped calls name the - missing backend instead of failing inside the workspace layout query.""" - self._require_moe_overlap() - from transformer_engine.common import _get_shared_object_file - - core_lib = ctypes.CDLL(str(_get_shared_object_file("core"))) - core_lib.nvte_set_cutedsl_backend(0) - try: - with self.assertRaisesRegex(RuntimeError, "NVTE_ENABLE_CUTEDSL_BACKEND"): - self._native_dispatch_gemm_fwd(OVERLAP_ALIGNMENT) - finally: - core_lib.nvte_set_cutedsl_backend(1) + self._moe_call(model, *self._moe_calls(1)[0]) @_mxfp8_align_test @_overlap_test @@ -2573,207 +2150,107 @@ def test_moe_overlap_rejects_dispatch_chunk(self): with self.assertRaisesRegex(RuntimeError, "dispatch_chunk_tokens"): self._moe_call(model, tokens, topk_idx, w, None) - @staticmethod - @contextlib.contextmanager - def _deterministic_algorithms(): - """Require deterministic algorithms, warning for torch ops that have none.""" - enabled = torch.are_deterministic_algorithms_enabled() - warn_only = torch.is_deterministic_algorithms_warn_only_enabled() - torch.use_deterministic_algorithms(True, warn_only=True) - try: - yield - finally: - torch.use_deterministic_algorithms(enabled, warn_only=warn_only) - - def _assert_bitwise_equal(self, got, ref, path="result"): - """Nested lists of tensors (or None) are equal bit for bit.""" - if isinstance(ref, (list, tuple)): - self.assertEqual(len(got), len(ref), path) - for i, (g, r) in enumerate(zip(got, ref)): - self._assert_bitwise_equal(g, r, f"{path}[{i}]") - elif ref is None: - self.assertIsNone(got, path) - else: - diff = (got.float() - ref.float()).abs().max().item() - self.assertTrue(torch.equal(got, ref), f"{path} differs between runs by {diff}") - @_mxfp8_align_test @_overlap_test def test_moe_overlap_deterministic(self): - """With deterministic algorithms required, two runs of the fused forward and backward agree - bit for bit in the output and the input and routing-weight gradients, and within tolerance - in the weight gradients, and match the run that allows non-deterministic algorithms within - tolerance; in BF16 and, where the overlap tests run MXFP8, under MXFP8 transport.""" + """With deterministic algorithms required, two fused runs agree bit for bit in the output + and the input and routing-weight gradients, and within tolerance in the weight gradients, + and match the non-deterministic run within tolerance; in BF16 and under MXFP8.""" self._require_moe_overlap() - for recipe in [None] + ([MXFP8BlockScaling()] if _mxfp8_overlap() else []): - with self.subTest(recipe=recipe): - self._run_moe_overlap_deterministic(recipe) - - def _run_moe_overlap_deterministic(self, recipe): - if recipe is not None: - self._require_mxfp8_shapes() - config = self._overlap_config(recipe) - model = te_ops.Sequential(*self._moe_ops(config, self._make_buffer_from_config(config))) tokens, topk_idx, w, grad = self._moe_calls(1)[0] + for recipe in _overlap_recipes(): + with self.subTest(recipe=recipe): + config = self._overlap_config(recipe) + model = te_ops.Sequential( + *self._moe_ops(config, self._make_buffer_from_config(config)) + ) - def run(): - for p in model.parameters(): - p.grad = None - with te.autocast(enabled=recipe is not None, recipe=recipe): - out = self._moe_call(model, tokens, topk_idx, w, grad) - torch.cuda.synchronize() - return out, self._param_grads(model) + def run(): + for p in model.parameters(): + p.grad = None + with te.autocast(enabled=recipe is not None, recipe=recipe): + out = self._moe_call(model, tokens, topk_idx, w, grad) + torch.cuda.synchronize() + return out, self._param_grads(model) - fast = run() - self._assert_fusion(model, True) - with self._deterministic_algorithms(): - first = run() - second = run() - self._assert_fusion(model, True) - self._assert_bitwise_equal(second[0], first[0]) - self._assert_moe_close(second[1], first[1]) - self._assert_moe_close(first, fast) + fast = run() + enabled = torch.are_deterministic_algorithms_enabled() + warn_only = torch.is_deterministic_algorithms_warn_only_enabled() + torch.use_deterministic_algorithms(True, warn_only=True) + try: + first, second = run(), run() + finally: + torch.use_deterministic_algorithms(enabled, warn_only=warn_only) + self._assert_fusion(model, True) + for got, want in zip(second[0], first[0]): + self.assertTrue( + torch.equal(got, want), "runs differ in an output or input grad" + ) + self._assert_moe_close(second[1], first[1]) + self._assert_moe_close(first, fast) @_mxfp8_align_test @_overlap_test def test_moe_overlap_cuda_graph(self): """The fused forward and backward, captured in a CUDA graph after warmup and replayed with - new routing, tokens, topk_weights and output gradient, match the unfused ops; in BF16 and, - where the overlap tests run MXFP8, under MXFP8 transport (its shared dispatch window, - requantization and weight gradients captured and replayed).""" + new routing, tokens, topk_weights and output gradient, match the unfused ops; in BF16 and + under MXFP8 transport.""" self._require_moe_overlap() - for recipe in [None] + ([MXFP8BlockScaling()] if _mxfp8_overlap() else []): - with self.subTest(recipe=recipe): - self._run_moe_overlap_cuda_graph(recipe) - - def _run_moe_overlap_cuda_graph(self, recipe): - """Capture and replay the fused MoE under ``recipe`` (None for BF16) and match the unfused - ops run under the same autocast.""" - if recipe is not None: - self._require_mxfp8_shapes() device = self.cfg.device - config = self._overlap_config(recipe) - ops = self._moe_ops(config, self._make_buffer_from_config(config)) - ref_ops = self._moe_ops(config, self._make_buffer_from_config(config)) - if recipe is not None: - # Power-of-two row and column factors give every scale block its own exponent. Both - # models share the weights. - gen = torch.Generator(device=device).manual_seed(6) - with torch.no_grad(): - for fc, ref_fc in ((ops[1], ref_ops[1]), (ops[3], ref_ops[3])): - for w_fused, w_ref in zip(fc.parameters(), ref_fc.parameters()): - shape = w_fused.shape - rows = torch.randint(-3, 4, (*shape[:-1], 1), device=device, generator=gen) - cols = torch.randint(-3, 4, shape[-1:], device=device, generator=gen) - values = torch.rand(shape, device=device, generator=gen) - 0.5 - w_fused.copy_(values * 0.1 * torch.exp2((rows + cols).float())) - w_ref.copy_(w_fused) - gen = torch.Generator(device=device).manual_seed(9) - random_idx, random_tokens, random_w = _make_moe_inputs(self.cfg.rank, self.cfg.ep_size) - replays = [ - ( - random_tokens, - random_idx, - random_w, - torch.randn(random_tokens.shape, device=device, generator=gen).to(torch.bfloat16), - ), - self._moe_calls(1)[0], - ] - # Static inputs, holding the captured call's values first. - tokens, topk_idx, w, grad = (t.clone() for t in self._moe_calls(2)[1]) - x = tokens.requires_grad_(True) - topk_w = w.requires_grad_(True) - model = te_ops.Sequential(*ops) - params = list(model.parameters()) - out = {} - - def step(): - for t in (x, topk_w, *params): - t.grad = None - with te.autocast(enabled=recipe is not None, recipe=recipe): - out["y"] = model(x, topk_idx, topk_w, topk_idx) - out["y"].backward(grad) - - graph = self._capture(step) - self._assert_fusion(model, True) - results = [] - for call in replays: - with torch.no_grad(): - for static, value in zip((x, topk_idx, topk_w, grad), call): - static.copy_(value) - graph.replay() - got = ( - (out["y"].detach().clone(), x.grad.clone(), topk_w.grad.clone()), - [p.grad.clone() for p in params], - ) - ref_model = te_ops.Sequential(*ref_ops) - for p in ref_model.parameters(): - p.grad = None - with self._moe_fusion(False), te.autocast(enabled=recipe is not None, recipe=recipe): - ref = (self._moe_call(ref_model, *call), self._param_grads(ref_model)) - torch.cuda.synchronize() - results.append((got, ref)) - # Compare once every rank has run every replay, so a mismatch on one rank leaves no rank - # waiting in a later replay. - for got, ref in results: - if recipe is None: - self._assert_moe_close(got, ref) - else: - # The unfused MXFP8 ops round the SwiGLU output and requantize to E4M3, so compare - # outputs and gradients in norm at the E4M3 tolerance. - self._assert_moe_close(got, ref, in_norm=True, outputs_in_norm=True, rtol=1 / 16) - - @_mxfp8_align_test - @_overlap_test - def test_moe_overlap_instances(self): - """Weights created in inference mode, which have no version counter, run in the fused op. - Two FusedMoE instances, each with its own - EpBuffer, interleave safely: the second instance's forward and backward between the first - instance's forward and backward leave the first instance's output and gradients identical - to running it alone. One buffer and op instance per outstanding call.""" - self._require_moe_overlap() - config = self._overlap_config() - with torch.inference_mode(): - ops = self._moe_ops(config, self._make_buffer_from_config(config)) - model = te_ops.Sequential(*ops) - topk_idx, tokens, w = _make_identity_inputs(self.cfg.rank, self.cfg.ep_size) - model(tokens, topk_idx, w, topk_idx) - torch.cuda.synchronize() - self._assert_fusion(model, True) - - # Separate instances and buffers; _moe_ops seeds identical weights. - model_a = te_ops.Sequential(*self._moe_ops(config, self._make_buffer_from_config(config))) - model_b = te_ops.Sequential(*self._moe_ops(config, self._make_buffer_from_config(config))) - call_a, call_b = self._moe_calls(2) + for recipe in _overlap_recipes(): + with self.subTest(recipe=recipe): + config = self._overlap_config(recipe) + ops = self._moe_ops(config, self._make_buffer_from_config(config)) + ref_ops = self._moe_ops(config, self._make_buffer_from_config(config)) + if recipe is not None: + self._scale_weights(ops) + with torch.no_grad(): + for idx in (1, 3): + for p, p_ref in zip(ops[idx].parameters(), ref_ops[idx].parameters()): + p_ref.copy_(p) + tokens, topk_idx, w, grad = (t.clone() for t in self._moe_calls(1)[0]) + x = tokens.requires_grad_(True) + topk_w = w.requires_grad_(True) + model = te_ops.Sequential(*ops) + params = list(model.parameters()) + out = {} - def forward(model, call): - for p in model.parameters(): - p.grad = None - x = call[0].clone().requires_grad_(True) - topk_w = call[2].clone().requires_grad_(True) - return x, topk_w, model(x, call[1], topk_w, call[1]) + def step(): + for t in (x, topk_w, *params): + t.grad = None + with te.autocast(enabled=recipe is not None, recipe=recipe): + out["y"] = model(x, topk_idx, topk_w, topk_idx) + out["y"].backward(grad) - def backward(model, x, topk_w, y, grad): - y.backward(grad) - torch.cuda.synchronize() - return [y.detach(), x.grad, topk_w.grad] + self._param_grads(model) - - # Each call run alone, as the serial reference. - xa, wa, ya = forward(model_a, call_a) - alone_a = backward(model_a, xa, wa, ya, call_a[3]) - self._assert_fusion(model_a, True) - xb, wb, yb = forward(model_b, call_b) - alone_b = backward(model_b, xb, wb, yb, call_b[3]) - self._assert_fusion(model_b, True) - - # Interleaved: the second instance's whole call lands between the first's forward and - # backward; separate buffers keep each call's routing state intact. - xa, wa, ya = forward(model_a, call_a) - xb, wb, yb = forward(model_b, call_b) - inter_b = backward(model_b, xb, wb, yb, call_b[3]) - inter_a = backward(model_a, xa, wa, ya, call_a[3]) - self._assert_moe_close(inter_a, alone_a, False, outputs_in_norm=False) - self._assert_moe_close(inter_b, alone_b, False, outputs_in_norm=False) + graph = self._capture(step) + self._assert_fusion(model, True) + # Replay with other routing, tokens, topk_weights and output gradient. + new_idx, new_tokens, new_w = _make_moe_inputs(self.cfg.rank, self.cfg.ep_size) + gen = torch.Generator(device=device).manual_seed(9) + new_grad = torch.randn(new_tokens.shape, device=device, generator=gen) + call = (new_tokens, new_idx, new_w, new_grad.to(torch.bfloat16)) + with torch.no_grad(): + for static, value in zip((x, topk_idx, topk_w, grad), call): + static.copy_(value) + graph.replay() + got = ( + (out["y"].detach().clone(), x.grad.clone(), topk_w.grad.clone()), + [p.grad.clone() for p in params], + ) + ref_model = te_ops.Sequential(*ref_ops) + for p in ref_model.parameters(): + p.grad = None + with self._moe_fusion(False), te.autocast( + enabled=recipe is not None, recipe=recipe + ): + ref = (self._moe_call(ref_model, *call), self._param_grads(ref_model)) + torch.cuda.synchronize() + # The unfused MXFP8 ops requantize to E4M3, so they are compared in norm at its + # tolerance. + if recipe is None: + self._assert_moe_close(got, ref) + else: + self._assert_moe_close(got, ref, in_norm=True, rtol=1 / 16) # Autograd diff --git a/tests/pytorch/distributed/run_test_ep.sh b/tests/pytorch/distributed/run_test_ep.sh index 276044f8333..b10fb081df1 100755 --- a/tests/pytorch/distributed/run_test_ep.sh +++ b/tests/pytorch/distributed/run_test_ep.sh @@ -177,17 +177,13 @@ else run_pass "overlap" 0 0 0 1 0 1 run_pass "overlap_eager" 0 1 0 1 0 1 run_pass "overlap_overflow" 0 0 1 1 0 1 - # Per-direction SM counts (dispatch fwd, combine fwd, dispatch bwd, combine bwd). The backward - # split skips when Transformer Engine was built against an NCCL EP without backward SM budgets. # NVTE_EP_OVERLAP_CONFIG: combine_chunk_hidden,push_last_chunk_sms,reduce_last_chunk_sms, - # dispatch_chunk_tokens. Flags per 256 combine columns without splitting the last chunk here, - # three combine chunks per row with split last chunks in the hidden 1536 pass below. - NVTE_EP_OVERLAP_CONFIG=256,0,0,0 NVTE_EP_COMM_SMS=12,20,0,0 run_pass "overlap_split" 0 0 0 1 0 1 - NVTE_EP_COMM_SMS=12,20,24,16 run_pass "overlap_split_bwd" 0 0 0 1 0 1 - # A hidden size that 1024 does not divide: the combine waits on whole rows. + # dispatch_chunk_tokens. NVTE_EP_COMM_SMS: SMs of the dispatch fwd, combine fwd, dispatch bwd and + # combine bwd (the pass skips without NCCL EP backward SM budgets). Two 256-column combine chunks + # per row, then a hidden size with a shorter last chunk, split across SMs. + NVTE_EP_OVERLAP_CONFIG=256,0,0,0 NVTE_EP_COMM_SMS=12,20,24,16 run_pass "overlap_split" 0 0 0 1 0 1 NVTE_EP_OVERLAP_CONFIG=512,16,8,0 NVTE_EP_HIDDEN_DIM=1536 run_pass "overlap_h1536" 0 0 0 1 0 1 - # A dispatch chunk other than the alignment is rejected; only that test runs and it runs no - # fused op. + # A dispatch chunk other than the alignment is rejected; only that test runs, with no fused op. NVTE_EP_OVERLAP_CONFIG=0,0,0,128 NVTE_EP_TEST_FILTER=test_moe_overlap_rejects_dispatch_chunk \ run_pass "overlap_dispatch_chunk" 0 0 0 1 0 1 0 fi diff --git a/tests/pytorch/test_ep_gemm.py b/tests/pytorch/test_ep_gemm.py index 71a0e901179..b1b712a639f 100644 --- a/tests/pytorch/test_ep_gemm.py +++ b/tests/pytorch/test_ep_gemm.py @@ -2,40 +2,50 @@ # # See LICENSE for license information. -"""Signal-aware grouped GEMM that follows the EP dispatch, loaded through TVM-FFI.""" +"""EP overlap tests: the signal-aware grouped GEMMs loaded through TVM-FFI, and the CPU checks of +the NCCL EP library discovery, the overlap toggle and the FusedMoE support rules.""" # pylint: disable=wrong-import-position -import ctypes import os import pytest import torch +import transformer_engine +from transformer_engine.common.recipe import ( + DelayedScaling, + Float8CurrentScaling, + Format, + MXFP8BlockScaling, +) + # The optional CuTeDSL dependencies are imported only when the overlap is requested, where a # missing one fails the module. -if os.environ.get("NVTE_MOE_OVERLAP", "0") == "0": - pytest.skip("NVTE_MOE_OVERLAP is not 1", allow_module_level=True) +OVERLAP = os.environ.get("NVTE_MOE_OVERLAP", "0") != "0" +if OVERLAP: + import ctypes -import tvm_ffi + import tvm_ffi -import transformer_engine.pytorch # pylint: disable=unused-import -import transformer_engine_torch as tex -from transformer_engine.common.CuTeDSL.ep_gemm import ( - combine_gemm, - dispatch_gemm, - wgrad_gemm, -) + import transformer_engine.pytorch # pylint: disable=unused-import + from transformer_engine.common.CuTeDSL.ep_gemm import ( + combine_gemm, + dispatch_gemm, + wgrad_gemm, + ) -pytestmark = [ - pytest.mark.skipif( - not torch.cuda.is_available() - or torch.cuda.get_device_capability() not in ((10, 0), (10, 3), (10, 7)), - reason="the kernels need SM 10.0, 10.3 or 10.7", - ), -] +requires_kernels = pytest.mark.skipif( + not OVERLAP + or not torch.cuda.is_available() + or torch.cuda.get_device_capability() not in ((10, 0), (10, 3), (10, 7)), + reason="the kernels need NVTE_MOE_OVERLAP=1 and SM 10.0, 10.3 or 10.7", +) -TILE = dispatch_gemm.ROWS_PER_TILE +TILE = dispatch_gemm.ROWS_PER_TILE if OVERLAP else 128 +# Expert rows: an empty expert, and experts shorter than the others. +ROWS = [2 * TILE, TILE, 0, 3 * TILE] +ROWS_SHORT = [TILE, 0, 2 * TILE, TILE] # SM 10.7 has no MXFP8 tail tiles. MXFP8_TAILS = torch.cuda.is_available() and torch.cuda.get_device_capability() != (10, 7) @@ -136,22 +146,15 @@ def _run_gemm(rows_per_expert, rows_alignment, mxfp8, tail_clusters, device_layo return a.float(), b.float(), alpha, torch.ones_like(prob), c, d_float, counter.item() -@pytest.mark.parametrize( - "rows_alignment,mxfp8,rows_per_expert", - [ - (TILE, False, [2 * TILE, TILE, 0, 3 * TILE]), - (TILE, True, [2 * TILE, TILE, 0, 3 * TILE]), - ], -) +@pytest.mark.parametrize("mxfp8", [False, True]) @pytest.mark.parametrize("tail_clusters", [0, 4]) @pytest.mark.parametrize("device_layout", [False, True]) -def test_dispatch_gemm_matches_reference( - rows_alignment, mxfp8, rows_per_expert, tail_clusters, device_layout -): - """Grouped GEMM over padded slabs matches a float32 reference, also with experts padded to - fewer rows than a tile, with a tail launch sharing the tiles and with the dispatch-written - layout; rows past the last expert stay 0.""" - args = (rows_per_expert, rows_alignment, mxfp8) +@requires_kernels +def test_dispatch_gemm_matches_reference(mxfp8, tail_clusters, device_layout): + """Grouped GEMM over padded slabs matches a float32 reference, also with a tail launch sharing + the tiles and with the dispatch-written layout; rows past the last expert stay 0.""" + rows_per_expert = ROWS + args = (rows_per_expert, TILE, mxfp8) a, b, alpha, prob, c, d, claims = _run_gemm(*args, tail_clusters, device_layout) if tail_clusters: # The tail's schedulers claimed from the counter they share with the base's. @@ -211,19 +214,14 @@ def _run_combine(rows_per_expert, rows_alignment, mxfp8, backward): return a.float(), b.float(), alpha, prob, d, sum(rows_per_expert) -@pytest.mark.parametrize( - "backward,mxfp8,rows_alignment,rows_per_expert", - [ - (False, False, TILE, [2 * TILE, TILE, 0, 3 * TILE]), - (False, True, TILE, [2 * TILE, TILE, 0, 3 * TILE]), - (True, False, TILE, [2 * TILE, TILE, 0, 3 * TILE]), - (True, True, TILE, [2 * TILE, TILE, 0, 3 * TILE]), - ], -) -def test_combine_gemm_matches_reference(backward, mxfp8, rows_alignment, rows_per_expert): +@pytest.mark.parametrize("backward", [False, True]) +@pytest.mark.parametrize("mxfp8", [False, True]) +@requires_kernels +def test_combine_gemm_matches_reference(backward, mxfp8): """Grouped combine GEMM over padded slabs, per expert ``d = (a @ weight) * alpha * prob``, matches a float32 reference; rows past the last expert stay 0.""" - a, b, alpha, prob, d, used = _run_combine(rows_per_expert, rows_alignment, mxfp8, backward) + rows_per_expert = ROWS + a, b, alpha, prob, d, used = _run_combine(rows_per_expert, TILE, mxfp8, backward) ref = torch.zeros(a.shape[0], b.shape[2] if backward else b.shape[1], device=a.device) start = 0 for e, count in enumerate(rows_per_expert): @@ -289,15 +287,16 @@ def _run_wgrad(rows_per_expert, mxfp8, fp32_out, accumulate, n=512, kernel_class @pytest.mark.parametrize( "mxfp8,fp32_out,accumulate,rows_per_expert", [ - (False, False, False, [2 * TILE, TILE, 0, 3 * TILE]), # BF16 written - (False, True, False, [2 * TILE, TILE, 0, 3 * TILE]), # FP32 written - (False, False, True, [TILE, 0, 2 * TILE, TILE]), # BF16 accumulated - (True, False, False, [2 * TILE, TILE, 0, 3 * TILE]), # MXFP8 operands - (True, True, False, [2 * TILE, TILE, 0, 3 * TILE]), # MXFP8, FP32 written - (True, False, True, [TILE, 0, 2 * TILE, TILE]), # MXFP8, BF16 accumulated - (True, True, True, [TILE, 0, 2 * TILE, TILE]), # MXFP8, FP32 accumulated + (False, False, False, ROWS), # BF16 written + (False, True, False, ROWS), # FP32 written + (False, False, True, ROWS_SHORT), # BF16 accumulated + (True, False, False, ROWS), # MXFP8 operands + (True, True, False, ROWS), # MXFP8, FP32 written + (True, False, True, ROWS_SHORT), # MXFP8, BF16 accumulated + (True, True, True, ROWS_SHORT), # MXFP8, FP32 accumulated ], ) +@requires_kernels def test_wgrad_gemm_matches_reference(mxfp8, fp32_out, accumulate, rows_per_expert): """Grouped weight gradient matches a float32 reference; empty experts keep their input.""" grad, x, base, weight_grad = _run_wgrad(rows_per_expert, mxfp8, fp32_out, accumulate) @@ -313,11 +312,12 @@ def test_wgrad_gemm_matches_reference(mxfp8, fp32_out, accumulate, rows_per_expe assert err.max() <= tol +@requires_kernels def test_wgrad_gemm_reuse_matches_reference(): """An MXFP8 weight gradient written in BF16 over short experts, with three or more units of N tiles per M tile, keeps A across the N tiles of an expert (the A-reuse kernel) and matches a float32 reference.""" - rows_per_expert = [2 * TILE, TILE, 0, 3 * TILE] + rows_per_expert = ROWS reuse = wgrad_gemm._mxfp8_kernels()[2] grad, x, _, weight_grad = _run_wgrad(rows_per_expert, True, False, False, 3072, reuse) ref = torch.zeros_like(weight_grad) @@ -329,30 +329,7 @@ def test_wgrad_gemm_reuse_matches_reference(): assert err.max() <= 2.0**-8 -def _dispatch_gemm_fwd_args(tokens_shape=(8, 1024)): - """Arguments of ``tex.ep_dispatch_gemm_fwd`` with BF16 operands of consistent shapes, 4 local - experts and 2 tiles of receive rows; the call needs no EP group when it is rejected.""" - device = torch.device("cuda") - hidden, ffn, experts, rows = 1024, 1024, 4, 2 * TILE - # Offsets then the total, 16-byte aligned: the layout the dispatch writes. - offsets = torch.zeros(1 + experts + 1, dtype=torch.int64, device=device) - return ( - torch.empty(4096, dtype=torch.uint8, device=device), - torch.zeros(8, 2, dtype=torch.int64, device=device), - torch.zeros(tokens_shape, dtype=torch.bfloat16, device=device), - torch.ones(8, 2, dtype=torch.float32, device=device), - torch.zeros(experts, 2 * ffn, hidden, dtype=torch.bfloat16, device=device), - torch.zeros(rows, hidden, dtype=torch.bfloat16, device=device), - torch.zeros(rows, dtype=torch.float32, device=device), - torch.zeros(experts, dtype=torch.int64, device=device), - offsets[1:], - torch.zeros(rows, 2 * ffn, dtype=torch.bfloat16, device=device), - torch.zeros(rows, ffn, dtype=torch.bfloat16, device=device), - 2, - TILE, - ) - - +@requires_kernels def test_mxfp8_wgrad_rejects_dispatch_flags(): """An MXFP8 weight gradient waits on the GEMM before it, not on the dispatch flags.""" with pytest.raises(ValueError, match="takes no dispatch flags"): @@ -367,7 +344,175 @@ def test_mxfp8_wgrad_rejects_dispatch_flags(): ) -def test_dispatch_gemm_fwd_rejects_flat_tokens(): - """Tokens that are not [num_tokens, hidden] raise an error before any GEMM work.""" - with pytest.raises(RuntimeError, match="tokens must be"): - tex.ep_dispatch_gemm_fwd(*_dispatch_gemm_fwd_args(tokens_shape=(8 * 1024,))) +# CPU-only checks, run without NVTE_MOE_OVERLAP. + + +def _hide_packaged_library(monkeypatch): + def _missing_library(_): + raise FileNotFoundError + + monkeypatch.setattr( + transformer_engine.common, + "_get_shared_object_file", + _missing_library, + ) + + +def test_nccl_ep_library_found_from_home(monkeypatch, tmp_path): + home = tmp_path / "nccl_ep" + library_dir = home / "lib" + library_dir.mkdir(parents=True) + (library_dir / "libnccl_ep.so.0.1").touch() + + monkeypatch.setenv("NCCL_EP_HOME", str(home)) + _hide_packaged_library(monkeypatch) + monkeypatch.setattr(transformer_engine, "find_library", lambda _: None) + + assert transformer_engine._nccl_ep_library_installed() + + +def test_nccl_ep_library_found_in_package(monkeypatch, tmp_path): + library = tmp_path / "libnccl_ep.so" + library.touch() + + monkeypatch.delenv("NCCL_EP_HOME", raising=False) + monkeypatch.setattr( + transformer_engine.common, + "_get_shared_object_file", + lambda _: library, + ) + monkeypatch.setattr(transformer_engine, "find_library", lambda _: None) + + assert transformer_engine._nccl_ep_library_installed() + + +def test_nccl_ep_library_found_by_dynamic_loader(monkeypatch): + monkeypatch.delenv("NCCL_EP_HOME", raising=False) + _hide_packaged_library(monkeypatch) + monkeypatch.setattr(transformer_engine, "find_library", lambda _: "libnccl_ep.so.0") + + assert transformer_engine._nccl_ep_library_installed() + + +def test_nccl_ep_library_not_found(monkeypatch): + monkeypatch.delenv("NCCL_EP_HOME", raising=False) + _hide_packaged_library(monkeypatch) + monkeypatch.setattr(transformer_engine, "find_library", lambda _: None) + + assert not transformer_engine._nccl_ep_library_installed() + + +@pytest.mark.parametrize("value,expected", [(None, False), ("0", False), ("1", True)]) +def test_moe_overlap_toggle(monkeypatch, value, expected): + from transformer_engine.pytorch import ep + + monkeypatch.setattr(ep.torch.cuda, "is_available", lambda: True) + monkeypatch.setattr(ep, "get_device_compute_capability", lambda: (10, 0)) + monkeypatch.setattr(ep, "cutedsl_backend_built", lambda: True) + monkeypatch.setenv("NVTE_ENABLE_CUTEDSL_BACKEND", "1") + if value is None: + monkeypatch.delenv("NVTE_MOE_OVERLAP", raising=False) + else: + monkeypatch.setenv("NVTE_MOE_OVERLAP", value) + assert ep._moe_overlap_available() is expected + + +def _overlap_ep_config(**overrides): + from transformer_engine.pytorch.ep import EpConfig + + fields = dict( + top_k=2, + hidden_dim=1024, + num_local_experts=4, + max_tokens_per_rank=256, + recv_capacity_per_rank=1024, + ep_group=None, + alignment=256, + ) + fields.update(overrides) + return EpConfig(**fields) + + +@pytest.mark.parametrize( + "config_overrides,reason_overrides,expected", + [ + ({}, {}, None), + ({"zero_copy": True}, {}, "zero-copy"), + ({"recv_capacity_per_rank": 1152}, {}, "recv_capacity_per_rank must be a multiple of 256"), + ({"alignment": 128}, {}, "alignment"), + ({}, {"bias": True}, "biases are not supported"), + ({}, {"single_grouped_weight": False}, "single_grouped_weight=True"), + ({}, {"activation": "ScaledGeGLU"}, "SwiGLU"), + ({}, {"glu_interleave_size": 16}, "glu_interleave_size 32"), + ({}, {"glu_interleave_size": None}, "glu_interleave_size 32"), + ({}, {"recipe": MXFP8BlockScaling()}, None), + ( + { + "dispatch_fwd_quant_recipe": MXFP8BlockScaling(), + "combine_bwd_quant_recipe": MXFP8BlockScaling(), + }, + {"recipe": MXFP8BlockScaling()}, + None, + ), + ( + {"dispatch_fwd_quant_recipe": Float8CurrentScaling()}, + {"recipe": MXFP8BlockScaling()}, + "dispatch_fwd_quant_recipe", + ), + ( + {"combine_bwd_quant_recipe": Float8CurrentScaling()}, + {"recipe": MXFP8BlockScaling()}, + "combine_bwd_quant_recipe", + ), + ({}, {"recipe": DelayedScaling()}, "other than MXFP8BlockScaling"), + ({}, {"recipe": MXFP8BlockScaling(fp8_format=Format.HYBRID)}, "E4M3"), + ({"hidden_dim": 768}, {"recipe": MXFP8BlockScaling()}, "multiple of 512"), + ( + {"dispatch_fwd_quant_recipe": MXFP8BlockScaling()}, + {}, + "BF16 FusedMoE cannot use a quantized EP transport recipe", + ), + ], +) +def test_moe_overlap_unsupported_reason(monkeypatch, config_overrides, reason_overrides, expected): + """A window FusedMoE cannot run names the unsupported setting; a supported one has no reason.""" + import torch + from transformer_engine.pytorch.ops.fused import moe_overlap + + monkeypatch.setattr(moe_overlap.FusedMoE, "is_supported", classmethod(lambda cls: True)) + kwargs = dict(params_dtype=torch.bfloat16, glu_interleave_size=32, single_grouped_weight=True) + kwargs.update(reason_overrides) + reason = moe_overlap._moe_overlap_unsupported_reason( + _overlap_ep_config(**config_overrides), 1024, **kwargs + ) + if expected is None: + assert reason is None + else: + assert reason is not None and expected in reason + + +@pytest.mark.parametrize( + "config", + [ + {"sm_config": ("EpSmConfig", {"dispatch_fwd_num_sms": -1})}, + {"sm_config": ("EpSmConfig", {"combine_bwd_num_sms": -4})}, + {"overlap_config": ("EpOverlapConfig", {"combine_chunk_hidden": -256})}, + {"overlap_config": ("EpOverlapConfig", {"combine_push_last_chunk_sms": -1})}, + {"overlap_config": ("EpOverlapConfig", {"combine_reduce_last_chunk_sms": -1})}, + {"overlap_config": ("EpOverlapConfig", {"dispatch_chunk_tokens": -256})}, + ], +) +def test_ep_bootstrap_rejects_negative_budgets(config): + """Negative SM budgets and chunk sizes are rejected before the EP group is touched.""" + from transformer_engine.pytorch import ep + + kwargs = {name: getattr(ep, cls)(**fields) for name, (cls, fields) in config.items()} + with pytest.raises(ValueError, match="negative"): + ep.ep_bootstrap( + None, + num_experts=8, + max_tokens_per_rank=64, + hidden_dim=512, + num_topk=2, + **kwargs, + ) diff --git a/tests/pytorch/test_nccl_ep_discovery.py b/tests/pytorch/test_nccl_ep_discovery.py deleted file mode 100644 index 2ea66763cf6..00000000000 --- a/tests/pytorch/test_nccl_ep_discovery.py +++ /dev/null @@ -1,204 +0,0 @@ -# Copyright (c) 2022-2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. -# -# See LICENSE for license information. - -import pytest - -import transformer_engine -from transformer_engine.common.recipe import ( - DelayedScaling, - Float8CurrentScaling, - Format, - MXFP8BlockScaling, -) - - -def _hide_packaged_library(monkeypatch): - def _missing_library(_): - raise FileNotFoundError - - monkeypatch.setattr( - transformer_engine.common, - "_get_shared_object_file", - _missing_library, - ) - - -def test_nccl_ep_library_found_from_home(monkeypatch, tmp_path): - home = tmp_path / "nccl_ep" - library_dir = home / "lib" - library_dir.mkdir(parents=True) - (library_dir / "libnccl_ep.so.0.1").touch() - - monkeypatch.setenv("NCCL_EP_HOME", str(home)) - _hide_packaged_library(monkeypatch) - monkeypatch.setattr(transformer_engine, "find_library", lambda _: None) - - assert transformer_engine._nccl_ep_library_installed() - - -def test_nccl_ep_library_found_in_package(monkeypatch, tmp_path): - library = tmp_path / "libnccl_ep.so" - library.touch() - - monkeypatch.delenv("NCCL_EP_HOME", raising=False) - monkeypatch.setattr( - transformer_engine.common, - "_get_shared_object_file", - lambda _: library, - ) - monkeypatch.setattr(transformer_engine, "find_library", lambda _: None) - - assert transformer_engine._nccl_ep_library_installed() - - -def test_nccl_ep_library_found_by_dynamic_loader(monkeypatch): - monkeypatch.delenv("NCCL_EP_HOME", raising=False) - _hide_packaged_library(monkeypatch) - monkeypatch.setattr(transformer_engine, "find_library", lambda _: "libnccl_ep.so.0") - - assert transformer_engine._nccl_ep_library_installed() - - -def test_nccl_ep_library_not_found(monkeypatch): - monkeypatch.delenv("NCCL_EP_HOME", raising=False) - _hide_packaged_library(monkeypatch) - monkeypatch.setattr(transformer_engine, "find_library", lambda _: None) - - assert not transformer_engine._nccl_ep_library_installed() - - -@pytest.mark.parametrize("value,expected", [(None, False), ("0", False), ("1", True)]) -def test_moe_overlap_toggle(monkeypatch, value, expected): - from transformer_engine.pytorch import ep - - monkeypatch.setattr(ep.torch.cuda, "is_available", lambda: True) - monkeypatch.setattr(ep, "get_device_compute_capability", lambda: (10, 0)) - monkeypatch.setattr(ep, "cutedsl_backend_built", lambda: True) - monkeypatch.setenv("NVTE_ENABLE_CUTEDSL_BACKEND", "1") - if value is None: - monkeypatch.delenv("NVTE_MOE_OVERLAP", raising=False) - else: - monkeypatch.setenv("NVTE_MOE_OVERLAP", value) - assert ep._moe_overlap_available() is expected - - -def test_moe_overlap_rejects_unsupported_alignment(monkeypatch): - import torch - from transformer_engine.pytorch.ep import EpConfig - from transformer_engine.pytorch.ops.fused import moe_overlap - - monkeypatch.setattr(moe_overlap.FusedMoE, "is_supported", classmethod(lambda cls: True)) - config = EpConfig( - top_k=2, - hidden_dim=1024, - num_local_experts=4, - max_tokens_per_rank=256, - recv_capacity_per_rank=1024, - ep_group=None, - alignment=128, - ) - reason = moe_overlap._moe_overlap_unsupported_reason( - config, 1024, params_dtype=torch.bfloat16, glu_interleave_size=32 - ) - assert reason is not None and "alignment" in reason - - -def _overlap_ep_config(**overrides): - from transformer_engine.pytorch.ep import EpConfig - - fields = dict( - top_k=2, - hidden_dim=1024, - num_local_experts=4, - max_tokens_per_rank=256, - recv_capacity_per_rank=1024, - ep_group=None, - alignment=256, - ) - fields.update(overrides) - return EpConfig(**fields) - - -@pytest.mark.parametrize( - "config_overrides,reason_overrides,expected", - [ - ({}, {}, None), - ({"zero_copy": True}, {}, "zero-copy"), - ({"recv_capacity_per_rank": 1152}, {}, "recv_capacity_per_rank must be a multiple of 256"), - ({}, {"bias": True}, "biases are not supported"), - ({}, {"single_grouped_weight": False}, "single_grouped_weight=True"), - ({}, {"activation": "ScaledGeGLU"}, "SwiGLU"), - ({}, {"glu_interleave_size": 16}, "glu_interleave_size 32"), - ({}, {"glu_interleave_size": None}, "glu_interleave_size 32"), - ({}, {"recipe": MXFP8BlockScaling()}, None), - ( - { - "dispatch_fwd_quant_recipe": MXFP8BlockScaling(), - "combine_bwd_quant_recipe": MXFP8BlockScaling(), - }, - {"recipe": MXFP8BlockScaling()}, - None, - ), - ( - {"dispatch_fwd_quant_recipe": Float8CurrentScaling()}, - {"recipe": MXFP8BlockScaling()}, - "dispatch_fwd_quant_recipe", - ), - ( - {"combine_bwd_quant_recipe": Float8CurrentScaling()}, - {"recipe": MXFP8BlockScaling()}, - "combine_bwd_quant_recipe", - ), - ({}, {"recipe": DelayedScaling()}, "other than MXFP8BlockScaling"), - ({}, {"recipe": MXFP8BlockScaling(fp8_format=Format.HYBRID)}, "E4M3"), - ({"hidden_dim": 768}, {"recipe": MXFP8BlockScaling()}, "multiple of 512"), - ( - {"dispatch_fwd_quant_recipe": MXFP8BlockScaling()}, - {}, - "BF16 FusedMoE cannot use a quantized EP transport recipe", - ), - ], -) -def test_moe_overlap_unsupported_reason(monkeypatch, config_overrides, reason_overrides, expected): - """A window FusedMoE cannot run names the unsupported setting; a supported one has no reason.""" - import torch - from transformer_engine.pytorch.ops.fused import moe_overlap - - monkeypatch.setattr(moe_overlap.FusedMoE, "is_supported", classmethod(lambda cls: True)) - kwargs = dict(params_dtype=torch.bfloat16, glu_interleave_size=32, single_grouped_weight=True) - kwargs.update(reason_overrides) - reason = moe_overlap._moe_overlap_unsupported_reason( - _overlap_ep_config(**config_overrides), 1024, **kwargs - ) - if expected is None: - assert reason is None - else: - assert reason is not None and expected in reason - - -@pytest.mark.parametrize( - "config", - [ - {"sm_config": ("EpSmConfig", {"dispatch_fwd_num_sms": -1})}, - {"sm_config": ("EpSmConfig", {"combine_bwd_num_sms": -4})}, - {"overlap_config": ("EpOverlapConfig", {"combine_chunk_hidden": -256})}, - {"overlap_config": ("EpOverlapConfig", {"combine_push_last_chunk_sms": -1})}, - {"overlap_config": ("EpOverlapConfig", {"combine_reduce_last_chunk_sms": -1})}, - {"overlap_config": ("EpOverlapConfig", {"dispatch_chunk_tokens": -256})}, - ], -) -def test_ep_bootstrap_rejects_negative_budgets(config): - """Negative SM budgets and chunk sizes are rejected before the EP group is touched.""" - from transformer_engine.pytorch import ep - - kwargs = {name: getattr(ep, cls)(**fields) for name, (cls, fields) in config.items()} - with pytest.raises(ValueError, match="negative"): - ep.ep_bootstrap( - None, - num_experts=8, - max_tokens_per_rank=64, - hidden_dim=512, - num_topk=2, - **kwargs, - ) From e54569eca4218f870c6b68e8dadeb9cd32ee944e Mon Sep 17 00:00:00 2001 From: Phuong Nguyen Date: Thu, 3 Dec 2026 17:59:19 -0800 Subject: [PATCH 62/67] [PyTorch] Clarify the EP overlap docs and CuTeDSL docstrings and trim the FusedMoE comments Signed-off-by: Phuong Nguyen --- docs/api/pytorch.rst | 8 +++- .../pytorch/ep/bench/bench_moe_overlap.py | 16 +++---- .../common/CuTeDSL/ep_gemm/combine_gemm.py | 31 +++++++------ .../common/CuTeDSL/ep_gemm/dispatch_gemm.py | 45 ++++++++++--------- .../common/CuTeDSL/ep_gemm/wgrad_gemm.py | 20 +++++---- .../pytorch/ops/fused/moe_overlap.py | 43 ++++++++---------- 6 files changed, 86 insertions(+), 77 deletions(-) diff --git a/docs/api/pytorch.rst b/docs/api/pytorch.rst index 491b5cc3755..168ed6cd069 100644 --- a/docs/api/pytorch.rst +++ b/docs/api/pytorch.rst @@ -152,8 +152,12 @@ an ``EpBuffer``. A buffer holds the routing state of one call until its backward several calls in flight (for example pipeline microbatches) each need their own ``EpBuffer`` and op instance. The guide shows how to connect the per-expert counts and routing weights through the sequence's extra-tensor channels. With the overlap enabled (``NVTE_MOE_OVERLAP=1``), a dispatch, -grouped MLP and combine sequence runs as one fused op, and a setting the fused op does not support -raises an error that names the reason. +grouped MLP and combine sequence runs as one fused op. A sequence that does not meet its +requirements raises an error that names the reason, instead of running unfused. The requirements +include BF16 weights and payload, packed weights without bias, ``ScaledSwiGLU`` with +``glu_interleave_size=32``, an EP alignment of 256, no recipe or ``MXFP8BlockScaling``, no delayed +weight gradient computation, and one shared ``EpConfig`` and ``EpBuffer``. See ``FusedMoE`` for the +full list. .. autoapiclass:: transformer_engine.pytorch.ops.MoeDispatch diff --git a/examples/pytorch/ep/bench/bench_moe_overlap.py b/examples/pytorch/ep/bench/bench_moe_overlap.py index e2f7b381e3c..67cabf6c389 100644 --- a/examples/pytorch/ep/bench/bench_moe_overlap.py +++ b/examples/pytorch/ep/bench/bench_moe_overlap.py @@ -5,12 +5,12 @@ """Timing harness for the overlapped MoE op (FusedMoE), forward and backward, in eager and CUDA-graph modes. Launch with torchrun, one process per GPU: - torchrun --standalone --nproc-per-node=4 bench_moe_overlap.py --precision bf16 + NVTE_ENABLE_CUTEDSL_BACKEND=1 NVTE_MOE_OVERLAP=1 \\ + torchrun --standalone --nproc-per-node=4 bench_moe_overlap.py --precision bf16 The op fuses an MoE MLP (dispatch, GroupedLinear, ScaledSwiGLU, GroupedLinear, combine) so the -NCCL EP dispatch and combine overlap the expert GEMMs. Requires SM 10.0, 10.3 or 10.7, an EP group -within one NVLink domain, NVTE_ENABLE_CUTEDSL_BACKEND=1 and NVTE_MOE_OVERLAP=1. The defaults match -the DeepSeek-V3 EP4 shape. +NCCL EP dispatch and combine overlap the expert GEMMs. Requires SM 10.0, 10.3 or 10.7 and an EP +group within one NVLink domain. The defaults match the DeepSeek-V3 EP4 shape. """ import argparse @@ -24,6 +24,7 @@ from transformer_engine.pytorch import ops as te_ops from transformer_engine.common.recipe import MXFP8BlockScaling from transformer_engine.pytorch.ep import EpBuffer, EpConfig, EpSmConfig, ep_bootstrap, ep_finalize +from transformer_engine.pytorch.ops.fused import moe_overlap def _parse_args(): @@ -145,11 +146,10 @@ def _autocast(recipe): def _assert_fused(args, recipe, num_experts, device, model): - from transformer_engine.pytorch.ops.fused import moe_overlap - - topk_idx, x, topk_w, _ = _inputs(args, num_experts, device) + topk_idx, x, topk_w, grad_out = _inputs(args, num_experts, device) with _autocast(recipe): - model(x, topk_idx, topk_w, topk_idx) + y = model(x, topk_idx, topk_w, topk_idx) + y.backward(grad_out) torch.cuda.synchronize() fused = any( isinstance(op, moe_overlap.FusedMoE) diff --git a/transformer_engine/common/CuTeDSL/ep_gemm/combine_gemm.py b/transformer_engine/common/CuTeDSL/ep_gemm/combine_gemm.py index 633b33265c8..63be9387145 100644 --- a/transformer_engine/common/CuTeDSL/ep_gemm/combine_gemm.py +++ b/transformer_engine/common/CuTeDSL/ep_gemm/combine_gemm.py @@ -2,19 +2,24 @@ # # See LICENSE for license information. -"""Grouped GEMM that publishes its output to the EP combine (BF16 or MXFP8, SM 10.0, 10.3 and -10.7). - - mode a b (weight) d - forward [rows,k] [E,n,k] [rows,n] BF16, scaled per row by prob - backward [rows,k] [E,k,n] (the forward weight) [rows,n] BF16, scaled per row by prob - -BF16 operands, or E4M3 with GEMM-swizzled E8M0 scales ``sfa`` and ``sfb`` for MXFP8 (the backward -reads the columnwise forward weight). Common operands: ``expert_row_ends`` [E] int64, -``alpha`` [E] FP32, ``prob`` [rows] FP32, ``workspace`` uint8, stream. -``signal[u] = u`` once columns ``[u * n_chunk, (u + 1) * n_chunk)`` of ``d`` are final; the caller -sets ``signal[]`` to -1 before each launch. With ``n_chunk`` 0 the GEMM publishes nothing and runs -in the stock tile order; its workspace ends in one flag word the caller sets. +"""Grouped GEMM that publishes its output to the EP combine (SM 10.0, 10.3 and 10.7). + + mode a b (weight) d + forward [rows,k] [E,n,k] [rows,n] BF16, scaled per row by prob + backward [rows,k] [E,k,n] (the forward weight) [rows,n] BF16, scaled per row by prob + +Operands: +- BF16: ``a`` and ``b`` as above. +- MXFP8: ``a`` and ``b`` in E4M3 with GEMM-swizzled E8M0 scales ``sfa`` and ``sfb``; the backward + reads the columnwise forward weight. +- Both: ``expert_row_ends`` [E] int64, ``alpha`` [E] FP32, ``prob`` [rows] FP32, ``workspace`` + uint8, stream. + +Signals: +- ``signal[u] = u`` once columns ``[u * n_chunk, (u + 1) * n_chunk)`` of ``d`` are final; the + caller sets ``signal[]`` to -1 before each launch. +- With ``n_chunk`` 0 the GEMM publishes nothing and runs in the stock tile order; its workspace + ends in one flag word the caller sets. """ import functools diff --git a/transformer_engine/common/CuTeDSL/ep_gemm/dispatch_gemm.py b/transformer_engine/common/CuTeDSL/ep_gemm/dispatch_gemm.py index ae0468c7408..78eeaa6b943 100644 --- a/transformer_engine/common/CuTeDSL/ep_gemm/dispatch_gemm.py +++ b/transformer_engine/common/CuTeDSL/ep_gemm/dispatch_gemm.py @@ -2,31 +2,34 @@ # # See LICENSE for license information. -"""Signal-aware grouped GEMMs that follow an EP dispatch (BF16 or MXFP8, SM 10.0, 10.3 and 10.7). +"""Signal-aware grouped GEMMs that follow an EP dispatch (SM 10.0, 10.3 and 10.7). -An M tile starts once each of its slots s has ``signal[s] == s``. Operands (rows = receive rows): +An M tile starts once each of its slots s has ``signal[s] == s``. Rows = receive rows. - mode a b (weight) outputs - fwd BF16 [rows,k] [E,n,k] c [rows,n]; d [rows,n/2] = silu(gate)*up*prob - bwd BF16 [rows,k] [E,k,n] d [rows,2n] = grad of c; dprob [rows] FP32 (added to) - fwd MXFP8 E4M3 E4M3 c BF16 [rows,n]; d E4M3 [rows,n/2] + swizzled sfd - bwd MXFP8 E4M3 columnwise E4M3 d rowwise + d_col columnwise, h [rows,n] columnwise + mode a b (weight) outputs + forward [rows,k] [E,n,k] c [rows,n]; d [rows,n/2] = silu(gate) * up * prob + backward [rows,k] [E,k,n] d [rows,2n] = grad of c; dprob [rows] FP32, added to Forward is FC1 (gate and up alternate in 32-column blocks of ``c``). Backward is the FC2 data -gradient with the SwiGLU backward in the epilogue; its ``c`` is the FC1 output [rows, 2n]. -Common operands: ``expert_row_ends`` [E] int64, ``alpha`` [E] -FP32, ``prob`` [rows] FP32, ``workspace`` uint8, stream. With ``device_layout`` the forward also -waits for the dispatch to write ``expert_row_ends`` and the entry before it (expert 0's offset), -both -1 beforehand. The kernel waits until they are at least 0. - -MXFP8 scales: ``sfa`` is compact (as the dispatch delivers it) and ``sfb`` swizzled. The forward -takes no ``prob`` and a ``norm_const`` [1] FP32 of 1. The backward writes ``sfd_row`` (swizzled), -``sfd_col`` and ``sfh_col`` (swizzled per expert). Without ``d_col`` or ``h`` in the configuration -the backward takes None for ``d_col`` and ``sfd_col``, or ``h`` and ``sfh_col``, and does not write -them. - -The routing-weight gradient dprob is added to atomically, or with ``deterministic`` written to one -FP32 slot per row and N tile, ``dprob`` then being [rows * dprob_n_slots(n)] to sum in a fixed order. +gradient with the SwiGLU backward in the epilogue; its ``c`` is the FC1 output [rows,2n]. + +Operands: +- BF16: as in the table. +- MXFP8: ``a`` and ``b`` in E4M3, the backward ``b`` columnwise. ``sfa`` is compact (as the + dispatch delivers it) and ``sfb`` swizzled. + - forward: ``c`` BF16, ``d`` E4M3 with swizzled ``sfd``; takes no ``prob`` and a + ``norm_const`` [1] FP32 of 1. + - backward: ``d`` rowwise (``sfd_row`` swizzled) and ``d_col`` columnwise (``sfd_col``), and + ``h`` [rows,n] columnwise (``sfh_col`` swizzled per expert). Without ``d_col`` or ``h`` in the + configuration, pass None for it and its scale; it is not written. +- Both: ``expert_row_ends`` [E] int64, ``alpha`` [E] FP32, ``prob`` [rows] FP32, ``workspace`` + uint8, stream. + +Options: +- ``device_layout``: the forward also waits for the dispatch to write ``expert_row_ends`` and the + entry before it (expert 0's offset), both -1 beforehand; the kernel waits until they are >= 0. +- ``deterministic``: ``dprob`` is added to atomically by default; with this it is written to one + FP32 slot per row and N tile, [rows * dprob_n_slots(n)], to sum in a fixed order. """ import functools diff --git a/transformer_engine/common/CuTeDSL/ep_gemm/wgrad_gemm.py b/transformer_engine/common/CuTeDSL/ep_gemm/wgrad_gemm.py index 479cc85cecd..02d31a44276 100644 --- a/transformer_engine/common/CuTeDSL/ep_gemm/wgrad_gemm.py +++ b/transformer_engine/common/CuTeDSL/ep_gemm/wgrad_gemm.py @@ -4,14 +4,18 @@ """Grouped weight gradient chained into the overlapped backward (SM 10.0, 10.3 and 10.7). -``weight_grad[e] = grad[rows of e]^T x[rows of e]`` per expert: ``grad`` [rows, m] and ``x`` -[rows, n] BF16, or MXFP8 columnwise data with their GEMM-swizzled columnwise scales, -``weight_grad`` [experts, m, n] BF16 or FP32, written or added to. Operands: ``expert_row_ends`` -[experts] int64, ``workspace`` uint8, stream. - -Each launch is a persistent grid that claims output tiles from an atomic counter in ``workspace``, -so launches sharing one workspace split the tiles across SMs. It is a programmatic dependent of the -kernel before it and lets the kernel behind it start early. +``weight_grad[e] = grad[rows of e]^T x[rows of e]`` per expert, with ``grad`` [rows,m], ``x`` +[rows,n] and ``weight_grad`` [experts,m,n] written or added to. + +Operands: +- BF16: ``grad`` and ``x`` BF16. +- MXFP8: ``grad`` and ``x`` columnwise E4M3 with GEMM-swizzled columnwise scales. +- Both: ``weight_grad`` BF16 or FP32, ``expert_row_ends`` [experts] int64, ``workspace`` uint8, + stream. + +Schedule: each launch is a persistent grid that claims output tiles from an atomic counter in +``workspace``, so launches sharing one workspace split the tiles across SMs. It is a programmatic +dependent of the kernel before it and lets the kernel behind it start early. """ import functools diff --git a/transformer_engine/pytorch/ops/fused/moe_overlap.py b/transformer_engine/pytorch/ops/fused/moe_overlap.py index ad4e2a3f87c..dedb5036444 100644 --- a/transformer_engine/pytorch/ops/fused/moe_overlap.py +++ b/transformer_engine/pytorch/ops/fused/moe_overlap.py @@ -85,16 +85,14 @@ class FusedMoE(FusedOperation): Notes: - With the overlap enabled (``NVTE_MOE_OVERLAP=1``), a ``Sequential`` of these ops that does not meet the requirements raises an error naming the reason, instead of running unfused. - - Each GEMM allocates a small uint8 workspace for its flags and state in the binding, freed - after the call; the calls of an EP group must run on one CUDA stream. + - The calls of an EP group must run on one CUDA stream. - With a fixed receive capacity the op can be captured in a CUDA graph after a warmup call; - with eager receive sizing (no ``recv_capacity_per_rank``) the host is synchronized and it + with eager receive sizing (no ``recv_capacity_per_rank``) it synchronizes the host and cannot be captured. - - Without a recipe the routing weights are applied in the activation; under + - Without a recipe the routing weights are applied in the activation. Under ``MXFP8BlockScaling`` the GEMMs and the EP transport run in MXFP8 (an unset transport - recipe of the config defaults to MXFP8; another recipe is not supported yet) and the - routing weights are applied to the second GEMM's output. Either way their gradient goes to the dispatch's - ``topk_weights``. + recipe defaults to MXFP8) and the routing weights scale the second GEMM's output. Their + gradient goes to the dispatch's ``topk_weights`` either way. - The weights are prepared for the GEMMs (quantized to MXFP8) at each forward. """ @@ -122,8 +120,7 @@ def __init__( self._mxfp8 = recipe is not None self._operands = _Mxfp8Operands() if self._mxfp8 else _Bf16Operands() self._weight_quantizers = {1: {}, 3: {}} - # The dispatch and combine share one EpBuffer (see _unsupported_reason); FusedMoE reads it - # from self.basic_ops[0].buffer at each forward. + # The dispatch and combine share one EpBuffer; it is read from basic_ops[0] at each forward. def fuser_forward( self, @@ -171,8 +168,8 @@ def fuser_forward( topk_idx = _require_contiguous(topk_idx, "topk_idx") topk_weights = _require_contiguous(topk_weights, "topk_weights") tokens_per_expert = buffer.tokens_per_expert - # The int64 expert layout the GEMMs read: expert 0's start (0), then each expert's padded - # row end. Front-pad one element so the row ends (expert_token_offsets[1:]) start 16-byte + # Int64 expert layout the GEMMs read: expert 0's start (0), then each expert's padded row + # end. One element of front padding keeps the row ends (expert_token_offsets[1:]) 16-byte # aligned. expert_token_offsets = torch.empty( buffer.num_local_experts + 2, dtype=torch.int64, device=device @@ -183,9 +180,8 @@ def fuser_forward( "Eager FusedMoE reads the recv total on the host and cannot be captured in a" " CUDA graph; bootstrap EP with recv_capacity_per_rank." ) - # The prepare writes the recv total to pinned host memory, and the expert starts. - # Launch it first and mark its completion with an event, so the weight and input - # preparation below overlaps it; only the total read waits. + # The prepare writes the recv total to pinned host memory. Launch it first so the + # weight and input preparation below overlaps it; only the total read waits. tex.ep_prepare( buffer.handle_mem, topk_idx, tokens_per_expert, buffer.top_k, buffer.alignment, buffer.total_recv_tokens, expert_token_offsets[:-1], @@ -680,8 +676,7 @@ def _bf16_grad_output(grad_output) -> torch.Tensor: class _CallWgrad(dict): """Keyword arguments of a weight gradient computed inside a backward call, passed as - ``**wgrad``. Its wgrad factory only records the input and the output; the call runs the kernel - later, so distributed weights, which FusedMoE rejects, do not fit.""" + ``**wgrad``. Its wgrad factory only records the operands; the call runs the kernel.""" def gemm_fn_factory(self, num_groups: int, weight_shape) -> Callable: """Wgrad factory that records the operands of a weight of shape ``weight_shape``.""" @@ -764,12 +759,11 @@ def _with_columnwise_data(recv_tokens, first_dims, expert_token_offsets, operand def _mxfp8_weight_operands( fc_op: GroupedLinear, num_groups: int, columnwise: bool, quantizer_cache: dict ) -> _MxFp8WeightOperands: - """GEMM operands of the weight quantized to MXFP8, with the columnwise ones when asked; data - is flat; the bindings shape it as [num_groups, out_features, in_features]. - BF16 weights are quantized with GEMM-swizzled scales; the scales of MXFP8 weight parameters - are swizzled into a copy. Each direction is swizzled along its own scaling axis. - ``quantizer_cache`` keeps the quantizer copy of BF16 weights per direction; a new quantizer of - the op, as after a recipe change, replaces it.""" + """MXFP8 GEMM operands of the weight, with the columnwise ones when asked; data is flat and the + bindings shape it as [num_groups, out_features, in_features]. BF16 weights are quantized with + GEMM-swizzled scales; the scales of MXFP8 weight parameters are swizzled into a copy. + ``quantizer_cache`` keeps the quantizer copy of BF16 weights per direction until the op's + quantizer changes, as after a recipe change.""" weight = fc_op.weight if weight.quantizer is not None: # Only add usages, never drop: later weight updates keep what this op needs. @@ -840,9 +834,8 @@ def _moe_overlap_unsupported_reason( ) -> Optional[str]: """Why a ``Sequential`` of ``MoeDispatch``, ``GroupedLinear``, ``ScaledSwiGLU``, ``GroupedLinear`` and ``MoeCombine`` built with these settings does not run as one - ``FusedMoE``, or ``None`` when it does. The reason names an unsupported setting. It only - queries the device and the static settings; those that can change between calls are checked - when the op runs. + ``FusedMoE``, or ``None`` when it does. It checks the device and the static settings; those + that can change between calls are checked when the op runs. Parameters ---------- From 58497b24eb8e7cdff7905ddfe799d49485dba7d4 Mon Sep 17 00:00:00 2001 From: Phuong Nguyen Date: Thu, 3 Dec 2026 17:59:19 -0800 Subject: [PATCH 63/67] [Common][PyTorch] Shorten the EP backend docs and pass the EP SM and overlap budgets to ep_initialize as arrays Signed-off-by: Phuong Nguyen --- .../cast/mxfp8/requantize_mxfp8_cutedsl.cuh | 7 +- transformer_engine/common/ep/ep_backend.cpp | 14 +-- transformer_engine/common/ep/ep_backend.h | 52 ++++------ transformer_engine/common/ep/ep_gemm_api.cpp | 98 ++++++++----------- transformer_engine/common/ep/ep_gemm_config.h | 5 +- .../common/ep/ep_overlap_workspace.cu | 2 + .../include/transformer_engine/ep_gemm.h | 6 +- transformer_engine/pytorch/csrc/extensions.h | 8 +- .../pytorch/csrc/extensions/ep.cpp | 78 ++++++--------- transformer_engine/pytorch/ep.py | 20 ++-- 10 files changed, 119 insertions(+), 171 deletions(-) diff --git a/transformer_engine/common/cast/mxfp8/requantize_mxfp8_cutedsl.cuh b/transformer_engine/common/cast/mxfp8/requantize_mxfp8_cutedsl.cuh index 76067707464..ac0750772f8 100644 --- a/transformer_engine/common/cast/mxfp8/requantize_mxfp8_cutedsl.cuh +++ b/transformer_engine/common/cast/mxfp8/requantize_mxfp8_cutedsl.cuh @@ -81,9 +81,10 @@ inline bool mxfp8_requantize_cutedsl(const GroupedTensor &input, GroupedTensor * const size_t hidden = input.logical_shape.data[1]; const size_t groups = input.num_tensors; const bool return_dequantized = dequantized != nullptr && dequantized->data.dptr != nullptr; - // Varying first dims without BF16 output use the warp-tile kernel, which loads scales as words. - // force_warp_tile selects it for unequal expert slabs given by element offsets, which the - // uniform-slab kernel does not take. + // Varying first dims without BF16 output use the warp-tile kernel. force_warp_tile is for MoE + // overlap: its expert slabs are unequal and given only by element offsets, but the tensor is + // declared with equal shapes, so the shape test would pick the uniform-slab kernel, which cannot + // read them. const bool warp_tile = force_warp_tile || (!input.all_same_shape() && !return_dequantized); if (rows == 0 || hidden == 0 || rows % 128 || hidden % 128 || (!warp_tile && hidden >= 512 && hidden % 512)) diff --git a/transformer_engine/common/ep/ep_backend.cpp b/transformer_engine/common/ep/ep_backend.cpp index 410b3dfddb0..01a13297de7 100644 --- a/transformer_engine/common/ep/ep_backend.cpp +++ b/transformer_engine/common/ep/ep_backend.cpp @@ -103,9 +103,8 @@ inline ncclEpTensor_t make_nccl_ep_tensor(const NVTETensor t, NVTEShape& shape_o return desc; } -// NCCL EP first published the overlap completion signal in 0.3.0. An older runtime loaded through -// NCCL_EP_HOME ignores the signal output field and returns success without ever raising the flags, -// leaving the overlapped GEMM waiting forever. Reject a signaled op on such a runtime up front. +// A runtime older than NCCL EP 0.3.0 ignores the signal and never raises the flags, so the +// overlapped GEMM would wait forever. Reject a signaled op on such a runtime up front. void require_signal_capable(const char* call) { constexpr int kMinSignalVersion = 300; // NCCL EP 0.3.0 const int version = nccl_ep::runtime_version(); @@ -115,15 +114,13 @@ void require_signal_capable(const char* call) { "; it needs NCCL EP >= 0.3.0. Use a compatible runtime or disable the overlap."); } -// Signal descriptor of a dispatch or combine call; attach() returns the NCCL EP signal to wire into -// the call, or nullptr when no signal is given. +// attach() returns the NCCL EP signal to wire into a call, or nullptr when no signal is given. struct SignalDesc { NVTEShape shape; ncclEpTensor_t desc = NCCL_EP_TENSOR_INIT; ncclEpSignal_t sig = NCCL_EP_SIGNAL_INIT; - // A row tile spans `granularity` rows and every column (dispatch), else every row and - // `granularity` hidden columns (combine). + // Tiles are `granularity` rows (dispatch) or hidden columns (combine). ncclEpSignal_t* attach(const EpSignal* signal, bool row_tiles, const char* call) { if (signal == nullptr) { return nullptr; @@ -142,8 +139,7 @@ struct SignalDesc { } }; -// NCCL EP rejects a signaled call it cannot serve with ncclInvalidUsage, e.g. on a group of more -// than one LSA team (NVLink domain). +// NCCL EP returns ncclInvalidUsage for a signaled call on a group of more than one LSA team. void check_signaled_call(ncclResult_t status, bool signaled, const char* call) { NVTE_CHECK(!signaled || status != ncclInvalidUsage, "NCCL EP rejected the signaled ", call, " (invalid usage): the overlapped EP ops need the EP group within one NVLink domain " diff --git a/transformer_engine/common/ep/ep_backend.h b/transformer_engine/common/ep/ep_backend.h index 7449bfbe2be..0e647477c53 100644 --- a/transformer_engine/common/ep/ep_backend.h +++ b/transformer_engine/common/ep/ep_backend.h @@ -26,10 +26,9 @@ namespace transformer_engine { namespace ep { -/*! \brief Readiness flags of an overlapped op: 1D int32, one flag per `granularity` units of the - * signaled tensor (rows of recv_tokens for a dispatch, hidden columns for a combine). */ +/*! \brief Readiness flags of an overlapped op: 1D int32, one flag per `granularity` rows (dispatch) + * or hidden columns (combine). Reset to -1; slot s is set to s once its unit is ready. */ struct EpSignal { - // Reset to -1; slot s is set to s once its unit is ready (consumer waits for ready[s] == s). NVTETensor ready; size_t granularity; }; @@ -40,28 +39,23 @@ class EPBackend { /*! \brief Access the current device's backend. Aborts if not initialized. */ static EPBackend& get(); - /*! \brief Bootstrap from an existing EP sub-communicator. - * ep_comm is borrowed; the caller keeps it alive until shutdown() returns - * and must span exactly config.ep_size ranks. - * Initializes the backend on the current CUDA device. - */ + /*! \brief Bootstrap on the current CUDA device. ep_comm is borrowed, must span config.ep_size + * ranks and must outlive shutdown(). */ static void initialize(ncclComm_t ep_comm, NVTEEpGroupConfig config); /*! \brief Tear down all local backends. Idempotent. Does not destroy ep_comm_. */ static void shutdown(); - // Host-only: report handle_mem byte size for layer_cfg. - // Returns the maximum across initialized local devices. + // Host-only: handle_mem byte size for layer_cfg, the maximum across initialized local devices. static size_t handle_mem_size(NVTEEpLayerConfig layer_cfg); - // Updates handle_mem with this step's routing and writes the recv counts. NCCL EP uses count - // mode; the scan path is used only when the transport is IB. + // Updates handle_mem with this step's routing and writes the recv counts. void prepare(NVTETensor handle_mem, const NVTETensor topk_idx, NVTETensor recv_tokens_per_expert, NVTETensor total_recv_tokens_per_rank, NVTETensor expert_offsets, NVTEEpLayerConfig layer_cfg, cudaStream_t stream); - // Per-step ops below require a prior prepare(); layer_cfg rebinds the handle from handle_mem. - // A non-null dispatch_signal publishes one flag per signal granularity rows of recv_tokens. + // Per-step ops below require a prior prepare(). A non-null dispatch_signal publishes one flag + // per signal granularity rows of recv_tokens. void dispatch(NVTETensor handle_mem, const NVTETensor topk_idx, const NVTETensor tokens, const NVTECommWindow& tokens_win, const NVTETensor topk_weights, const NVTECommWindow& topk_weights_win, NVTETensor recv_tokens, @@ -69,12 +63,9 @@ class EPBackend { const NVTECommWindow& recv_topk_weights_win, const EpSignal* dispatch_signal, const NVTEEpLayerConfig& layer_cfg, cudaStream_t stream); - // Fused prepare + dispatch: seeds routing then dispatches in one call. Routing writes the - // per-expert recv counts to recv_tokens_per_expert and the scalar pre-drop per-rank recv total - // to total_recv_tokens_per_rank (nullable); the dispatch then reads the counts from the handle. - // expert_token_offsets (nullable): the padded per-expert token offsets; NCCL EP requires them, - // the counts and the total, when given, to share one integer type. - // dispatch_signal: as for dispatch(). + // Prepare and dispatch in one call. Writes the per-expert recv counts to recv_tokens_per_expert + // and the pre-drop per-rank total to total_recv_tokens_per_rank (nullable). expert_token_offsets + // (nullable) gets the padded offsets; the counts, total and offsets share one integer type. void prepare_and_dispatch(NVTETensor handle_mem, const NVTETensor topk_idx, const NVTETensor tokens, const NVTECommWindow& tokens_win, const NVTETensor topk_weights, const NVTECommWindow& topk_weights_win, @@ -86,22 +77,21 @@ class EPBackend { const EpSignal* dispatch_signal, NVTEEpLayerConfig layer_cfg, cudaStream_t stream); - // A non-null combine_signal makes the combine start on column chunks as the producer of - // expert_out publishes them. + // A non-null combine_signal starts the combine on column chunks as expert_out's producer + // publishes them. void combine(NVTETensor handle_mem, const NVTETensor expert_out, const NVTECommWindow& expert_out_win, NVTETensor result, const EpSignal* combine_signal, const NVTEEpLayerConfig& layer_cfg, cudaStream_t stream); // g_recv_topk_weights: 1D [recv_capacity] f32; grad_topk_weights: 2D [T, top_k] f32. - // combine_signal: as for combine(). void dispatch_bwd(NVTETensor handle_mem, const NVTETensor grad, const NVTECommWindow& grad_win, const NVTETensor g_recv_topk_weights, const NVTECommWindow& g_recv_topk_weights_win, NVTETensor grad_tokens, NVTETensor grad_topk_weights, const EpSignal* combine_signal, const NVTEEpLayerConfig& layer_cfg, cudaStream_t stream); - // dispatch_signal: as for dispatch(), over the rows of grad_expert_out. + // dispatch_signal covers the rows of grad_expert_out. void combine_bwd(NVTETensor handle_mem, const NVTETensor grad, const NVTECommWindow& grad_win, NVTETensor grad_expert_out, const NVTECommWindow& grad_expert_out_win, const EpSignal* dispatch_signal, const NVTEEpLayerConfig& layer_cfg, @@ -116,7 +106,6 @@ class EPBackend { EPBackend(const EPBackend&) = delete; EPBackend& operator=(const EPBackend&) = delete; - // ep_comm is borrowed; caller retains ownership across the backend lifetime. void init(ncclComm_t ep_comm, NVTEEpGroupConfig config); // Caller must hold mutex_. @@ -125,8 +114,7 @@ class EPBackend { static EPBackend& instance(int device); static void validate_config(const NVTEEpGroupConfig& config); - // Open a fresh ncclEpHandle over handle_mem. num_topk=-1 for paths - // that don't carry per-token weights. + // Open a fresh ncclEpHandle over handle_mem; num_topk=-1 when no per-token weights are carried. ncclEpHandle_t open_handle(void* handle_mem, size_t handle_mem_size, int num_topk, size_t dispatch_output_per_expert_alignment); @@ -136,16 +124,12 @@ class EPBackend { std::atomic initialized_{false}; std::mutex mutex_; - // Bind a fresh handle to handle_mem's already-prepared contents via ncclEpImportHandle. - // The caller owns the returned handle. Caller must hold mutex_. + // Bind a new handle to handle_mem's prepared contents; the caller owns it. Holds mutex_. ncclEpHandle_t import_handle_locked(void* handle_mem, size_t handle_mem_size, int num_tokens, NVTEEpLayerConfig layer_cfg); - // Build the dispatch in/out structs and issue ncclEpDispatch on the given - // handle. When recv_tokens_per_expert != nullptr (count mode), it is wired to - // layout_info.expert_counters so the dispatch writes per-expert recv counts; likewise - // expert_token_offsets to layout_info.expert_offsets. - // Caller must hold mutex_. + // Issue ncclEpDispatch on handle; recv_tokens_per_expert and expert_token_offsets, when given, + // receive the counts and offsets. Caller must hold mutex_. void issue_dispatch_locked(ncclEpHandle_t handle, const NVTETensor topk_idx, const NVTETensor tokens, const NVTECommWindow& tokens_win, const NVTETensor topk_weights, const NVTECommWindow& topk_weights_win, diff --git a/transformer_engine/common/ep/ep_gemm_api.cpp b/transformer_engine/common/ep/ep_gemm_api.cpp index 3199b72973b..e507a315439 100644 --- a/transformer_engine/common/ep/ep_gemm_api.cpp +++ b/transformer_engine/common/ep/ep_gemm_api.cpp @@ -58,9 +58,8 @@ size_t align_up(size_t value) { return (value + kWorkspaceAlign - 1) / kWorkspaceAlign * kWorkspaceAlign; } -// Hidden columns per combine flag. configured overrides the default of one NCCL EP push tile -// (1024 bfloat16 elements, or the row when shorter); the last chunk of a row the width does not -// divide is the shorter remainder. +// Hidden columns per combine flag: configured, else one NCCL EP push tile (1024 bfloat16 elements +// or the row when shorter). The last chunk of a row is the shorter remainder. size_t combine_chunk(size_t n, int configured) { NVTE_CHECK(n % kTileN == 0, "output columns (", n, ") must be a multiple of ", kTileN); if (configured <= 0) return std::min(n, 1024); @@ -98,8 +97,7 @@ EpGemmContext make_context(const NVTEEpLayerConfig* layer_cfg, int NVTEEpSmConfi const NVTEEpGroupConfig& group = backend.group_config(); NVTE_CHECK(group.num_comm_sms > 0, "the overlapped ops need an explicit num_comm_sms"); NVTE_CHECK(!group.zero_copy, "the overlapped ops do not support zero-copy"); - // The GEMMs take the SMs left beside the ep_bootstrap counts, which these variables would - // change for the NCCL EP kernels only. + // These variables would change the NCCL EP SM counts but not the GEMMs' share. for (const char* name : {"NCCL_EP_COMM_SMS", "NCCL_EP_DISPATCH_SMS", "NCCL_EP_COMBINE_SMS", "NCCL_EP_DISPATCH_BWD_SMS", "NCCL_EP_COMBINE_BWD_SMS"}) { NVTE_CHECK(std::getenv(name) == nullptr, @@ -149,10 +147,9 @@ void check_rows(const EpGemmContext& ctx, size_t rows, const char* name) { ctx.group.max_recv_tokens_per_rank); } -// Whether the forward dispatch counts the routing itself and writes the caller's expert layout. As -// NCCL EP's dispatch_pull_count_capable for the overlapped group (pull-push flow in one LSA team): -// not in eager mode and at most 65536 / 32 local experts. Without drops only: with them the -// dispatch reports the pre-drop row total. +// Whether the forward dispatch counts the routing and writes the expert layout itself: as NCCL EP's +// dispatch_pull_count_capable, outside eager mode with at most 65536 / 32 local experts, and only +// without drops, which make the dispatch report the pre-drop row total. bool dispatch_writes_layout(const EpGemmContext& ctx, size_t num_local_experts) { return !ctx.eager && !ctx.group.drop_on_overflow && num_local_experts <= 65536 / 32; } @@ -185,8 +182,7 @@ ep::EpDispatchGemmConfig dispatch_fwd_config(const EpGemmContext& ctx, size_t ro } // The backward combine_gemm GEMM: the data gradient of [rows, hidden] inputs and ffn output -// columns. -// The routing-weight gradient is summed in a fixed order unless the layer allows atomics. +// columns. The routing-weight gradient is summed in a fixed order unless atomics are allowed. ep::EpDispatchGemmConfig combine_bwd_config(const EpGemmContext& ctx, size_t rows, size_t hidden, size_t ffn, size_t num_experts, NVTEScalingMode scaling_mode) { @@ -196,15 +192,15 @@ ep::EpDispatchGemmConfig combine_bwd_config(const EpGemmContext& ctx, size_t row return config; } -// With the weight gradient the dispatch backward starts behind the weight gradient's base, which -// waits for the GEMM to complete: the GEMM publishes nothing and runs in the stock tile order. +// With the weight gradient the dispatch backward starts behind the weight gradient's base, so the +// GEMM publishes nothing and runs in the stock tile order. bool dispatch_bwd_plain(const EpGemmContext& ctx, bool with_wgrad) { return with_wgrad && ctx.num_clusters > 0; } -// The backward dispatch_gemm GEMM of [rows, k] inputs and hidden output columns. With the weight -// gradient it runs alone on every SM. The combine's chunk schedule is the group's, so peers agree -// on it whether or not this rank computes a weight gradient. +// The backward dispatch_gemm GEMM of [rows, k] inputs and hidden output columns; with the weight +// gradient it runs alone on every SM. The chunk schedule is the group's, so peers agree on it +// whether or not this rank computes a weight gradient. ep::EpCombineGemmConfig dispatch_bwd_config(const EpGemmContext& ctx, size_t rows, size_t k, size_t hidden, size_t num_experts, NVTEScalingMode scaling_mode, bool with_wgrad) { @@ -222,9 +218,7 @@ ep::EpCombineGemmConfig dispatch_bwd_config(const EpGemmContext& ctx, size_t row ctx.alignment()}; } -// Per-call scratch for the GEMM's readiness flags and state, sliced from the caller's workspace. -// ScratchLayout is the byte layout; nvte_ep_overlap_workspace_size uses it to size the workspace -// without a buffer, and claim_scratch uses it to resolve the pointers in GemmScratch. +// Byte layout of the per-call scratch in the caller's workspace; sizes it without a buffer. struct ScratchLayout { size_t alpha; // [num_experts] float32 per-expert output scale, set to 1 (reused as norm_const) size_t ones; // [rows] float32 of 1, the probability operand when the GEMM is unweighted @@ -249,8 +243,8 @@ ScratchLayout scratch_layout(size_t gemm_bytes, size_t num_experts, size_t rows, return l; } -// Resolved pointers into the workspace slices, plus the words each launch resets. layout is the -// caller's expert_token_offsets, whose row ends the GEMMs read. +// Pointers into the workspace slices and the words each launch resets. layout is the caller's +// expert_token_offsets, whose row ends the GEMMs read. struct GemmScratch { uint8_t* base; uint8_t* wgrad = nullptr; @@ -305,8 +299,7 @@ std::pair workspace_span(const NVTETensor workspace) { return {static_cast(ptr), nvte_tensor_numel(workspace)}; } -// Words of a GEMM that waits on the dispatch tile flags: its tile counter, flags and scheduler -// state. +// Words of a GEMM that waits on the dispatch tile flags. void set_signal_words(GemmScratch& scratch, const ep::WorkspaceLayout& layout, size_t slots) { scratch.signal = reinterpret_cast(scratch.base + layout.signal); scratch.signal_capacity = static_cast(slots); @@ -316,8 +309,7 @@ void set_signal_words(GemmScratch& scratch, const ep::WorkspaceLayout& layout, s ep::kFillZero); } -// Words of a GEMM that publishes column chunks: its first zeroed_bytes (scheduler words, zero at -// entry) and chunk flags. +// Words of a GEMM that publishes column chunks: scheduler words and chunk flags. void set_chunk_words(GemmScratch& scratch, const ep::WorkspaceLayout& layout, size_t chunks, size_t zeroed_bytes) { scratch.signal = reinterpret_cast(scratch.base + layout.signal); @@ -326,8 +318,8 @@ void set_chunk_words(GemmScratch& scratch, const ep::WorkspaceLayout& layout, si scratch.reset.fill(scratch.signal, scratch.signal_capacity, ep::kFillMinusOne); } -// Words of a GEMM that publishes nothing: its first gemm_bytes (zero at entry), and the chunk flags -// of the combine behind it, all ready. +// Words of a GEMM that publishes nothing: its scheduler words and the combine's chunk flags, all +// ready. void set_published_chunk_words(GemmScratch& scratch, size_t gemm_bytes, size_t chunks) { scratch.signal = scratch.flags; scratch.signal_capacity = static_cast(chunks); @@ -382,7 +374,7 @@ struct Wgrad { }; // Checks the weight-gradient operands of a backward entry; nullopt without weight_grad. MXFP8 -// reads both operands columnwise. signal_unit_tokens: as its launches pass it, which can select +// reads both operands columnwise. signal_unit_tokens must match its launches: it can select // another kernel and workspace layout. std::optional make_wgrad(const EpGemmContext& ctx, NVTETensor grad, NVTETensor x, NVTETensor weight_grad, bool accumulate, size_t rows, @@ -447,11 +439,10 @@ std::optional make_wgrad(const EpGemmContext& ctx, NVTETensor grad, NVTET return wgrad; } -// One launch of a weight gradient on num_clusters clusters (none: no launch), a programmatic -// dependent of the kernel before it. Launches sharing the call's workspace split the tiles. -// wait_primary_at_start: no load before that kernel completes. signal_unit_tokens (BF16): the -// launch takes the dispatch flags of that many rows each: no load before every flag of the expert -// rows is set, in place of wait_primary_at_start. +// One weight-gradient launch on num_clusters clusters (none: no launch), a programmatic dependent +// of the kernel before it; launches sharing the call's workspace split the tiles. +// wait_primary_at_start: no load before that kernel completes. signal_unit_tokens (BF16): wait on +// the dispatch flags of that many rows each instead. void launch_wgrad(const Wgrad& wgrad, const GemmScratch& scratch, int num_clusters, bool wait_primary_at_start, size_t signal_unit_tokens, cudaStream_t stream) { if (num_clusters <= 0) { @@ -463,17 +454,14 @@ void launch_wgrad(const Wgrad& wgrad, const GemmScratch& scratch, int num_cluste config.signal_unit_tokens = signal_unit_tokens; ep::WorkspaceLayout layout; const tvm::ffi::Function gemm = get_gemm(config, &layout); - // The call sized the scratch from its base configuration. A base and tail must land on one - // workspace and the same tile-counter offset so they share one counter instead of each resetting - // and re-running the whole GEMM. + // Base and tail must share one workspace and tile counter, or each would re-run the whole GEMM. NVTE_CHECK( layout.total_bytes <= wgrad.layout.total_bytes && layout.counter == wgrad.layout.counter, "weight-gradient launches must share one workspace and tile counter"); auto out = wrap_rowwise(wgrad.weight_grad, false); auto row_ends = wrap_row_ends(scratch); auto ws = wrap_raw(scratch.wgrad, kNVTEByte, layout.total_bytes); - // The tile counter the launches share: the caller zeroed it and the kernel does not reset it, so - // a base and tail into one workspace split one tile list instead of each draining it. + // The shared tile counter, zeroed by the caller and not reset by the kernel. auto counter = wrap_raw(scratch.wgrad + layout.counter, kNVTEInt32, 1); if (config.is_mxfp8()) { auto grad = wrap_columnwise(wgrad.grad, true); @@ -494,10 +482,9 @@ void launch_wgrad(const Wgrad& wgrad, const GemmScratch& scratch, int num_cluste gemm(&grad, &x, &out, &row_ends, &ws, &counter, static_cast(stream)); } -// The columnwise MXFP8 copy of t's received rows, requantized from its rowwise data and compact -// scales into GEMM-swizzled columnwise scales per expert slab. It runs after the preceding kernel -// on the stream, on every SM. The expert slabs are given by the element offsets reset_workspace -// writes from the expert layout. +// Requantizes t's received rows from rowwise data and compact scales into columnwise data with +// GEMM-swizzled scales per expert slab, on every SM after the preceding kernel. The slabs come from +// the element offsets reset_workspace writes. void launch_requant(NVTETensor t, const GemmScratch& scratch, size_t rows, size_t cols, size_t num_experts, cudaStream_t stream) { using namespace transformer_engine; @@ -524,8 +511,8 @@ void launch_requant(NVTETensor t, const GemmScratch& scratch, size_t rows, size_ NVTE_CHECK(ok, "the EP MXFP8 requant is not available: ", kCutedslNeeds); } -// Bytes of the chained weight-gradient workspace of a backward GEMM over num_experts slabs of -// [m, n], as make_wgrad sizes it; the max over the output precisions, which the query lacks. +// Bytes of the chained weight-gradient workspace over num_experts slabs of [m, n], as make_wgrad +// sizes it, maximized over the output precisions. size_t wgrad_workspace_bytes(const EpGemmContext& ctx, size_t rows, size_t m, size_t n, size_t num_experts, NVTEScalingMode scaling_mode) { const size_t routed_tokens = @@ -545,10 +532,8 @@ size_t wgrad_workspace_bytes(const EpGemmContext& ctx, size_t rows, size_t m, si scaling_mode, ctx.alignment(), routed_tokens}; - // The output precision is not known here, so size over both. A variant the device does not - // support (e.g. the SM 10.7 FP32 MXFP8 weight gradient at or below 256 rows) is rejected with - // a TVM-FFI error while building its kernel; skip it rather than failing the sizing of a - // supported call. + // A variant the device does not support (e.g. the SM 10.7 FP32 MXFP8 weight gradient at or + // below 256 rows) throws a TVM-FFI error while building; skip it. try { const auto layout = config.workspace_layout(); if (layout.has_value()) { @@ -577,8 +562,7 @@ size_t gemm_workspace_bytes(const Config& config) { extern "C" { -// Returns the max scratch over every op of the group, not per op: the scratch is small, so one -// size that fits any call lets a caller size one workspace instead of querying each op. +// The max scratch over every op of the group, so one workspace fits any call. size_t nvte_ep_overlap_workspace_size(size_t hidden_dim, size_t ffn_dim, size_t num_local_experts, size_t recv_capacity, int with_weight_grad, int mxfp8, const NVTEEpLayerConfig* layer_cfg) { @@ -589,8 +573,7 @@ size_t nvte_ep_overlap_workspace_size(size_t hidden_dim, size_t ffn_dim, size_t const NVTEScalingMode mx = mxfp8 != 0 ? NVTE_MXFP8_1D_SCALING : NVTE_DELAYED_TENSOR_SCALING; const bool wg = with_weight_grad != 0; size_t need = 0; - // Largest scratch of a call whose GEMM uses `config`; unit_probs sizes the per-row ones buffer - // and wgrad the weight-gradient workspace. + // Largest scratch of a call whose GEMM uses `config`. const auto consider = [&](const auto& config, bool unit_probs, size_t wgrad, size_t dprob_slots_bytes = 0, size_t flag_words = 0) { need = std::max(need, scratch_layout(gemm_workspace_bytes(config), ne, rows, unit_probs, wgrad, @@ -612,8 +595,7 @@ size_t nvte_ep_overlap_workspace_size(size_t hidden_dim, size_t ffn_dim, size_t { const EpGemmContext ctx = make_context(layer_cfg, &NVTEEpSmConfig::dispatch_bwd_num_sms); const size_t wgrad = wg ? wgrad_workspace_bytes(ctx, rows, hidden_dim, ffn_dim, ne, mx) : 0; - // The call's mode is not known here, so size both the atomic and the deterministic - // routing-weight gradient. + // Size both the atomic and the deterministic routing-weight gradient. ep::EpDispatchGemmConfig config = combine_bwd_config(ctx, rows, hidden_dim, ffn_dim, ne, mx); const size_t slots_bytes = rows * ep::dprob_slots_per_row(ffn_dim) * sizeof(float); for (const bool deterministic : {false, true}) { @@ -688,8 +670,8 @@ void nvte_ep_dispatch_gemm_fwd(NVTETensor handle_mem, const NVTETensor topk_idx, "tokens and weight must be bfloat16 or MXFP8"); } - // The GEMM runs beside the dispatch, and its tail on the SMs the dispatch frees. Both launches - // claim tiles from one workspace. + // The GEMM runs beside the dispatch and its tail on the SMs the dispatch frees, both claiming + // tiles from one workspace. ep::WorkspaceLayout layout; const ep::EpDispatchGemmConfig config = dispatch_fwd_config(ctx, rows, hidden, n, num_experts, scaling_mode); @@ -1088,12 +1070,12 @@ void nvte_ep_dispatch_gemm_bwd(NVTETensor handle_mem, const NVTETensor grad_gemm // MXFP8: the call writes the columnwise wgrad_input from its rowwise data when that is set. const bool requant = wgrad && mxfp8 && nvte_get_tensor_param(wgrad_input, kNVTERowwiseData).data_ptr != nullptr; - // The one flag of the whole row of a plain GEMM is reset to 0, published. + // A plain GEMM publishes nothing: its chunk flags are all ready. const bool plain = dispatch_bwd_plain(ctx, wgrad.has_value()); const size_t chunk = combine_chunk(hidden, ctx.group.overlap_config.combine_chunk_hidden); const size_t num_chunks = DIVUP(hidden, chunk); - // With the weight gradient the weight gradient runs beside the dispatch backward. + // The weight gradient runs beside the dispatch backward. ep::WorkspaceLayout layout; const ep::EpCombineGemmConfig config = dispatch_bwd_config(ctx, rows, k, hidden, num_experts, scaling_mode, wgrad.has_value()); diff --git a/transformer_engine/common/ep/ep_gemm_config.h b/transformer_engine/common/ep/ep_gemm_config.h index 7761c29958d..b8009b77df1 100644 --- a/transformer_engine/common/ep/ep_gemm_config.h +++ b/transformer_engine/common/ep/ep_gemm_config.h @@ -60,8 +60,9 @@ struct WorkspaceLayout { // Compiled functions and workspace layouts depend on the architecture of the current device. inline std::string arch_key() { return "_sm" + std::to_string(cuda::sm_arch()); } -// Cache keyed by a configuration string, read under a shared lock. Configurations carry sizes that -// do not fit the 32-bit id of tvm_ffi_bridge::TVMFFIConfigCache. +// Cache of compiled TVM-FFI GEMM functions keyed by a configuration string, read under a shared +// lock. The first lookup of a configuration compiles, so warm up outside graph capture. +// Configurations carry sizes that do not fit the 32-bit id of tvm_ffi_bridge::TVMFFIConfigCache. template class KeyedCache { public: diff --git a/transformer_engine/common/ep/ep_overlap_workspace.cu b/transformer_engine/common/ep/ep_overlap_workspace.cu index a8373ca34bc..d219334f03b 100644 --- a/transformer_engine/common/ep/ep_overlap_workspace.cu +++ b/transformer_engine/common/ep/ep_overlap_workspace.cu @@ -87,6 +87,8 @@ void reset_workspace(const WorkspaceReset& reset, cudaStream_t stream) { NVTE_CHECK_CUDA(cudaGetLastError()); } +// Fixed-order sum of each row's per-ffn-column-cluster partial routing-weight gradients, so the +// result is bitwise reproducible. The nondeterministic mode adds atomically and skips this kernel. void reduce_dprob_slots(const float* slots, float* dprob, int rows, int n_slots, cudaStream_t stream) { if (rows == 0) { diff --git a/transformer_engine/common/include/transformer_engine/ep_gemm.h b/transformer_engine/common/include/transformer_engine/ep_gemm.h index 34161b7a80e..0f4ea875b21 100644 --- a/transformer_engine/common/include/transformer_engine/ep_gemm.h +++ b/transformer_engine/common/include/transformer_engine/ep_gemm.h @@ -165,10 +165,8 @@ void nvte_ep_combine_gemm_fwd(NVTETensor handle_mem, const NVTETensor gemm_in, * grad_recv_topk_weights uses the unweighted activation silu(gate) * up. weight_grad is written * only when non-null; accumulate_weight_grad adds to it instead of overwriting it. * - * grad_recv_topk_weights is summed in a fixed order by default (layer_cfg->allow_nondeterministic - * == 0): bitwise reproducible, at the cost of workspace for one float per row and 256 ffn columns - * and a reduce kernel after the call's GEMMs. Nonzero allow_nondeterministic adds into it - * atomically instead. + * grad_recv_topk_weights is summed in a fixed order by default (bitwise reproducible, needs + * workspace and a reduce kernel). A nonzero layer_cfg->allow_nondeterministic adds atomically. * * Requirements: see the file overview. * diff --git a/transformer_engine/pytorch/csrc/extensions.h b/transformer_engine/pytorch/csrc/extensions.h index 79fde88b0ae..2512ce380f2 100644 --- a/transformer_engine/pytorch/csrc/extensions.h +++ b/transformer_engine/pytorch/csrc/extensions.h @@ -9,6 +9,7 @@ #include +#include #include #include #include @@ -763,14 +764,13 @@ int64_t get_nccl_comm_ptr(c10d::ProcessGroup *process_group); // Borrows torch's NCCL host comm (``comm_ptr`` from ``get_nccl_comm_ptr``). // ``group_name`` is the PG name used by the symm-mem window resolver. // ``zero_copy`` is forwarded into ``NVTEEpGroupConfig.zero_copy``. +// ``sm_config``: dispatch fwd, combine fwd, dispatch bwd, combine bwd SM counts. +// ``overlap_config``: dispatch chunk tokens, combine chunk hidden, push and reduce last-chunk SMs. void ep_initialize(uintptr_t comm_ptr, const std::string &group_name, int64_t num_experts, int64_t max_tokens_per_rank, int64_t max_recv_tokens_per_rank, int64_t hidden_dim, int64_t max_num_sms, pybind11::object max_token_dtype, bool zero_copy, int64_t num_topk, bool drop_on_overflow, - int64_t dispatch_fwd_num_sms, int64_t combine_fwd_num_sms, - int64_t dispatch_bwd_num_sms, int64_t combine_bwd_num_sms, - int64_t dispatch_chunk_tokens, int64_t combine_chunk_hidden, - int64_t combine_push_last_chunk_sms, int64_t combine_reduce_last_chunk_sms); + std::array sm_config, std::array overlap_config); void ep_finalize(); diff --git a/transformer_engine/pytorch/csrc/extensions/ep.cpp b/transformer_engine/pytorch/csrc/extensions/ep.cpp index de6edb8dfc4..760f7e6b985 100644 --- a/transformer_engine/pytorch/csrc/extensions/ep.cpp +++ b/transformer_engine/pytorch/csrc/extensions/ep.cpp @@ -15,6 +15,7 @@ #include #include +#include #include #include #include @@ -57,19 +58,15 @@ std::string g_ep_group_name; // NOLINT(runtime/string) // True while the EP backend holds a borrowed reference to torch's NCCL comm. bool g_ep_initialized = false; -// Zero-copy IO toggle captured at ep_initialize. Atomic so the Python-side -// toggle is safe against concurrent ep_dispatch/combine (which release the GIL). +// Zero-copy toggle captured at ep_initialize; atomic as dispatch/combine release the GIL. std::atomic g_zero_copy_enabled{false}; -// Sentinel returned by maybe_make_window when zero-copy is off or the tensor -// is not symm-mem-backed; the backend treats it as "no window, use staged copy". +// No window: the backend uses a staged copy. constexpr NVTECommWindow kNoWindow = {nullptr, 0}; #ifdef NCCL_HAS_SYMMEM_SUPPORT -// Offset of a symm-mem allocation relative to the start of its NCCL window. -// Newer torch places the signal pad at the front of the allocation and exposes -// get_window_offset() for it; on older torch the window starts at the buffer -// base, where get_offset() is already window-relative. +// Offset of a symm-mem allocation in its NCCL window: get_window_offset() on newer torch, which +// puts the signal pad first, else get_offset(). template auto symm_mem_window_offset(T* sm, int) -> decltype(sm->get_window_offset()) { return sm->get_window_offset(); @@ -78,27 +75,28 @@ template size_t symm_mem_window_offset(T* sm, ...) { return sm->get_offset(); } + +// The symm-mem handle of t on the EP group, or null when t is not symm-mem-backed. +c10::intrusive_ptr symm_mem_of(const at::Tensor& t) { + try { + return c10d::symmetric_memory::rendezvous(t, g_ep_group_name); + } catch (const std::exception&) { + return nullptr; + } +} #endif -// Resolve ``t`` to its NCCL symm-mem window. Returns ``kNoWindow`` when symm-mem -// support isn't compiled in, no group is set, or ``t`` isn't symm-mem-backed. +// The NCCL symm-mem window of t, or kNoWindow without symm-mem support, a group or backing. NVTECommWindow make_window(const at::Tensor& t) { #ifdef NCCL_HAS_SYMMEM_SUPPORT if (g_ep_group_name.empty()) return kNoWindow; - c10::intrusive_ptr sm; - try { - sm = c10d::symmetric_memory::rendezvous(t, g_ep_group_name); - } catch (const std::exception&) { - return kNoWindow; // Tensor not symm-mem-backed; fall back to staged copy. - } + const auto sm = symm_mem_of(t); if (sm == nullptr) return kNoWindow; auto* nccl_sm = dynamic_cast(sm.get()); NVTE_CHECK(nccl_sm != nullptr, "Symm-mem backend mismatch: expected NCCLSymmetricMemory. Set the backend to " "\"NCCL\" before allocating EP payload buffers."); - // NCCL EP consumes window-relative offsets. Add ``t``'s own storage offset so a - // slice/view of a symm-mem allocation (e.g. the scale region carved from a shared - // recv buffer) resolves to its true position in the window. + // Window-relative offset, including t's storage offset for a slice of the allocation. const uint64_t offset = static_cast(symm_mem_window_offset(nccl_sm, 0)) + static_cast(t.storage_offset()) * static_cast(t.element_size()); @@ -109,16 +107,14 @@ NVTECommWindow make_window(const at::Tensor& t) { #endif } -// Resolve ``t`` to an NCCL symm-mem window for the zero-copy one-sided path. -// Returns ``kNoWindow`` when zero-copy is disabled or make_window finds none; -// callers pass the resulting window unconditionally to the backend. +// make_window when zero-copy is enabled, else kNoWindow. NVTECommWindow maybe_make_window(const at::Tensor& t) { if (!g_zero_copy_enabled.load(std::memory_order_relaxed)) return kNoWindow; return make_window(t); } -// Window of a symm-mem input and, for MXFP8, of its scales, whatever the -// zero-copy setting. Throws when either is not symm-mem-backed on the EP group. +// Window of a symm-mem input and, for MXFP8, its scales, whatever the zero-copy setting. Throws +// when either is not symm-mem-backed on the EP group. NVTECommWindow make_input_window(const at::Tensor& t, const std::optional& scale_inv) { NVTECommWindow win = make_window(t); NVTE_CHECK(win.window != nullptr, "symm_input needs a symm-mem input on the EP group"); @@ -132,22 +128,13 @@ NVTECommWindow make_input_window(const at::Tensor& t, const std::optional sm; - try { - sm = c10d::symmetric_memory::rendezvous(t, g_ep_group_name); - } catch (const std::exception&) { - sm = nullptr; - } - NVTE_CHECK(sm != nullptr, "ep zero-copy: ", name, + NVTE_CHECK(symm_mem_of(t) != nullptr, "ep zero-copy: ", name, " must be symm-mem-backed on the EP group (allocate via symm_mem_alloc)."); #else (void)t; @@ -370,10 +357,7 @@ void ep_initialize(uintptr_t comm_ptr, const std::string& group_name, int64_t nu int64_t max_tokens_per_rank, int64_t max_recv_tokens_per_rank, int64_t hidden_dim, int64_t max_num_sms, pybind11::object max_token_dtype, bool zero_copy, int64_t num_topk, bool drop_on_overflow, - int64_t dispatch_fwd_num_sms, int64_t combine_fwd_num_sms, - int64_t dispatch_bwd_num_sms, int64_t combine_bwd_num_sms, - int64_t dispatch_chunk_tokens, int64_t combine_chunk_hidden, - int64_t combine_push_last_chunk_sms, int64_t combine_reduce_last_chunk_sms) { + std::array sm_config, std::array overlap_config) { NVTE_CHECK(!group_name.empty(), "group_name must be non-empty (used for symm-mem lookup)"); NVTE_CHECK(comm_ptr != 0, "comm_ptr must be non-null (torch NCCL host comm pointer)"); NVTE_CHECK(!g_ep_initialized, "ep_initialize called twice without ep_finalize"); @@ -394,12 +378,10 @@ void ep_initialize(uintptr_t comm_ptr, const std::string& group_name, int64_t nu .zero_copy = zero_copy ? 1 : 0, .num_topk = static_cast(num_topk), .drop_on_overflow = drop_on_overflow ? 1 : 0, - .sm_config = {static_cast(dispatch_fwd_num_sms), static_cast(combine_fwd_num_sms), - static_cast(dispatch_bwd_num_sms), static_cast(combine_bwd_num_sms)}, - .overlap_config = {static_cast(dispatch_chunk_tokens), - static_cast(combine_chunk_hidden), - static_cast(combine_push_last_chunk_sms), - static_cast(combine_reduce_last_chunk_sms)}, + .sm_config = {static_cast(sm_config[0]), static_cast(sm_config[1]), + static_cast(sm_config[2]), static_cast(sm_config[3])}, + .overlap_config = {static_cast(overlap_config[0]), static_cast(overlap_config[1]), + static_cast(overlap_config[2]), static_cast(overlap_config[3])}, }; // Release the GIL only around the native init. It must stay held while pybind11 casts // the ``max_token_dtype`` object above and destroys the by-value ``pybind11::object`` @@ -1220,10 +1202,8 @@ void register_ep_bindings(pybind11::module_& m) { py::arg("max_tokens_per_rank"), py::arg("max_recv_tokens_per_rank"), py::arg("hidden_dim"), py::arg("max_num_sms") = 0, py::arg("max_token_dtype"), py::arg("zero_copy") = false, py::arg("num_topk") = 0, py::arg("drop_on_overflow") = false, - py::arg("dispatch_fwd_num_sms") = 0, py::arg("combine_fwd_num_sms") = 0, - py::arg("dispatch_bwd_num_sms") = 0, py::arg("combine_bwd_num_sms") = 0, - py::arg("dispatch_chunk_tokens") = 0, py::arg("combine_chunk_hidden") = 0, - py::arg("combine_push_last_chunk_sms") = 0, py::arg("combine_reduce_last_chunk_sms") = 0); + py::arg("sm_config") = std::array{}, + py::arg("overlap_config") = std::array{}); m.def("ep_finalize", &ep_finalize, "Tear down the EP backend. Idempotent.", py::call_guard()); m.def("ep_get_zero_copy", &ep_get_zero_copy, "Return the current EP zero-copy toggle state."); diff --git a/transformer_engine/pytorch/ep.py b/transformer_engine/pytorch/ep.py index e6306330317..22bdffaa84a 100644 --- a/transformer_engine/pytorch/ep.py +++ b/transformer_engine/pytorch/ep.py @@ -293,14 +293,18 @@ def ep_bootstrap( bool(zero_copy), int(num_topk), bool(drop_on_overflow), - int(sm_config.dispatch_fwd_num_sms), - int(sm_config.combine_fwd_num_sms), - int(sm_config.dispatch_bwd_num_sms), - int(sm_config.combine_bwd_num_sms), - int(overlap_config.dispatch_chunk_tokens), - int(overlap_config.combine_chunk_hidden), - int(overlap_config.combine_push_last_chunk_sms), - int(overlap_config.combine_reduce_last_chunk_sms), + ( + int(sm_config.dispatch_fwd_num_sms), + int(sm_config.combine_fwd_num_sms), + int(sm_config.dispatch_bwd_num_sms), + int(sm_config.combine_bwd_num_sms), + ), + ( + int(overlap_config.dispatch_chunk_tokens), + int(overlap_config.combine_chunk_hidden), + int(overlap_config.combine_push_last_chunk_sms), + int(overlap_config.combine_reduce_last_chunk_sms), + ), ) _BOOTSTRAPPED = True _EP_GROUP = ep_group From 8985c5afd9474a57991dafa641fe40cf5588a4e9 Mon Sep 17 00:00:00 2001 From: Phuong Nguyen Date: Thu, 3 Dec 2026 20:58:39 -0800 Subject: [PATCH 64/67] [PyTorch] Drop the int64 offsets dtype test now that the fused grouped MLP keeps int32 offsets Signed-off-by: Phuong Nguyen --- tests/pytorch/test_grouped_mlp.py | 49 ------------------------------- 1 file changed, 49 deletions(-) diff --git a/tests/pytorch/test_grouped_mlp.py b/tests/pytorch/test_grouped_mlp.py index 055598a0c2d..3f17f8f86c1 100644 --- a/tests/pytorch/test_grouped_mlp.py +++ b/tests/pytorch/test_grouped_mlp.py @@ -1829,55 +1829,6 @@ def test_grouped_mlp_glu_mxfp8_real_cudnn_fusion( ] assert traced_cudnn_grouped_glu_wrappers == expected_calls - @pytest.mark.skipif(not mxfp8_available, reason=reason_for_no_mxfp8) - def test_grouped_mlp_mxfp8_offsets_dtype(self, monkeypatch) -> None: - """The cuDNN MXFP8 GEMMs take int64 offsets.""" - if not _cudnn_frontend_version_supported(): - pytest.skip("Requires cuDNN frontend >= 1.31.0") - if not device_is_blackwell: - pytest.skip("Requires Blackwell") - import cudnn - - offsets_dtypes = {} - for name, key in ( - ("grouped_gemm_glu_wrapper_sm100", "padded_offsets"), - ("grouped_gemm_dglu_wrapper_sm100", "padded_offsets"), - ("grouped_gemm_wgrad_wrapper_sm100", "offsets_tensor"), - ): - - def traced(*args, _wrapper=getattr(cudnn, name), _name=name, _key=key, **kwargs): - offsets_dtypes.setdefault(_name, set()).add(kwargs[_key].dtype) - return _wrapper(*args, **kwargs) - - monkeypatch.setattr(cudnn, name, traced) - fused_cls = te.ops.fused.GroupedMLP_CuTeGEMMGLU - _clear_grouped_glu_kernel_caches() - fused_cls.grouped_gemm_wgrad_kernel.cache_clear() - # FC2 bias-gradient accumulation uses an atomic Triton reduction. - monkeypatch.setenv("NVTE_ALLOW_NONDETERMINISTIC_ALGO", "1") - monkeypatch.delenv("NVTE_DISABLE_CUDNN_UNFUSED_GEMM_IN_GROUPED_MLP", raising=False) - monkeypatch.delenv("NVTE_DISABLE_CUTEDSL_WGRAD_FUSED_GROUPED_MLP", raising=False) - try: - self.test_grouped_mlp( - enable_fusion=True, - group_size=4, - bias=True, - hidden_size=128, - quantization="mxfp8", - single_grouped_weight=True, - activation="scaled_swiglu", - strict_fusion=True, - ) - torch.cuda.synchronize() - finally: - _clear_grouped_glu_kernel_caches() - fused_cls.grouped_gemm_wgrad_kernel.cache_clear() - assert offsets_dtypes == { - "grouped_gemm_glu_wrapper_sm100": {torch.int64}, - "grouped_gemm_dglu_wrapper_sm100": {torch.int64}, - "grouped_gemm_wgrad_wrapper_sm100": {torch.int64}, - } - @pytest.mark.skipif(not nvfp4_available, reason=reason_for_no_nvfp4) @pytest.mark.parametrize("situ_betas", ((4.0, 25.0), (2.0, 8.0))) def test_grouped_mlp_situglu_nvfp4_real_cudnn_hadamard_fusion( From a7714631efd5bd469d652d54ad5bfec0458ec408 Mon Sep 17 00:00:00 2001 From: Phuong Nguyen Date: Thu, 3 Dec 2026 21:13:55 -0800 Subject: [PATCH 65/67] [PyTorch] Test overwrite_main_grad in the EP overlap test on trainable weights against a zero-start reference Signed-off-by: Phuong Nguyen --- tests/pytorch/distributed/run_ep.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/tests/pytorch/distributed/run_ep.py b/tests/pytorch/distributed/run_ep.py index b9e412bc930..de4031c3f2e 100644 --- a/tests/pytorch/distributed/run_ep.py +++ b/tests/pytorch/distributed/run_ep.py @@ -1831,7 +1831,8 @@ def test_moe_overlap_op_variants(self): (None, {"params_to_bf16": True, "main_grad": torch.float32}), (None, {"frozen": (1,)}), (None, {"frozen": (3,)}), - (None, {"frozen": (1, 3), "main_grad": torch.bfloat16, "overwrite": True}), + (None, {"main_grad": torch.bfloat16, "overwrite": True}), + (None, {"frozen": (1, 3), "main_grad": torch.bfloat16}), ] if len(_overlap_recipes()) > 1: recipe = MXFP8BlockScaling() @@ -1905,7 +1906,10 @@ def run(fused): for p in model.parameters(): p.grad = None if main_grad is not None: - p.main_grad = torch.full(p.shape, 0.5, dtype=main_grad, device=device) + # An overwritten reference starts at zero, so it holds the fresh + # weight gradient the fused op must leave over its nonzero start. + start = 0.0 if overwrite and not fused else 0.5 + p.main_grad = torch.full(p.shape, start, dtype=main_grad, device=device) p.overwrite_main_grad = overwrite p.grad_added_to_main_grad = False y = model(x, topk_idx, topk_w, topk_idx) From 78d444ba141222986a2f00e1d9345125486a4c50 Mon Sep 17 00:00:00 2001 From: Phuong Nguyen Date: Thu, 3 Dec 2026 21:17:58 -0800 Subject: [PATCH 66/67] [Common] Write the recomputed activation from the SM 10.7 MXFP8 dGLU kernel Signed-off-by: Phuong Nguyen --- .../common/CuTeDSL/ep_gemm/dispatch_gemm.py | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/transformer_engine/common/CuTeDSL/ep_gemm/dispatch_gemm.py b/transformer_engine/common/CuTeDSL/ep_gemm/dispatch_gemm.py index 78eeaa6b943..8acbe771bb6 100644 --- a/transformer_engine/common/CuTeDSL/ep_gemm/dispatch_gemm.py +++ b/transformer_engine/common/CuTeDSL/ep_gemm/dispatch_gemm.py @@ -321,11 +321,6 @@ def _optional_rows_view(t, rows, cols): def _compile_backward_mxfp8(cfg: DispatchGemmConfig): """MXFP8 FC2 data gradient with the columnwise forward weight [experts, k, n] read N-major, SwiGLU backward in the epilogue, and the forward activation recomputed columnwise.""" - if cfg.h and is_sm107(): - raise NotImplementedError( - "The SM 10.7 MXFP8 dGLU kernel (cuDNN FE moe_blockscaled_grouped_gemm_dglu_rubin) has" - " no h output, the recomputed columnwise forward activation." - ) kernel, (rows, k, n, experts, num_clusters), tail = _prologue(cfg) n_slots = dprob_n_slots(n) if cfg.deterministic else 1 @@ -349,8 +344,8 @@ def launch( def launch_rubin( a, b, sfb, sfa, c, d, d_col, sfd_row, sfd_col, h, sfh_col, dprob, expert_row_ends, alpha, prob, norm_const, workspace, stream, - ): # fmt: skip # pylint: disable=unused-argument - # The SM 10.7 kernel takes the SwiGLU linear offset ahead of dbias and has no h output. + ): # fmt: skip + # The SM 10.7 kernel takes the SwiGLU linear offset ahead of dbias. weight = weight_view(b, n, k, experts, n_major=True) dprob_out = _dprob_view(cfg, dprob, rows, n_slots) kernel( @@ -359,6 +354,7 @@ def launch_rubin( rows_view(d, rows, 2 * n), _optional_rows_view(d_col, rows, 2 * n), sfa, sfd_row, sfd_col, None, norm_const, expert_row_ends, alpha, alpha, prob_view(prob, rows), dprob_out, cutlass.Float32(0.0), None, num_clusters, stream, + h_tensor=_optional_rows_view(h, rows, n), sfh_col_tensor=sfh_col, ) # fmt: skip row_ends, alpha, prob, workspace = tail From 8b671095b81ea0dfe917a4aba72ece8bd584df16 Mon Sep 17 00:00:00 2001 From: Phuong Nguyen Date: Fri, 4 Dec 2026 11:24:16 -0800 Subject: [PATCH 67/67] [Common] Run the EP dispatch backward unsignaled where the forward dispatch writes the layout Signed-off-by: Phuong Nguyen --- transformer_engine/common/ep/ep_gemm_api.cpp | 46 ++++++++++++-------- 1 file changed, 27 insertions(+), 19 deletions(-) diff --git a/transformer_engine/common/ep/ep_gemm_api.cpp b/transformer_engine/common/ep/ep_gemm_api.cpp index e507a315439..e1540cdddc1 100644 --- a/transformer_engine/common/ep/ep_gemm_api.cpp +++ b/transformer_engine/common/ep/ep_gemm_api.cpp @@ -192,25 +192,32 @@ ep::EpDispatchGemmConfig combine_bwd_config(const EpGemmContext& ctx, size_t row return config; } -// With the weight gradient the dispatch backward starts behind the weight gradient's base, so the -// GEMM publishes nothing and runs in the stock tile order. -bool dispatch_bwd_plain(const EpGemmContext& ctx, bool with_wgrad) { - return with_wgrad && ctx.num_clusters > 0; +// Where the forward dispatch writes the layout, the dispatch backward is unsignaled: NCCL EP then +// launches its push as the programmatic dependent of the kernel before it, which lets it in only +// once the GEMM completes. The choice is the group's, so peers agree on it. +bool dispatch_bwd_unsignaled(const EpGemmContext& ctx, size_t num_experts) { + return dispatch_writes_layout(ctx, num_experts); } -// The backward dispatch_gemm GEMM of [rows, k] inputs and hidden output columns; with the weight -// gradient it runs alone on every SM. The chunk schedule is the group's, so peers agree on it -// whether or not this rank computes a weight gradient. +// When the dispatch backward is unsignaled, or starts behind the weight gradient's base, the GEMM +// publishes nothing and runs in the stock tile order. +bool dispatch_bwd_plain(const EpGemmContext& ctx, bool with_wgrad, size_t num_experts) { + return dispatch_bwd_unsignaled(ctx, num_experts) || (with_wgrad && ctx.num_clusters > 0); +} + +// The backward dispatch_gemm GEMM of [rows, k] inputs and hidden output columns; plain, it runs +// alone on every SM. The chunk schedule is the group's, so peers agree on it whether or not this +// rank computes a weight gradient. ep::EpCombineGemmConfig dispatch_bwd_config(const EpGemmContext& ctx, size_t rows, size_t k, size_t hidden, size_t num_experts, NVTEScalingMode scaling_mode, bool with_wgrad) { - const bool plain = dispatch_bwd_plain(ctx, with_wgrad); + const bool plain = dispatch_bwd_plain(ctx, with_wgrad, num_experts); const size_t chunk = combine_chunk(hidden, ctx.group.overlap_config.combine_chunk_hidden); return ep::EpCombineGemmConfig{rows, k, hidden, num_experts, - with_wgrad ? ctx.all_clusters : ctx.num_clusters, + plain ? ctx.all_clusters : ctx.num_clusters, plain ? 0 : chunk, !plain, true, @@ -606,11 +613,11 @@ size_t nvte_ep_overlap_workspace_size(size_t hidden_dim, size_t ffn_dim, size_t // Backward dispatch: FC1 dgrad, with the FC1 weight gradient [2 * ffn, hidden]. { const EpGemmContext ctx = make_context(layer_cfg, &NVTEEpSmConfig::combine_bwd_num_sms); - const bool plain = dispatch_bwd_plain(ctx, wg); + const bool plain = dispatch_bwd_plain(ctx, wg, ne); const size_t chunk = combine_chunk(hidden_dim, ctx.group.overlap_config.combine_chunk_hidden); const size_t wgrad = wg ? wgrad_workspace_bytes(ctx, rows, 2 * ffn_dim, hidden_dim, ne, mx) : 0; consider(dispatch_bwd_config(ctx, rows, 2 * ffn_dim, hidden_dim, ne, mx, wg), true, wgrad, 0, - plain ? DIVUP(hidden_dim, chunk) : 0); + plain && !dispatch_bwd_unsignaled(ctx, ne) ? DIVUP(hidden_dim, chunk) : 0); } return need; } @@ -1070,21 +1077,22 @@ void nvte_ep_dispatch_gemm_bwd(NVTETensor handle_mem, const NVTETensor grad_gemm // MXFP8: the call writes the columnwise wgrad_input from its rowwise data when that is set. const bool requant = wgrad && mxfp8 && nvte_get_tensor_param(wgrad_input, kNVTERowwiseData).data_ptr != nullptr; - // A plain GEMM publishes nothing: its chunk flags are all ready. - const bool plain = dispatch_bwd_plain(ctx, wgrad.has_value()); + // A plain GEMM publishes nothing: the chunk flags of a signaled dispatch backward are all ready. + const bool unsignaled = dispatch_bwd_unsignaled(ctx, num_experts); + const bool plain = dispatch_bwd_plain(ctx, wgrad.has_value(), num_experts); const size_t chunk = combine_chunk(hidden, ctx.group.overlap_config.combine_chunk_hidden); const size_t num_chunks = DIVUP(hidden, chunk); + const size_t flag_words = plain && !unsignaled ? num_chunks : 0; // The weight gradient runs beside the dispatch backward. ep::WorkspaceLayout layout; const ep::EpCombineGemmConfig config = dispatch_bwd_config(ctx, rows, k, hidden, num_experts, scaling_mode, wgrad.has_value()); const tvm::ffi::Function gemm = get_gemm(config, &layout); - GemmScratch scratch = - claim_scratch(ws_base, ws_bytes, layout.total_bytes, num_experts, rows, true, - wgrad ? wgrad->layout.total_bytes : 0, 0, plain ? num_chunks : 0); + GemmScratch scratch = claim_scratch(ws_base, ws_bytes, layout.total_bytes, num_experts, rows, + true, wgrad ? wgrad->layout.total_bytes : 0, 0, flag_words); if (plain) { - set_published_chunk_words(scratch, layout.total_bytes, num_chunks); + set_published_chunk_words(scratch, layout.total_bytes, flag_words); } else { set_chunk_words(scratch, layout, num_chunks, layout.signal); } @@ -1130,8 +1138,8 @@ void nvte_ep_dispatch_gemm_bwd(NVTETensor handle_mem, const NVTETensor grad_gemm TensorWrapper signal(scratch.signal, std::vector{num_chunks}, DType::kInt32); const ep::EpSignal combine_signal{signal.data(), chunk}; ctx.backend.dispatch_bwd(handle_mem, grad_recv_tokens, no_window, grad_recv_topk_weights, - no_window, grad_tokens, grad_topk_weights, &combine_signal, - ctx.layer_cfg, stream); + no_window, grad_tokens, grad_topk_weights, + unsignaled ? nullptr : &combine_signal, ctx.layer_cfg, stream); } } // extern "C"