diff --git a/3rdparty/nccl-extensions b/3rdparty/nccl-extensions index 3a03258e981..58aa61d4193 160000 --- a/3rdparty/nccl-extensions +++ b/3rdparty/nccl-extensions @@ -1 +1 @@ -Subproject commit 3a03258e981bdb3d3d0c1eb8144eb8752e8d2fa1 +Subproject commit 58aa61d4193c333042613d956b9f2da60a57d6ee diff --git a/docs/api/pytorch.rst b/docs/api/pytorch.rst index e770cf24fc9..168ed6cd069 100644 --- a/docs/api/pytorch.rst +++ b/docs/api/pytorch.rst @@ -148,8 +148,16 @@ 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. With the overlap enabled (``NVTE_MOE_OVERLAP=1``), a dispatch, +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 @@ -157,6 +165,10 @@ routing weights through the sequence's extra-tensor channels. .. autoapiclass:: transformer_engine.pytorch.ep.EpConfig +.. 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/docs/envvars.rst b/docs/envvars.rst index aa5d011794f..a61f4a9a9a4 100644 --- a/docs/envvars.rst +++ b/docs/envvars.rst @@ -161,6 +161,26 @@ 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`). +.. envvar:: NVTE_MOE_OVERLAP + + :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 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 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 + 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 :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..67cabf6c389 --- /dev/null +++ b/examples/pytorch/ep/bench/bench_moe_overlap.py @@ -0,0 +1,266 @@ +# 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: + + 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 and an EP +group within one NVLink domain. 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, EpSmConfig, ep_bootstrap, ep_finalize +from transformer_engine.pytorch.ops.fused import moe_overlap + + +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), + sm_config=EpSmConfig(*sms), + ) + + 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): + topk_idx, x, topk_w, grad_out = _inputs(args, num_experts, device) + with _autocast(recipe): + y = model(x, topk_idx, topk_w, topk_idx) + y.backward(grad_out) + 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/qa/L0_pytorch_unittest/test.sh b/qa/L0_pytorch_unittest/test.sh index 17bddf39bb8..f46eb78441c 100644 --- a/qa/L0_pytorch_unittest/test.sh +++ b/qa/L0_pytorch_unittest/test.sh @@ -103,6 +103,9 @@ 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" +# 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" if [ "$RET" -ne 0 ]; then echo "Error in the following test cases:$FAILED_CASES" diff --git a/tests/cpp_distributed/test_ep.cu b/tests/cpp_distributed/test_ep.cu index e1fddafe137..5de9abdd016 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{}, @@ -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. @@ -456,7 +496,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 +567,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 +610,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 +654,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 +723,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 +791,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 +862,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 +988,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 +1026,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 310d9a29c4a..de4031c3f2e 100644 --- a/tests/pytorch/distributed/run_ep.py +++ b/tests/pytorch/distributed/run_ep.py @@ -5,9 +5,11 @@ from contextlib import nullcontext from dataclasses import replace +import itertools import os import sys import unittest +from unittest import mock import numpy as np import torch @@ -16,10 +18,13 @@ 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.common.recipe import MXFP8BlockScaling +from transformer_engine.pytorch.ops.fused.moe_overlap import _moe_overlap_unsupported_reason +from transformer_engine.common.recipe import Float8CurrentScaling, MXFP8BlockScaling from transformer_engine.pytorch.ep import ( EpBuffer, EpConfig, + EpOverlapConfig, + EpSmConfig, ep_bootstrap, ep_finalize, get_ep_drop_on_overflow, @@ -41,10 +46,23 @@ # 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: 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 = 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,18 @@ 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}") +# 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 = None +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): @@ -84,6 +114,18 @@ 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 _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): """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 +170,16 @@ def _build_ep_group(): return dist.new_group(ranks=ranks, backend="nccl") +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 +270,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 +282,55 @@ 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, + 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. + 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 +369,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( @@ -335,6 +413,23 @@ def _require_mxfp8_shapes(self): "(set NVTE_EP_HIDDEN_DIM / NVTE_EP_TOKENS_PER_RANK)" ) + 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.""" @@ -491,7 +586,7 @@ def test_primitive_dispatch_combine_identity(self): torch.cuda.synchronize() torch.testing.assert_close(result.float(), tokens.float(), atol=5e-2, rtol=5e-2) - # Autograd + # Overlapped MoE @_zero_copy_test_include def test_dispatch_autograd(self): @@ -814,23 +909,6 @@ def step(): torch.cuda.synchronize() torch.testing.assert_close(result.float(), ref.float(), atol=0, rtol=0) - 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 - def _caller_recv(self): """A persistent recv token + weight buffer pair sized to recv_capacity_per_rank, for capturing a caller-provided-recv dispatch.""" @@ -1666,6 +1744,520 @@ def _run_megamoe_vs_reference( **tolerances, ) + def _moe_ops( + self, config, buffer, accumulate_into_main_grad=False, *, ffn=HIDDEN_DIM, **linear_kwargs + ): + """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 = { + "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 + ) + fc2 = te_ops.GroupedLinear( + NUM_LOCAL_EXPERTS, ffn, 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 + + @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 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) + if len(_overlap_recipes()) == 1: + return + recipe = MXFP8BlockScaling() + 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): + 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, + ) # fmt: skip + self.assertIn(name, reason or "") + + @_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 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}), + (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, {"main_grad": torch.bfloat16, "overwrite": True}), + (None, {"frozen": (1, 3), "main_grad": torch.bfloat16}), + ] + if len(_overlap_recipes()) > 1: + recipe = MXFP8BlockScaling() + cases += [ + (recipe, {"input_grad": False}), + (recipe, {"params_to_bf16": True}), + (recipe, {"quantized_weights": True, "main_grad": torch.float32}), + (recipe, {"frozen": (1,)}), + (recipe, {"frozen": (3,)}), + ] + 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=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) + 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 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 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 is not None, + ffn=ffn, + dtype=torch.float32 if params_to_bf16 else torch.bfloat16, + ) + if recipe is not None: + 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) + tokens, topk_idx, w, grad_out = self._moe_calls(1)[0] + + def run(fused): + # 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) + 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 is not None: + # 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) + y.backward(grad_out) + torch.cuda.synchronize() + self._assert_fusion(model, fused) + trained = [p for p in model.parameters() if p.requires_grad] + if main_grad is not None: + self.assertTrue(all(p.grad_added_to_main_grad for p in trained)) + 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())) + 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. + 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(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 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(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) + + 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=1 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 nullcontext() + return mock.patch.object(moe_overlap, "_moe_overlap_available", return_value=False) + + def _assert_fusion(self, model, fused): + """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 + + ran = any( + isinstance(op, moe_overlap.FusedMoE) + for group in model._module_groups + for op, _ in getattr(group, "_forward_ops", []) + ) + 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.""" + 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) + + @_eager_test_include + @_overflow_test_include + @_mxfp8_align_test + @_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.""" + self._require_moe_overlap() + topk_idx, tokens, w = _make_identity_inputs(self.cfg.rank, self.cfg.ep_size) + for recipe in _overlap_recipes(): + 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) + 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): + 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._assert_fusion(model, fused) + results.append( + (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, int(counts.sum())) + + @_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.""" + 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(), *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._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 + 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 + @_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() + 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 needs_grad: + torch.testing.assert_close(x_grad, ref_x_grad) + torch.testing.assert_close(w_grad, ref_w_grad) + else: + self.assertIsNone(x_grad) + self.assertIsNone(w_grad) + + @_eager_test_include + @_overflow_test_include + @_mxfp8_align_test + @_overlap_test + 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) + model = te_ops.Sequential(*self._moe_ops(config, buffer)) + buffer.tokens_per_expert = buffer.tokens_per_expert.to(torch.int32) + with self.assertRaisesRegex(TypeError, "int64"): + self._moe_call(model, *self._moe_calls(1)[0]) + + @_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) + + @_mxfp8_align_test + @_overlap_test + def test_moe_overlap_deterministic(self): + """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() + 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) + + 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 + under MXFP8 transport.""" + self._require_moe_overlap() + device = self.cfg.device + 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 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) + # 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 + def _init_distributed(): dist.init_process_group(backend="nccl") diff --git a/tests/pytorch/distributed/run_test_ep.sh b/tests/pytorch/distributed/run_test_ep.sh index a23809ad108..b10fb081df1 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). @@ -49,12 +62,22 @@ run_pass() { local overflow="${4:-0}" 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" - 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 + 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}" \ - 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="${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]} @@ -68,6 +91,26 @@ run_pass() { echo "[${label}] ERROR: no test summary — likely hang or early crash" RET=1 fi + # 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" + 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 } @@ -88,7 +131,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 @@ -109,4 +152,40 @@ 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 -exit $RET +# 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=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=1 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}") +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 [ "${NVTE_MOE_OVERLAP:-0}" != "0" ]; then + 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=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 + run_pass "overlap_overflow" 0 0 1 1 0 1 + # NVTE_EP_OVERLAP_CONFIG: combine_chunk_hidden,push_last_chunk_sms,reduce_last_chunk_sms, + # 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, 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 + +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 new file mode 100644 index 00000000000..b1b712a639f --- /dev/null +++ b/tests/pytorch/test_ep_gemm.py @@ -0,0 +1,518 @@ +# Copyright (c) 2022-2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# See LICENSE for license information. + +"""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 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. +OVERLAP = os.environ.get("NVTE_MOE_OVERLAP", "0") != "0" +if OVERLAP: + import ctypes + + import tvm_ffi + + import transformer_engine.pytorch # pylint: disable=unused-import + from transformer_engine.common.CuTeDSL.ep_gemm import ( + combine_gemm, + dispatch_gemm, + wgrad_gemm, + ) + +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 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) + + +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, + token_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}_{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(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) + # 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.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=torch.int64, 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) + 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("mxfp8", [False, True]) +@pytest.mark.parametrize("tail_clusters", [0, 4]) +@pytest.mark.parametrize("device_layout", [False, True]) +@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. + 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 + 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(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) + 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.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 + )[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", [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.""" + 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): + 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, 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``. With ``kernel_class``, the configuration must build that kernel.""" + device = torch.device("cuda") + 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, 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) + launch = tvm_ffi.get_global_func(name) + + 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) + 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.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. + counter = torch.zeros(1, dtype=torch.int32, device=device) + stream = ctypes.c_void_p(torch.cuda.current_stream().cuda_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() + + +@pytest.mark.parametrize( + "mxfp8,fp32_out,accumulate,rows_per_expert", + [ + (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) + 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 + + +@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 = 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) + 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 + + +@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"): + 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, + ) + + +# 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 ac7edbc3d0a..00000000000 --- a/tests/pytorch/test_nccl_ep_discovery.py +++ /dev/null @@ -1,60 +0,0 @@ -# Copyright (c) 2022-2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. -# -# See LICENSE for license information. - -import transformer_engine - - -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() 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..58af43ab352 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,30 @@ 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, + 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, + ): + 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 +59,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..75a51debf7c --- /dev/null +++ b/transformer_engine/common/CuTeDSL/ep_gemm/__init__.py @@ -0,0 +1,12 @@ +# 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. +""" + +from . import dispatch_gemm, combine_gemm, 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..f8b584b7998 --- /dev/null +++ b/transformer_engine/common/CuTeDSL/ep_gemm/_loader.py @@ -0,0 +1,231 @@ +# Copyright (c) 2022-2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# See LICENSE for license information. + +"""Loading of the EP grouped GEMMs from the cuDNN frontend package, with TVM-FFI registration. + +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 importlib +import logging +from dataclasses import dataclass + +import tvm_ffi + +from ..utils import device_compute_capability, tvm_ffi_function + +logger = logging.getLogger(__name__) + +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 + +# cuDNN frontend package holding the EP grouped GEMM kernels. +# 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. +_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_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", + "moe_grouped_gemm_wgrad_wide": "wgrad.moe_grouped_gemm_wgrad_wide", +} + + +@dataclass(frozen=True) +class GemmArch: + """BF16 grouped GEMM kernels of one architecture as ``module.Class`` paths under ``_PKG``.""" + + dispatch_fwd: str # FC1 + SwiGLU + dispatch_bwd: str # FC2 data gradient + SwiGLU backward + combine: str # FC2, FC1 data gradient + + +_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", +) +# 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(): + """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 device_compute_capability() == (10, 7) + + +def import_gemm_modules(*names): + """Import the named modules of the kernel package (and ``moe_utils`` last).""" + return tuple( + importlib.import_module(f"{_PKG}.{_MODULE_PATHS.get(name, 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).rsplit(".", 1) + module = importlib.import_module(f"{_PKG}.{module_name}") + return getattr(module, class_name), importlib.import_module(f"{_PKG}.moe_utils") + + +def wide_bf16_wgrad_kernel(): + """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): + """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 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 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 + + 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_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(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), + ) + + +def register_function(fn_name, compile_fn, what) -> bool: + """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: + tvm_ffi.register_global_func(fn_name, tvm_ffi_function(compile_fn()), override=True) + except Exception as e: # pylint: disable=broad-exception-caught + 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 new file mode 100644 index 00000000000..63be9387145 --- /dev/null +++ b/transformer_engine/common/CuTeDSL/ep_gemm/combine_gemm.py @@ -0,0 +1,238 @@ +# 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 (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 +from dataclasses import dataclass, field + +import cutlass +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, + MMA_TILER_MN, + ROWS_PER_TILE, + blockscaled_kwargs, + compile_launch, + fake_tensor, + fp8_fake, + import_bf16_kernel, + import_gemm_modules, + is_sm107, + prob_view, + register_function, + rows_view, + scale_fake, + tail_fakes, + 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) + 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) + + @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.StreamingOutputNotifyConfig( + comb.StreamingOutputNotifyMode.N_CHUNK, + cfg.n_chunk, + comb.streaming_output_notify_capacity(cfg.n_chunk, cfg.n), + caller_reset=True, + clusters_beside_consumer=cfg.num_clusters, + ) + if cfg.mxfp8 and is_sm107(): + 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: + 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, + **blockscaled_kwargs(cfg.num_experts), + ) + 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, + streaming_output_notify=notify, + launch_pdl_dependents_at_entry=cfg.dependents_at_entry, + ) + + +@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.streaming_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) + # 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), + 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, + 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, + ) # 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, +): # 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, + ))) # 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, +) -> 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, + ) # 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..8acbe771bb6 --- /dev/null +++ b/transformer_engine/common/CuTeDSL/ep_gemm/dispatch_gemm.py @@ -0,0 +1,421 @@ +# Copyright (c) 2022-2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# See LICENSE for license information. + +"""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``. Rows = receive rows. + + 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]. + +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 +from dataclasses import dataclass, field + +import cutlass +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, + dprob_n_slots, + CLUSTER_MN, + MMA_TILER_MN, + ROWS_PER_TILE, + blockscaled_kwargs, + compile_launch, + fake_tensor, + fp8_fake, + import_bf16_kernel, + import_gemm_modules, + is_sm107, + prob_view, + register_function, + rows_view, + scale_fake, + slots_view, + tail_fakes, + weight_view, +) + +# Activation of the FC1 GLU to the activation function of its backward epilogue. +_BACKWARD_ACTIVATIONS = {"swiglu": "dswiglu"} + + +@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) + 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 + 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) + + 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.token_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() -> 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 _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 = { + **blockscaled_kwargs(cfg.num_experts), + "streaming_signal_capacity": cfg.signal_capacity, + "compact_sfa_sf_warp": True, + "use_pdl": True, + } + if cfg.backward: + return _backward_kernel_class(True)( + discrete_col_sfd=True, + act_func=backward_activation, + launch_pdl_dependents_at_entry=True, + **deterministic, + **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 + # 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, + act_func=cfg.activation, + enable_bias=False, + generate_c=True, + device_layout=cfg.device_layout, + **_tail_trigger(), + **{**common, "vectorized_f32": True}, + ) + 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, + device_layout=cfg.device_layout, + **_tail_trigger(), + **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, + "streaming_signal_capacity": cfg.signal_capacity, + "use_pdl": True, + } + if cfg.backward: + 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") + return kernel_class( + weight_mode=moe_utils.MoEWeightMode.DENSE, + act_func=cfg.activation, + generate_c=True, + enable_bias=False, + device_layout=cfg.device_layout, + **_tail_trigger(), + **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_kernel_helpers") + offsets = helpers.streaming_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 _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) + 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) + 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 = _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), + rows_view(d, rows, 2 * n), expert_row_ends, alpha, alpha, prob_view(prob, rows), + dprob_out, 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 * n_slots,), (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) + 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), + rows_view(d, rows, d_cols), None, 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, + 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 _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.""" + 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, 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) + 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), + 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, None, num_clusters, stream, + 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 + # 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( + 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, + h_tensor=_optional_rows_view(h, rows, n), sfh_col_tensor=sfh_col, + ) # fmt: skip + + row_ends, alpha, prob, workspace = tail + return compile_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), + 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)) if cfg.d_col else None, + scale_fake(rows, 2 * 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 * n_slots,), (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, token_alignment, + 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(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, 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, 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, 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, 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 new file mode 100644 index 00000000000..02d31a44276 --- /dev/null +++ b/transformer_engine/common/CuTeDSL/ep_gemm/wgrad_gemm.py @@ -0,0 +1,324 @@ +# 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, 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 +from dataclasses import dataclass, field + +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, + MMA_TILER_MN, + SF_VEC_SIZE, + fake_tensor, + fp8_fake, + import_gemm_modules, + is_sm107, + register_function, + scale_fake, + wide_bf16_wgrad_kernel, +) + + +@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 + 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 + 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) + + 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.""" + 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.""" + return self.signal_unit_tokens > 0 + + @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 + return wide_bf16_wgrad_kernel().can_implement(self.m, self.n) + + +def _mxfp8_kernels(): + """(stock, global-descriptor, A-reuse) MXFP8 weight-gradient kernel classes of the device and + moe_utils.""" + if is_sm107(): + 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 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; 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.""" + 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) + 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, + 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" + 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, + **common, + ) + + +@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.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), + ) + 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, counter, 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, + scheduler_counter=counter, + ) # fmt: skip + + 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, + ) + + @cute.jit + 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, scheduler_counter=counter + ) + + if not cfg.signal_unit_tokens: + return compile_launch(launch, *fakes) + + @cute.jit + def launch_signal(grad, x, weight_grad, expert_row_ends, workspace, counter, signal, stream): + a, b, out = views(grad, x, weight_grad) + 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) + + +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, +): # 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), + ) # 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, +): # 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, + ))) # 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, +) -> 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, + ) # 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..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") @@ -64,6 +69,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/__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/common/cast/mxfp8/requantize_mxfp8_cutedsl.cuh b/transformer_engine/common/cast/mxfp8/requantize_mxfp8_cutedsl.cuh index aa7b4e63ea6..ac0750772f8 100644 --- a/transformer_engine/common/cast/mxfp8/requantize_mxfp8_cutedsl.cuh +++ b/transformer_engine/common/cast/mxfp8/requantize_mxfp8_cutedsl.cuh @@ -72,7 +72,8 @@ struct MXFP8RequantConfig { }; inline bool mxfp8_requantize_cutedsl(const GroupedTensor &input, GroupedTensor *output, - Tensor *dequantized, cudaStream_t stream) { + 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()) return false; @@ -80,15 +81,21 @@ 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. - const bool warp_tile = !input.all_same_shape() && !return_dequantized; + // 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)) 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; + // 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; } @@ -102,7 +109,7 @@ 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}; @@ -117,7 +124,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 (needs_offsets) { const SimpleTensor offsets(input.tensor_offsets.dptr, {groups + 1}, DType::kInt64); mOffsets = DLTensorWrapper(offsets, false, device); } diff --git a/transformer_engine/common/ep/ep_api.cpp b/transformer_engine/common/ep/ep_api.cpp index bc85c1e00f5..8f98e28d287 100644 --- a/transformer_engine/common/ep/ep_api.cpp +++ b/transformer_engine/common/ep/ep_api.cpp @@ -53,25 +53,35 @@ 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); } 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, @@ -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); } @@ -177,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 6642dc435c0..01a13297de7 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 @@ -102,6 +103,50 @@ inline ncclEpTensor_t make_nccl_ep_tensor(const NVTETensor t, NVTEShape& shape_o return desc; } +// 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(); + 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."); +} + +// 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; + + // 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; + } + 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); + 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; + } +}; + +// 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 " + "(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,19 @@ 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); + 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 ", + sm_cfg.dispatch_fwd_num_sms, ", ", sm_cfg.combine_fwd_num_sms, ", ", + sm_cfg.dispatch_bwd_num_sms, ", ", sm_cfg.combine_bwd_num_sms); + 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 ", + 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); @@ -336,9 +394,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.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_.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. +#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; @@ -359,6 +451,20 @@ void EPBackend::init(ncclComm_t ep_comm, NVTEEpGroupConfig group_config) { setenv("NCCL_EP_PREPROCESS_NUM_SMS", sm_buf, /*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.overlap_config.combine_push_last_chunk_sms); + set_last_chunk_sms("NCCL_EP_HT_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)); ep_comm_ = ep_comm; @@ -399,7 +505,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]"); @@ -408,7 +515,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) { @@ -420,11 +528,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"); @@ -434,15 +548,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 +630,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, /*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; // Block-scaled payloads forward the per-token scale-inverse; select the matching recipe. @@ -526,8 +643,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 +656,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 +672,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 +684,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 +694,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 +715,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 +735,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, /*row_tiles=*/false, "combine"); + ncclEpCombineOutputs_t out_struct = NCCL_EP_COMBINE_OUTPUTS_INIT; out_struct.tokens = &nccl_result_out; @@ -615,14 +747,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 +778,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, /*row_tiles=*/false, "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 +794,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..0e647477c53 100644 --- a/transformer_engine/common/ep/ep_backend.h +++ b/transformer_engine/common/ep/ep_backend.h @@ -26,43 +26,46 @@ namespace transformer_engine { namespace ep { +/*! \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 { + NVTETensor ready; + size_t granularity; +}; + /*! \brief EP backend per CUDA device; owns the NCCL EP group, borrows the comm. */ class EPBackend { public: /*! \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, 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. + // 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, 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. + // 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, @@ -70,23 +73,31 @@ 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 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 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. 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 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 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(); @@ -95,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_. @@ -104,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); @@ -115,15 +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. - // 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, @@ -131,13 +137,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..e1540cdddc1 --- /dev/null +++ b/transformer_engine/common/ep/ep_gemm_api.cpp @@ -0,0 +1,1192 @@ +/************************************************************************* + * 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 +#include + +#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; + +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; +using ep::kClusterSize; +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; +using transformer_engine::wrap_rowwise; +using transformer_engine::wrap_scales; + +size_t align_up(size_t value) { + return (value + kWorkspaceAlign - 1) / kWorkspaceAlign * kWorkspaceAlign; +} + +// 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); + 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. +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 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 +// on the other 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 == 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"); + NVTE_CHECK(!group.zero_copy, "the overlapped ops do not support zero-copy"); + // 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, + "the overlapped ops split the SMs by the ep_bootstrap " + "counts; unset ", + name); + } + const int sm_count = transformer_engine::cuda::sm_count(); + 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)); + 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}; + 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, + ") 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); +} + +// 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; +} + +// 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, ctx.group.overlap_config.combine_chunk_hidden), + true, + false, + scaling_mode, + ctx.alignment(), + 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 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) { + 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; +} + +// 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); +} + +// 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, num_experts); + const size_t chunk = combine_chunk(hidden, ctx.group.overlap_config.combine_chunk_hidden); + return ep::EpCombineGemmConfig{rows, + k, + hidden, + num_experts, + plain ? ctx.all_clusters : ctx.num_clusters, + plain ? 0 : chunk, + !plain, + true, + scaling_mode, + ctx.alignment()}; +} + +// 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 + 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 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.flags = l.dprob_slots + align_up(dprob_slots_bytes); + l.total = l.flags + align_up(sizeof(int32_t) * flag_words); + return l; +} + +// 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; + 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 + int32_t* flags = nullptr; // [flag words] chunk flags the GEMM does not publish + 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, + 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_workspace_size"); + 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); + } + 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); + 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)}; +} + +// 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); + 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: 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); + 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); +} + +// 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); + 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)); + scratch.reset.layout = scratch.layout; + scratch.reset.num_experts = scratch.num_experts; +} + +// The per-expert row ends operand: the layout past expert 0's start. +DLTensorWrapper wrap_row_ends(const GemmScratch& scratch) { + 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: ", kCutedslNeeds); + 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. 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, + 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"); + 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_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, ctx.alignment(), routed_tokens}, + {}}; + const auto layout = wgrad.config.workspace_layout(); + NVTE_CHECK(layout.has_value(), "cannot query the weight-gradient workspace layout"); + wgrad.layout = *layout; + return wgrad; +} + +// 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) { + return; + } + ep::EpWgradConfig config = wgrad.config; + config.num_clusters = num_clusters; + config.wait_primary_at_start = wait_primary_at_start; + config.signal_unit_tokens = signal_unit_tokens; + ep::WorkspaceLayout layout; + const tvm::ffi::Function gemm = get_gemm(config, &layout); + // 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 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); + 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, &counter, + static_cast(stream)); + return; + } + 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)); +} + +// 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; + 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, + /*force_warp_tile=*/true); + NVTE_CHECK(ok, "the EP MXFP8 requant is not available: ", kCutedslNeeds); +} + +// 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 = + 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, + n, + num_experts, + 1, + fp32_out, + false, + false, + 0, + scaling_mode, + ctx.alignment(), + routed_tokens}; + // 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()) { + bytes = std::max(bytes, layout->total_bytes); + } else { + skipped = "its workspace layout is not available"; + } + } 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; +} + +// 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: ", kCutedslNeeds); + return layout->total_bytes; +} + +} // namespace + +extern "C" { + +// 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) { + 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`. + 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, + dprob_slots_bytes, flag_words) + .total); + }; + + // Forward dispatch: FC1 + SwiGLU, no weight gradient. + { + const EpGemmContext ctx = make_context(layer_cfg, &NVTEEpSmConfig::dispatch_fwd_num_sms); + 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. + { + 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, &NVTEEpSmConfig::dispatch_bwd_num_sms); + const size_t wgrad = wg ? wgrad_workspace_bytes(ctx, rows, hidden_dim, ffn_dim, ne, mx) : 0; + // 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}) { + config.deterministic = deterministic; + consider(config, false, wgrad, deterministic ? slots_bytes : 0); + } + } + // 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, 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 && !dispatch_bwd_unsignaled(ctx, ne) ? DIVUP(hidden_dim, chunk) : 0); + } + 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, + 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, &NVTEEpSmConfig::dispatch_fwd_num_sms); + 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(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) == 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) { + 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_ep_mxfp8_dims(hidden, n / 2); + } else { + NVTE_CHECK( + nvte_tensor_type(tokens) == kNVTEBFloat16 && nvte_tensor_type(weight) == kNVTEBFloat16, + "tokens and weight must be bfloat16 or MXFP8"); + } + + // 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); + // 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) { + 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.signal_unit_tokens()); + // NCCL EP writes the expert starts, layout[0, num_experts), and the padded counts. + 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, + std::vector{static_cast(scratch.signal_capacity)}, + DType::kInt32); + const ep::EpSignal dispatch_signal{signal.data(), ctx.signal_unit_tokens()}; + NVTECommWindow no_window{}; + if (device_layout) { + // 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) * 2), + ep::kFillMinusOne); // in int32 words + ep::reset_workspace(scratch.reset, stream); + 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(), + 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, + offsets.data(), ctx.layer_cfg, stream); + } + // 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 = 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, + 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_row_ends(scratch); + 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)); + } + } + // 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.layout + num_experts, sizeof(int64_t), + cudaMemcpyDefault, 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, &NVTEEpSmConfig::combine_fwd_num_sms); + 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); + } else { + NVTE_CHECK( + 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 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, DIVUP(n, n_chunk), layout.signal); + set_layout(scratch, expert_token_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_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); + 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{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, + 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 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) { + 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, &NVTEEpSmConfig::dispatch_bwd_num_sms); + 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, + "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; + 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"); + 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); + } 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_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"); + + // 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"); + // 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, wgrad_signal_tokens); + + ep::WorkspaceLayout layout; + 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. + 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); + } + 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); + } + ep::reset_workspace(scratch.reset, stream); + + // 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.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); + + // 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 = 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); + 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); + // 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 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)); + // 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 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, 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. + if (wgrad) { + // 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); + launch_wgrad(*wgrad, scratch, ctx.all_clusters - base_clusters, false, 0, stream); + } + reduce_dprob(); + 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. + 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, + const NVTETensor grad_recv_topk_weights, + 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, + 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, &NVTEEpSmConfig::combine_bwd_num_sms); + 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]; + 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_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; + 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_ep_mxfp8_dims(hidden, k / 2); + } 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; + // 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, flag_words); + if (plain) { + set_published_chunk_words(scratch, layout.total_bytes, flag_words); + } else { + set_chunk_words(scratch, layout, num_chunks, layout.signal); + } + if (wgrad) { + scratch.reset.fill(scratch.wgrad + wgrad->layout.counter, 1, ep::kFillZero); + } + set_layout(scratch, expert_token_offsets); + if (requant) { + scratch.reset.offsets = scratch.offsets; + scratch.reset.offsets_cols = static_cast(hidden); + } + ep::reset_workspace(scratch.reset, stream); + // The columnwise wgrad_input, before the GEMM. It reads the resident dispatched tokens, so it + // needs no readiness signal. + if (requant) { + launch_requant(wgrad_input, scratch, rows, hidden, num_experts, 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_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); + 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 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); + } + + NVTECommWindow no_window{}; + 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, + unsignaled ? nullptr : &combine_signal, ctx.layer_cfg, stream); +} + +} // 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, NVTE_Activation_Type, + 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, + NVTE_Activation_Type, 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..b8009b77df1 --- /dev/null +++ b/transformer_engine/common/ep/ep_gemm_config.h @@ -0,0 +1,307 @@ +/************************************************************************* + * 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 { + +// 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. +constexpr size_t kMxfp8HiddenMultiple = 512; +constexpr size_t kMxfp8FfnMultiple = 256; + +// 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 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: + // 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. + // 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) { + { + std::shared_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) { + std::unique_lock lock(mutex_); + return map_.emplace(key, value).first->second; + } + 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(); + // 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=*/central.get_tvm_ffi_available()); +} + +// 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) { + // 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; + } + 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 token_alignment; // rows per expert slab are a multiple of it + // 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; + // 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; } + + // 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(token_alignment), device_layout, d_col, h, + deterministic); + } + + 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 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 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(token_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"; + + 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 + 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 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(signal_unit_tokens), + static_cast(scaling_mode), static_cast(token_alignment), + static_cast(routed_tokens)); + } + + 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); } +}; + +} // namespace ep +} // namespace transformer_engine + +#endif // TRANSFORMER_ENGINE_COMMON_EP_EP_GEMM_CONFIG_H_ 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..c07239bdfa1 --- /dev/null +++ b/transformer_engine/common/ep/ep_gemm_utils.h @@ -0,0 +1,61 @@ +/************************************************************************* + * 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 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); +} + +// 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"); + NVTE_CHECK(nvte_tensor_numel(expert_token_offsets) == num_experts + 1 && + 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)) + 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 && + nvte_tensor_type(counts) == kNVTEInt64, + "recv_tokens_per_expert must be an int64 tensor of num_experts elements"); + } +} + +} // namespace ep +} // namespace transformer_engine + +#endif // TRANSFORMER_ENGINE_COMMON_EP_EP_GEMM_UTILS_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..d219334f03b --- /dev/null +++ b/transformer_engine/common/ep/ep_overlap_workspace.cu @@ -0,0 +1,104 @@ +/************************************************************************* + * Copyright (c) 2022-2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * + * See LICENSE for license information. + ************************************************************************/ + +#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].iota ? i : reset.fills[f].value; + } + } + } + if (blockIdx.x != 0 || reset.layout == nullptr) { + return; + } + const int64_t num_experts = reset.num_experts; + // 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) { + 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] = 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) { + if (count == 0) { + return; + } + NVTE_CHECK(num_fills < kMaxFills, "too many workspace fills"); + 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) { + // 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()); +} + +// 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) { + 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 new file mode 100644 index 00000000000..ce907e0d23f --- /dev/null +++ b/transformer_engine/common/ep/ep_overlap_workspace.h @@ -0,0 +1,62 @@ +/************************************************************************* + * 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 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 { + 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; + // 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] 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 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; + + // 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. +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 + +#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..3715f4aa6b8 100644 --- a/transformer_engine/common/include/transformer_engine/ep.h +++ b/transformer_engine/common/include/transformer_engine/ep.h @@ -37,6 +37,40 @@ 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; +} 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; + /*! 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; +} NVTEEpOverlapConfig; + /*! \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 @@ -53,7 +87,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 +104,10 @@ 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; + /*! 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, @@ -87,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: @@ -146,12 +190,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. * @@ -214,7 +262,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..0f4ea875b21 --- /dev/null +++ b/transformer_engine/common/include/transformer_engine/ep_gemm.h @@ -0,0 +1,295 @@ +/************************************************************************* + * 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 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 + * nvte_ep_combine_gemm_fwd FC2 combine combine_fwd_num_sms + * nvte_ep_combine_gemm_bwd FC2 dgrad + SwiGLU bwd, wgrad dispatch bwd dispatch_bwd_num_sms + * nvte_ep_dispatch_gemm_bwd FC1 dgrad, wgrad combine bwd combine_bwd_num_sms + * + * Overlap (each call draws its own schedule): + * - Dispatch side: the dispatch leads, signaling each row tile; the GEMM consumes tiles beside + * 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. + * - 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. + * - 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. 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, 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_ +#define TRANSFORMER_ENGINE_EP_GEMM_H_ + +#include +#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. + * + * 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. + * \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] 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] 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] 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 + * rows. + * \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. + * \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, + NVTE_Activation_Type activation, 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. + * + * Requirements: see the file overview. + * + * Schedule (FC2 leads, hidden chunks; combine_fwd_num_sms; time --->): + * FC2 |--- head ---------------| + * combine |--- push chunks -----------| + * + * \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] 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. + * \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_workspace_size returns. + * \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 second GEMM's data gradient, + * SwiGLU backward in its epilogue, overlapped with the backward dispatch. + * + * 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: + * + * 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. + * + * 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. + * + * Schedule (backward dispatch leads, dY tiles; dispatch_bwd_num_sms; time --->): + * bwd dispatch |--- deliver tiles ---| + * dGLU |--- head ------------|--- tail ---| + * + * \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] 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 + * 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, 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. + * \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. + * \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 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); + +/*! \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. + * + * 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 ---| + * FC1 wgrad | |--- other SMs ----------| + * + * \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] 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 + * 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 of the size nvte_ep_overlap_workspace_size returns. + * \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 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, + NVTETensor workspace, const NVTEEpLayerConfig* layer_cfg, + cudaStream_t stream); + +/*! \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. + * \param[in] num_local_experts Experts held by this rank. + * \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; allow_nondeterministic selects the GEMM + * kernels sized, and the size fits either mode. + * \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..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,4 +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. +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_ 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/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_ 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/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 4a582ac24c2..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,10 +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); + bool zero_copy, int64_t num_topk, bool drop_on_overflow, + std::array sm_config, std::array overlap_config); void ep_finalize(); @@ -778,7 +782,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 343e5f2d4c6..760f7e6b985 100644 --- a/transformer_engine/pytorch/csrc/extensions/ep.cpp +++ b/transformer_engine/pytorch/csrc/extensions/ep.cpp @@ -14,15 +14,21 @@ #include #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. @@ -37,6 +43,7 @@ #include "../common.h" #include "../extensions.h" +#include "../pybind.h" #include "transformer_engine/gemm.h" namespace transformer_engine::pytorch { @@ -51,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(); @@ -72,30 +75,28 @@ template size_t symm_mem_window_offset(T* sm, ...) { return sm->get_offset(); } -#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) { -#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; +// 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 { - sm = c10d::symmetric_memory::rendezvous(t, g_ep_group_name); + return 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. + return nullptr; } +} +#endif + +// 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; + 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()); @@ -106,22 +107,34 @@ NVTECommWindow maybe_make_window(const at::Tensor& t) { #endif } -// 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 -// path but turns the "not symm-mem" outcome into a hard error. +// 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, 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; +} + +// With zero-copy enabled, throws unless the named tensor is symm-mem-backed on the EP group. void check_symm_mem_required(const at::Tensor& t, const char* name) { #ifdef NCCL_HAS_SYMMEM_SUPPORT if (!g_zero_copy_enabled.load(std::memory_order_relaxed)) return; NVTE_CHECK(!g_ep_group_name.empty(), "Zero-copy is enabled but EP group name is unset; call ep_initialize first."); - c10::intrusive_ptr 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; @@ -172,6 +185,158 @@ size_t check_mxfp8_scale_pair(const at::Tensor& send_scale, const at::Tensor& re return sc_cols; } +// 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; + } + 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); + if (data.data_ptr == nullptr) { + continue; + } + 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, shape); + } + } + return t; +} + +// 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 t; +} + +// Optional weight gradient of an overlapped backward GEMM and the activations it reads: plain, or +// 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: + 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"); + if (enabled_) { + NVTE_CHECK(weight_grad->is_contiguous(), "weight_grad must be contiguous"); + input_ = operand_tensor(*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"); +} + +// 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; } +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"); + } +} + +// 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); } @@ -191,7 +356,8 @@ 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, + 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"); @@ -212,6 +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(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`` @@ -237,13 +407,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, }; } @@ -258,13 +430,17 @@ 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. - 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 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"); + 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,18 +448,32 @@ 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); + // [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"); + check_dense_cuda(*expert_offsets, "expert_offsets"); + 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 @@ -712,6 +902,298 @@ 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) { + 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 +// ones torch tensors; every operand of a call is of the one kind. The weights are +// [experts, out_features, in_features]. +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); + check_cuda_object("recv_tokens", recv_tokens); + check_cuda_object("act_out", act_out); + auto stream = at::cuda::getCurrentCUDAStream().stream(); + 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->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"); + 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); + 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]"); + 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) == 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"); + 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); + auto topk_weights_te = makeTransformerEngineTensor(topk_weights); + 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 expert_token_offsets_te = makeTransformerEngineTensor(expert_token_offsets); + // 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); + } + 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. + auto workspace_t = overlap_workspace(hidden, ffn, num_experts, recv_rows, false, mxfp8, layer_cfg, + tokens_per_expert); + auto workspace_te = makeTransformerEngineTensor(workspace_t); + { + 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); + } +} + +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) { + check_cuda_operands({{"handle_mem", operand(handle_mem)}, + {"expert_token_offsets", operand(expert_token_offsets)}, + {"expert_out", operand(expert_out)}, + {"result", operand(result)}, + {"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(); + 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); + NVTE_CHECK(gemm_in_te.shape().ndim == 2, "gemm_in must be [rows, ffn]"); + auto weight_te = + 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 && + 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"); + 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); + 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. + 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); +} + +// 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. 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, + 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, bool deterministic) { + check_cuda_operands({{"handle_mem", operand(handle_mem)}, + {"gemm_out", operand(gemm_out)}, + {"recv_topk_weights", operand(recv_topk_weights)}, + {"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); + 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(gemm_out.is_contiguous(), "gemm_out must be contiguous"); + 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 && + 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"); + auto handle_mem_te = makeTransformerEngineTensor(handle_mem); + 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 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); + TensorWrapper act_out_te; + if (act_out.has_value()) { + act_out_te = operand_tensor(*act_out); + } + // The weight is [experts, hidden, ffn], and grad_gemm_out is [rows, 2 * ffn]. + 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), + /*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 = + 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, 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(), 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); +} + +// 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 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, + 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)}, + {"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)}, + {"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_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), + "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 = 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, 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); + 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_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, + 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(), 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); +} + void register_ep_bindings(pybind11::module_& m) { namespace py = pybind11; m.def("ep_initialize", &ep_initialize, @@ -719,7 +1201,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("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."); @@ -731,7 +1215,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"), @@ -746,6 +1230,36 @@ 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; 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("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"), + 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); + 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("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, + 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("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"), + 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); 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..22bdffaa84a 100644 --- a/transformer_engine/pytorch/ep.py +++ b/transformer_engine/pytorch/ep.py @@ -6,8 +6,10 @@ from __future__ import annotations import atexit +import math +import os import warnings -from dataclasses import dataclass +from dataclasses import dataclass, fields from typing import Optional, TYPE_CHECKING import torch @@ -15,11 +17,13 @@ import transformer_engine_torch as tex +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 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). @@ -31,6 +35,8 @@ __all__ = [ "EpConfig", "EpBuffer", + "EpSmConfig", + "EpOverlapConfig", "ep_bootstrap", "get_ep_drop_on_overflow", "get_ep_group", @@ -56,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 @@ -84,11 +100,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. +_SYM_DISPATCH_BUFFERS: Optional[MXFP8TensorStorage] = None @dataclass(frozen=True, slots=True) @@ -125,9 +145,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, _SYM_DISPATCH_BUFFERS if _BOOTSTRAPPED: try: + _SYM_DISPATCH_BUFFERS = None tex.ep_finalize() except Exception: # pylint: disable=broad-exception-caught import traceback @@ -140,6 +161,41 @@ 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. + """ + + 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 + + def ep_bootstrap( ep_group: dist.ProcessGroup, num_experts: int, @@ -151,6 +207,8 @@ def ep_bootstrap( zero_copy: bool = False, 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. @@ -172,9 +230,28 @@ 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=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. ``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() + _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: @@ -216,6 +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), + ), ) _BOOTSTRAPPED = True _EP_GROUP = ep_group @@ -254,6 +343,21 @@ def get_ep_drop_on_overflow() -> Optional[bool]: return bool(_BOOTSTRAP_SETTINGS["drop_on_overflow"]) +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 + 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 + return True + + def _ep_is_eager() -> bool: """Return whether the bootstrapped EP group uses variable-size eager buffers.""" return _EAGER @@ -269,10 +373,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, _SYM_DISPATCH_BUFFERS if not _BOOTSTRAPPED: return try: + _SYM_DISPATCH_BUFFERS = None # Deregister pooled symm-mem windows while the group's comm is still valid. release_symm_mem_pool() tex.ep_finalize() @@ -1084,17 +1189,88 @@ def _alloc_io(shape, dtype: torch.dtype, device, zero_copy: bool) -> torch.Tenso return torch.empty(*shape, dtype=dtype, device=device) +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 + 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 _SYM_DISPATCH_BUFFERS 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." + ) + + shape = (_BOOTSTRAP_SETTINGS["max_tokens_per_rank"], _BOOTSTRAP_SETTINGS["hidden_dim"]) + data_bytes = round_up_to_nearest_multiple(math.prod(shape), 256) + 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) + _SYM_DISPATCH_BUFFERS = _mxfp8_storage( + (window[:data_bytes], window[data_bytes:]), shape, quantizer + ) + return _SYM_DISPATCH_BUFFERS + + +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.") + 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 _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[MXFP8TensorStorage] = None, ) -> tuple[MXFP8TensorStorage, torch.Tensor]: - """Quantize an EP input with a supported quantizer.""" + """Quantize an EP input with a supported quantizer. + + ``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 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 +1280,19 @@ def quantize_for_ep( def _quantize_mxfp8( input_: torch.Tensor | QuantizedTensorStorage, quantizer: "MXFP8Quantizer", + 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 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._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_ elif isinstance(input_, QuantizedTensorStorage): @@ -1118,7 +1301,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(_buffers(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 +1332,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(_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] return quantized, scale_inv diff --git a/transformer_engine/pytorch/ops/fused/__init__.py b/transformer_engine/pytorch/ops/fused/__init__.py index ff1075e6fe2..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,3 +35,4 @@ GroupedMLP_CuTeGEMMUnary, GroupedMLP_CuTeGEMMGLUBf16, ) +from .moe_overlap import FusedMoE # pylint: disable=wrong-import-position diff --git a/transformer_engine/pytorch/ops/fused/grouped_mlp.py b/transformer_engine/pytorch/ops/fused/grouped_mlp.py index e609a6e8bb5..7eb7605f76e 100644 --- a/transformer_engine/pytorch/ops/fused/grouped_mlp.py +++ b/transformer_engine/pytorch/ops/fused/grouped_mlp.py @@ -937,7 +937,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) + # 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, 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..dedb5036444 --- /dev/null +++ b/transformer_engine/pytorch/ops/fused/moe_overlap.py @@ -0,0 +1,1017 @@ +# 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 DType, MXFP8_BLOCK_SCALING_SIZE +from ...cpu_offload import ( + is_cpu_offload_enabled, + mark_activation_offload, + mark_not_offload, + start_offload, +) +from ...ep import ( + EpConfig, + _moe_overlap_available, + _sym_dispatch_buffers, + quantize_for_ep, +) +from ...distributed_weight import is_distributed_weight +from ...quantization import Recipe +from ...tensor.mxfp8_tensor import MXFP8Quantizer +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, + 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``. + - ``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. + - Recipe of none or ``MXFP8BlockScaling``. + + 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. + - 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``) it synchronizes the host and + 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 (an unset transport + 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. + """ + + @classmethod + def is_supported(cls) -> bool: + """Whether this fused operation can run on the current system.""" + return _moe_overlap_available() + + 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 + self._operands = _Mxfp8Operands() if self._mxfp8 else _Bf16Operands() + self._weight_quantizers = {1: {}, 3: {}} + # The dispatch and combine share one EpBuffer; it is read from basic_ops[0] 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] + + 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): + raise TypeError(f"topk_idx must be int32 or int64, got {topk_idx.dtype}.") + 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 + topk_idx = _require_contiguous(topk_idx, "topk_idx") + topk_weights = _require_contiguous(topk_weights, "topk_weights") + tokens_per_expert = buffer.tokens_per_expert + # 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 + )[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. 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], + ) # fmt: skip + 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.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 + recv_tokens, gemm_out, act_out = operands.recv_buffers(rows, hidden, ffn, device) + recv_weights = torch.empty(rows, dtype=torch.float32, device=device) + tex.ep_dispatch_gemm_fwd( + buffer.handle_mem, topk_idx, tokens, topk_weights, operands.forward_weight(w1), + 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 + 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, 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, w1, w2, backward + ) + 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: + """Raise for a setting that can change between calls and the GEMMs do not support.""" + # 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, 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 + 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 = 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. + # 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 + # 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`` + 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, self._weight_quantizers[idx] + ) + return _bf16_weight(fc_op, fc_op.num_groups) + + 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, + ): + # 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 = 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] + 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, expert_token_offsets=expert_token_offsets + ) + + 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, None, "FC2", fc2_wgrad) + 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, 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") + + # 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") + + 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, + 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; + 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 + 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 = expert_token_offsets[1:] + 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 + operands = self._operands + ( + recv_data, recv_scale, gemm_out, recv_weights, w1_col, w1_col_scale, w2_col, + w2_col_scale, + ) = 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 + hidden = buffer.hidden_dim + ffn = fc2_op.in_features + rows = gemm_out.shape[0] + 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.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.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 + # the call writes neither for a frozen weight. + grad_gemm = empty( + 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) + + grad_params = functools.partial( + self._grad_params, device=device, expert_token_offsets=expert_token_offsets + ) + + 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.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 + + def fc1_grad_params(wgrad_args=None): + if not fc1_ctx.weight_requires_grad: + return grad_params(fc1_op, fc1_ctx, None, None, "FC1") + if wgrad_args is not None: + # The call writes the columnwise received rows from their rowwise copy. + 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, + ) + 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, + _with_columnwise_data(recv_tokens, first_dims, expert_token_offsets, operands), + grad_gemm_cols, "FC1", + ) # fmt: skip + + fc2_wgrad = _CallWgrad() + if fc2_ctx.weight_requires_grad: + 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, 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, + deterministic=_deterministic_algorithms_required(), **fc2_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() + + 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.""" + + # 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) + + @staticmethod + def dispatch_input(input_, device): + """Dispatch input and whether the dispatch reads it in place from a symm-mem window.""" + del device + return input_, False + + @staticmethod + def forward_weight(weight): + """GEMM operand of a weight.""" + return weight + + @staticmethod + def recv_buffers(rows, hidden, ffn, device): + """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), + torch.empty(rows, ffn, dtype=torch.bfloat16, device=device), + ) + + @staticmethod + 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 + + @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 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), () + + +class _Mxfp8Operands: + """Operands of the forward GEMM calls with MXFP8 GEMMs and EP transport.""" + + fc1_wgrad_inputs = (0, 1) + fc2_wgrad_inputs = () + offload_slots = (0, 1, 2) + + def __init__(self) -> None: + # 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): + """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 + def forward_weight(weight): + """Rowwise MXFP8 operand of a weight.""" + return weight.rowwise + + def recv_buffers(self, rows, hidden, ffn, device): + """MXFP8 recv tokens, BF16 GEMM output and MXFP8 activation output.""" + return ( + 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), + ) + + @staticmethod + def combine_recv_weights(recv_weights): + """The routing weights scale the second GEMM's output rows.""" + return recv_weights + + @staticmethod + 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._rowwise_data, + recv_tokens._rowwise_scale_inv, + gemm_out, + recv_weights, + ), ( + ( + w1.columnwise._columnwise_data, + w1.columnwise._columnwise_scale_inv, + w2.columnwise._columnwise_data, + w2.columnwise._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; a quantized gradient is dequantized.""" + 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.""" + + 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(wgrad_input, grouped_dy, wgrad_output): + del grouped_dy + self.update( + wgrad_input=wgrad_input, + 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 _MxFp8WeightOperands(NamedTuple): + """MXFP8 operands of a weight [num_groups, out_features, in_features]: rowwise and, when + prepared for the backward, columnwise.""" + + rowwise: MXFP8TensorStorage + columnwise: Optional[MXFP8TensorStorage] = None + + +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 _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 _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, 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 + grouped = GroupedTensorStorage( + shape=(rows, hidden), dtype=torch.bfloat16, num_tensors=first_dims.numel(), + 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 + tex.group_requantize_inplace( + grouped, operands.gemm_both, first_dims.numel(), first_dims, DType.kBFloat16, + tensor_offsets=grouped.tensor_offsets, + ) # fmt: skip + return grouped + + +def _mxfp8_weight_operands( + fc_op: GroupedLinear, num_groups: int, columnwise: bool, quantizer_cache: dict +) -> _MxFp8WeightOperands: + """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. + 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() + tex.grouped_swizzle_for_gemm(weight, rowwise=True, columnwise=columnwise) + else: + 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 + ) + 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: + """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) + + +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. It checks the device and the static settings; those + that can change between calls are checked when the op runs. + + 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``; must be 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 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. + """ + 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 and NVTE_MOE_OVERLAP=1" + ) + if config.payload_dtype is not torch.bfloat16: + return "needs a BF16 payload" + 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: + if not isinstance(recipe, MXFP8BlockScaling): + 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"): + 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 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}" + 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 != _GLU_BLOCK: + return f"needs glu_interleave_size {_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 + + +@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 + 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" + 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" + 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( # pylint: disable=unused-argument + ops: list[FusibleOperation], + *, + recipe=None, + **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.""" + 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)