From 831f8bf6c97b1b3451c356955eac3db62b8a278a Mon Sep 17 00:00:00 2001 From: ziyixiong-nv <219238287+ziyixiong-nv@users.noreply.github.com> Date: Tue, 17 Nov 2026 23:40:44 +0000 Subject: [PATCH] [TRTLLM-16622][perf] DeepSeek-V4.1: MoE decode at attention TP with FC1-only TRTLLM-Gen runs, a CuTe DSL FC2, one-cluster routing and dynamic EP DeepSeek-V4.1 decode at attention TP spends its MoE time in small TRTLLM-Gen calls whose FC2 cubins run in rounds and whose routing sits on the critical path. This change builds on the FC1-only TRTLLM-Gen run and the bit-identical CuTe DSL FC2 (moe_lowm_fc2, decode_moe) of #21997: - MoEDecodeOptions.cute_fc2_rows lets a model take that CuTe FC2 alone, without the decode tuning and engine: un-finalized attention-TP calls of up to that many rows on SM100/SM103, also on the runner's routing tables (FC1-only run_moe_routing_tables_fc1 and run_moe_bounded_fc1). - moe_lowm_fc2 re-applies the +0 of a cubin's zero-filled K tail where it has no tail of its own, so it also stands in for the FC2 cubins with 512-column K tiles. - Routes up to 8 tokens (384 experts, top-6) in one 8-CTA cluster that also lays out TRTLLM-Gen's routing tables with one warp and releases the expert GEMM right after its wait. - Splits each call's used experts home-first over the two EP ranks on batch-1 workers (dynamic EP); both ranks hold their MoE-TP shard of all routed experts, and the GEMMs launch with the dynamic tables' CTA bound (run_moe_bounded) instead of the worst case. ModelConfig carries the executor's max_batch_size for this (filled by the model loader; no LLM API change). - Serves the router GEMM as K-chunk partials from 12 rows per rank instead of 65 on SM100/SM103 for a model that opts in; every other caller keeps 65. Gating: DeepSeek-V4.1 declares MoEDecodeOptions(cute_fc2_rows=16, one_cluster_route=True) and sets extra_attrs "moe_dynamic_ep" (which also needs attention TP, MoE EP2 with MoE TP >= 4, batch-1 workers, sqrt-softplus routing, TRTLLM-Gen NVFP4 and no EPLB or DWDP, on SM100/SM103) and "moe_router_partials_small_m". The one-cluster route kernel takes the 384-expert top-6 tables: bit-identical to the CuTe route kernel's up to the row order in an expert's block. Qwen3.5 and every other model, DeepSeek-V4 included, keep their kernels and outputs, except that the shared CuTe FC2 now adds a 512-column K tile cubin's +0 tail where the intermediate size is an odd multiple of 256 (an exactly zero output takes the cubin's sign); SM107 is unchanged. The MXFP4 x MXFP8 runner is unchanged: its CuTe FC2 is left to #22371, which needs it for the DSpark draft's MXFP4 experts. Numerics: bit-identical, except that dynamic EP changes which rows fall into each rank's BF16 partial (FP32 summation order, like an EPLB placement change): the all-reduced MoE output stays within 8.7e-3 of the call's largest value of the static split's. Measured on GB300, DeepSeek-V4.1 decode at TEP8 batch 1 with DSpark (k=5): - CuTe FC2 with the one-cluster route kernel: decode step 2.803 / 2.777 -> 2.670 ms. - Dynamic EP: MoE half of a layer -1.44 us (-58 us per step); EP-rank imbalance 2.8 -> 0.7 us. - Early GEMM release and one-warp tables: -10..-30 us and -11 us per step. - CTA-bounded GEMMs: FC1 grid 324 -> 162 CTAs at 6 rows; FC2 no longer waits for FC1's end. Router partials from 12 rows, DEP32 at 48 rows per rank: step 7.06 -> 7.00 ms (-0.9%). Tests: test_moe_lowm_fc2.py adds the opt-in on the one-cluster route kernel's tables against the FC2 cubin (eager and CUDA graph replay) and a 768-column shape; test_one_cluster_route_matches_the_cute_kernel; test_moe_ep_dynamic_matches_static_split (4 GPUs, dynamic against static split, both route kernels, finalized and un-finalized, CUDA graph replay; GB200 pre-merge, GB300 post-merge); test_megamoe_e2e gains the 48-row shape for the router partials. Signed-off-by: ziyixiong-nv <219238287+ziyixiong-nv@users.noreply.github.com> --- .../kernels/moe/trtllmGen/runner.cu | 18 +- .../kernels/moe/trtllmGen/runner.h | 8 +- .../thop/moe/trtllmGen/fp4BlockScaleMoe.cpp | 115 +++- .../custom_ops/router_logit_partials.py | 13 +- .../custom_ops/trtllm_gen_custom_ops.py | 343 ++++++---- .../_torch/kernels/blackwell/moe_lowm_fc2.py | 70 +- tensorrt_llm/_torch/model_config.py | 2 + .../_torch/models/modeling_deepseekv4.py | 10 +- .../_torch/models/modeling_deepseekv41.py | 17 +- .../moe/fused_moe/MOE_DEVELOPER_GUIDE.md | 2 +- .../_torch/moe/fused_moe/configurable_moe.py | 45 ++ .../_torch/moe/fused_moe/impl_contract.py | 9 +- .../_torch/moe/fused_moe/moe_op_backend.py | 19 +- .../_torch/moe/fused_moe/trtllm_gen/base.py | 7 +- .../moe/fused_moe/trtllm_gen/decode_moe.py | 156 ++++- .../fused_moe/trtllm_gen/fp4_block_scale.py | 13 +- .../moe/fused_moe/trtllm_gen/trtllm_nvfp4.py | 44 +- .../moe/kernels/blackwell/dsv4_route_one.py | 604 ++++++++++++++++++ .../moe/kernels/blackwell/dsv4_route_quant.py | 161 ++++- .../_torch/pyexecutor/model_loader.py | 1 + tests/integration/defs/.test_durations | 2 + .../test-db/l0_gb200_multi_gpus.yml | 2 + .../test-db/l0_gb300_multi_gpus.yml | 2 + .../modeling/test_modeling_deepseekv4.py | 1 + .../_torch/moe/test_dsv4_route_quant.py | 92 +++ tests/unittest/_torch/moe/test_megamoe_e2e.py | 23 +- .../_torch/moe/test_moe_ep_dynamic.py | 233 +++++++ .../unittest/_torch/moe/test_moe_lowm_fc2.py | 152 ++++- 28 files changed, 1944 insertions(+), 220 deletions(-) create mode 100644 tensorrt_llm/_torch/moe/kernels/blackwell/dsv4_route_one.py create mode 100644 tests/unittest/_torch/moe/test_moe_ep_dynamic.py diff --git a/cpp/tensorrt_llm/kernels/moe/trtllmGen/runner.cu b/cpp/tensorrt_llm/kernels/moe/trtllmGen/runner.cu index ec2b618e3087..57b0b3626e91 100644 --- a/cpp/tensorrt_llm/kernels/moe/trtllmGen/runner.cu +++ b/cpp/tensorrt_llm/kernels/moe/trtllmGen/runner.cu @@ -24,6 +24,8 @@ #include #include +#include + TRTLLM_NAMESPACE_BEGIN namespace kernels @@ -493,9 +495,13 @@ void Runner::run(void* hiddenState, void* hiddenStateScale, void* weights, void* int32_t numExperts, int32_t numTokens, int32_t* permutedIdxToTokenIdx, int32_t* ptrNumNonExitingCtas, int32_t* ptrTotalNumPaddedTokens, int32_t* ptrCtaIdxXyToBatchIdx, int32_t* ptrCtaIdxXyToMnLimit, void* bmm1Workspace, bool useRoutingScalesOnInput, int device, cudaStream_t stream, int32_t configIndex, - int32_t validHiddenSize, int32_t validIntermediateSize) + int32_t validHiddenSize, int32_t validIntermediateSize, int32_t maxNumCtasInBatchDim) { auto maxNumCgasInBatchDim = Routing::getMaxNumCgasInBatchDim(numTokens, topK, numExperts, mTileTokensDim); + if (maxNumCtasInBatchDim > 0) + { + maxNumCgasInBatchDim = std::min(maxNumCgasInBatchDim, maxNumCtasInBatchDim); + } bool is_gated_activation = tensorrt_llm::kernels::isGatedActType(mActType); int32_t intermediateSizeFactor = (is_gated_activation ? 2 : 1); mRunner.run(numTokens, intermediateSizeFactor * intermediateSize, hiddenSize, numTokens, @@ -590,9 +596,13 @@ void Runner::run(void* permutedHiddenState, void* permutedHiddenStateScale, void int32_t intermediateSize, int32_t numExperts, int32_t numTokens, int32_t* ptrNumNonExitingCtas, int32_t* ptrTotalNumPaddedTokens, int32_t* ptrCtaIdxXyToBatchIdx, int32_t* ptrCtaIdxXyToMnLimit, void* bmm2Workspace, int device, cudaStream_t stream, int32_t configIndex, int32_t validHiddenSize, - int32_t validIntermediateSize) + int32_t validIntermediateSize, int32_t maxNumCtasInBatchDim) { auto maxNumCgasInBatchDim = Routing::getMaxNumCgasInBatchDim(numTokens, topK, numExperts, mTileTokensDim); + if (maxNumCtasInBatchDim > 0) + { + maxNumCgasInBatchDim = std::min(maxNumCgasInBatchDim, maxNumCtasInBatchDim); + } mRunner.run(numTokens, hiddenSize, intermediateSize, numTokens, validHiddenSize, validIntermediateSize, {}, numTokens, numExperts, maxNumCgasInBatchDim, permutedHiddenState, permutedHiddenStateScale, weights, weightsScale, /* perTokensSfA */ nullptr, @@ -842,7 +852,7 @@ void Runner::run( workspace.cta_idx_xy_to_batch_idx, workspace.cta_idx_xy_to_mn_limit, workspace.bmm1_workspace, args.mUseRoutingScalesOnInput, device, stream, config.gemm1Config, args.valid_hidden_size.value_or(args.hidden_size), - args.valid_intermediate_size.value_or(args.intermediate_size)); + args.valid_intermediate_size.value_or(args.intermediate_size), args.max_num_ctas_in_batch_dim); // We do not fuse activation with FC1 for DeepSeek FP8 due to the weights shuffling constraint. TLLM_CHECK_WITH_INFO(!args.skip_gemm2 || !args.do_finalize, "skip_gemm2 requires do_finalize == false."); @@ -869,7 +879,7 @@ void Runner::run( workspace.num_non_exiting_ctas, workspace.total_num_padded_tokens, workspace.cta_idx_xy_to_batch_idx, workspace.cta_idx_xy_to_mn_limit, workspace.bmm2_workspace, device, stream, config.gemm2Config, args.valid_hidden_size.value_or(args.hidden_size), - args.valid_intermediate_size.value_or(args.intermediate_size)); + args.valid_intermediate_size.value_or(args.intermediate_size), args.max_num_ctas_in_batch_dim); // Run finalize if (args.do_finalize) diff --git a/cpp/tensorrt_llm/kernels/moe/trtllmGen/runner.h b/cpp/tensorrt_llm/kernels/moe/trtllmGen/runner.h index 3afb022f7a48..0e92408ab193 100644 --- a/cpp/tensorrt_llm/kernels/moe/trtllmGen/runner.h +++ b/cpp/tensorrt_llm/kernels/moe/trtllmGen/runner.h @@ -227,7 +227,8 @@ class Runner int32_t intermediateSize, int32_t numExperts, int32_t numTokens, int32_t* permutedIdxToTokenIdx, int32_t* ptrNumNonExitingCtas, int32_t* ptrTotalNumPaddedTokens, int32_t* ptrCtaIdxXyToBatchIdx, int32_t* ptrCtaIdxXyToMnLimit, void* bmm1Workspace, bool useRoutingScalesOnInput, int device, - cudaStream_t stream, int32_t configIndex, int32_t validHiddenSize = -1, int32_t validIntermediateSize = -1); + cudaStream_t stream, int32_t configIndex, int32_t validHiddenSize = -1, int32_t validIntermediateSize = -1, + int32_t maxNumCtasInBatchDim = 0); private: int32_t mTileTokensDim; @@ -266,7 +267,7 @@ class Runner int32_t intermediateSize, int32_t numExperts, int32_t numTokens, int32_t* ptrNumNonExitingCtas, int32_t* ptrTotalNumPaddedTokens, int32_t* ptrCtaIdxXyToBatchIdx, int32_t* ptrCtaIdxXyToMnLimit, void* bmm2Workspace, int device, cudaStream_t stream, int32_t configIndex, int32_t validHiddenSize = -1, - int32_t validIntermediateSize = -1); + int32_t validIntermediateSize = -1, int32_t maxNumCtasInBatchDim = 0); private: int32_t mTileTokensDim; @@ -355,6 +356,9 @@ struct MoERunnerArgs // Stop after FC1 (+ activation): the caller runs FC2 on workspace.gemm1_output / gemm1_output_scale with the // routing tables. Requires do_finalize == false. bool skip_gemm2{false}; + + // The most CTAs the caller's routing puts in the batch dimension, or 0 for the worst case of the problem. + int32_t max_num_ctas_in_batch_dim{0}; }; struct MoEWorkspace diff --git a/cpp/tensorrt_llm/thop/moe/trtllmGen/fp4BlockScaleMoe.cpp b/cpp/tensorrt_llm/thop/moe/trtllmGen/fp4BlockScaleMoe.cpp index 3d77c97321f1..71887095ee28 100644 --- a/cpp/tensorrt_llm/thop/moe/trtllmGen/fp4BlockScaleMoe.cpp +++ b/cpp/tensorrt_llm/thop/moe/trtllmGen/fp4BlockScaleMoe.cpp @@ -61,7 +61,7 @@ std::vector run_fp4_block_scale_moe_runner(torch::optional const& topk_weights, torch::optional const& topk_ids, torch::optional const& out_tensor = torch::nullopt, PreRoutedBuffers const* prerouted = nullptr, - bool const fc1_only = false) + bool const fc1_only = false, int64_t const prerouted_max_ctas = 0) { // fc1_only: routing (unless pre-routed) and FC1 only; the caller runs FC2 into the returned gemm2 output, which // keeps the do_finalize == false contract (gemm2 output, expert weights, expanded -> permuted index). @@ -230,6 +230,12 @@ std::vector run_fp4_block_scale_moe_runner(torch::optional 0) + { + args.max_num_ctas_in_batch_dim = static_cast(std::min(max_num_ctas, prerouted_max_ctas)); + } if (prerouted != nullptr) { // The kernels launch on the device of hidden_states and read these buffers directly. @@ -553,24 +559,19 @@ std::vector run_fp4_block_scale_moe_runner(torch::optional runRoutingTablesFc1(torch::optional const& routing_logits, + torch::optional const& routing_bias, torch::Tensor const& hidden_states, + torch::Tensor const& hidden_states_scale, torch::Tensor const& gemm1_weights, + torch::Tensor const& gemm1_weights_scale, std::optional const& gemm1_bias, + std::optional const& gemm1_alpha, std::optional const& gemm1_beta, + std::optional const& gemm1_clamp_limit, torch::Tensor const& gemm2_weights, + torch::Tensor const& gemm2_weights_scale, torch::Tensor const& output1_scales_scalar, + torch::Tensor const& output1_scales_gate_scalar, torch::Tensor const& output2_scales_scalar, + int64_t const num_experts, int64_t const top_k, std::optional const n_group, + std::optional const topk_group, int64_t const intermediate_size, int64_t const local_expert_offset, + int64_t const local_num_experts, std::optional const routed_scaling_factor, + int64_t const routing_method_type, std::vector moeConfigIndex, + torch::optional const& topk_weights, torch::optional const& topk_ids, + torch::Tensor const& routing_tables, std::vector const& routing_table_tiles) + { + return runImpl(routing_logits, routing_bias, hidden_states, hidden_states_scale, gemm1_weights, + gemm1_weights_scale, gemm1_bias, gemm1_alpha, gemm1_beta, gemm1_clamp_limit, gemm2_weights, + gemm2_weights_scale, std::nullopt, output1_scales_scalar, output1_scales_gate_scalar, output2_scales_scalar, + num_experts, top_k, n_group, topk_group, intermediate_size, local_expert_offset, local_num_experts, + routed_scaling_factor, routing_method_type, /*do_finalize=*/false, moeConfigIndex, topk_weights, topk_ids, + torch::nullopt, /*prerouted=*/nullptr, /*routing_tile_n=*/-1, routing_tables, routing_table_tiles, + /*fc1_only=*/true); + } + + // runRoutingTables() on tables that put at most routing_max_ctas CTAs in the batch dimension of any tile; the + // GEMMs launch that many instead of the worst case. + [[nodiscard]] std::vector runBounded(torch::optional const& routing_logits, + torch::optional const& routing_bias, torch::Tensor const& hidden_states, + torch::Tensor const& hidden_states_scale, torch::Tensor const& gemm1_weights, + torch::Tensor const& gemm1_weights_scale, std::optional const& gemm1_bias, + std::optional const& gemm1_alpha, std::optional const& gemm1_beta, + std::optional const& gemm1_clamp_limit, torch::Tensor const& gemm2_weights, + torch::Tensor const& gemm2_weights_scale, std::optional const& gemm2_bias, + torch::Tensor const& output1_scales_scalar, torch::Tensor const& output1_scales_gate_scalar, + torch::Tensor const& output2_scales_scalar, int64_t const num_experts, int64_t const top_k, + std::optional const n_group, std::optional const topk_group, int64_t const intermediate_size, + int64_t const local_expert_offset, int64_t const local_num_experts, + std::optional const routed_scaling_factor, int64_t const routing_method_type, bool const do_finalize, + std::vector moeConfigIndex, torch::optional const& topk_weights, + torch::optional const& topk_ids, torch::optional const& output, + torch::Tensor const& routing_tables, std::vector const& routing_table_tiles, + int64_t const routing_max_ctas) + { + return runImpl(routing_logits, routing_bias, hidden_states, hidden_states_scale, gemm1_weights, + gemm1_weights_scale, gemm1_bias, gemm1_alpha, gemm1_beta, gemm1_clamp_limit, gemm2_weights, + gemm2_weights_scale, gemm2_bias, output1_scales_scalar, output1_scales_gate_scalar, output2_scales_scalar, + num_experts, top_k, n_group, topk_group, intermediate_size, local_expert_offset, local_num_experts, + routed_scaling_factor, routing_method_type, do_finalize, moeConfigIndex, topk_weights, topk_ids, output, + /*prerouted=*/nullptr, /*routing_tile_n=*/-1, routing_tables, routing_table_tiles, + /*fc1_only=*/false, routing_max_ctas); + } + + // runBounded() up to FC1 + activation, with the arguments and outputs of runFc1. + [[nodiscard]] std::vector runBoundedFc1(torch::optional const& routing_logits, + torch::optional const& routing_bias, torch::Tensor const& hidden_states, + torch::Tensor const& hidden_states_scale, torch::Tensor const& gemm1_weights, + torch::Tensor const& gemm1_weights_scale, std::optional const& gemm1_bias, + std::optional const& gemm1_alpha, std::optional const& gemm1_beta, + std::optional const& gemm1_clamp_limit, torch::Tensor const& gemm2_weights, + torch::Tensor const& gemm2_weights_scale, torch::Tensor const& output1_scales_scalar, + torch::Tensor const& output1_scales_gate_scalar, torch::Tensor const& output2_scales_scalar, + int64_t const num_experts, int64_t const top_k, std::optional const n_group, + std::optional const topk_group, int64_t const intermediate_size, int64_t const local_expert_offset, + int64_t const local_num_experts, std::optional const routed_scaling_factor, + int64_t const routing_method_type, std::vector moeConfigIndex, + torch::optional const& topk_weights, torch::optional const& topk_ids, + torch::Tensor const& routing_tables, std::vector const& routing_table_tiles, + int64_t const routing_max_ctas) + { + return runImpl(routing_logits, routing_bias, hidden_states, hidden_states_scale, gemm1_weights, + gemm1_weights_scale, gemm1_bias, gemm1_alpha, gemm1_beta, gemm1_clamp_limit, gemm2_weights, + gemm2_weights_scale, std::nullopt, output1_scales_scalar, output1_scales_gate_scalar, output2_scales_scalar, + num_experts, top_k, n_group, topk_group, intermediate_size, local_expert_offset, local_num_experts, + routed_scaling_factor, routing_method_type, /*do_finalize=*/false, moeConfigIndex, topk_weights, topk_ids, + torch::nullopt, /*prerouted=*/nullptr, /*routing_tile_n=*/-1, routing_tables, routing_table_tiles, + /*fc1_only=*/true, routing_max_ctas); + } + // run() with caller-computed routing tables for tile routing_tile_n (see PreRoutedBuffers), used in place of the // routing kernel when the tactic's tile matches. EP problems are passed all-local (num_experts = local_num_experts, // local_expert_offset = 0, -1 for other ranks' routes) with topk_ids / topk_weights and no routing_logits. @@ -858,7 +938,7 @@ class FP4BlockScaleMoeRunner : public torch::CustomClassHolder torch::optional const& topk_ids, torch::optional const& output, PreRoutedBuffers const* prerouted, int64_t const routing_tile_n, torch::optional const& routing_tables, std::vector const& routing_table_tiles, - bool const fc1_only) + bool const fc1_only, int64_t const routing_max_ctas = 0) { int64_t tileN = moeConfigIndex[0]; int64_t config = moeConfigIndex[1]; @@ -895,6 +975,7 @@ class FP4BlockScaleMoeRunner : public torch::CustomClassHolder // routing_tables [tiles, 5, width]: per tile the PreRoutedBuffers rows, the last holding (num_non_exiting_ctas, // total_num_padded_tokens). Only this tactic's tile is used; other tiles route as usual. std::optional tables; + int64_t tables_max_ctas = 0; if (routing_tables.has_value()) { auto const& all = routing_tables.value(); @@ -907,6 +988,7 @@ class FP4BlockScaleMoeRunner : public torch::CustomClassHolder auto const t = all.select(0, std::distance(routing_table_tiles.begin(), it)); tables = PreRoutedBuffers{t[0], t[1], t[2], t[3], t[4].narrow(0, 0, 1), t[4].narrow(0, 1, 1)}; prerouted = &tables.value(); + tables_max_ctas = routing_max_ctas; } } return run_fp4_block_scale_moe_runner(routing_logits, routing_bias, hidden_states, hidden_states_scale, @@ -914,7 +996,7 @@ class FP4BlockScaleMoeRunner : public torch::CustomClassHolder gemm2_weights_scale, gemm2_bias, output1_scales_scalar, output1_scales_gate_scalar, output2_scales_scalar, num_experts, top_k, n_group, topk_group, intermediate_size, local_expert_offset, local_num_experts, routed_scaling_factor, tileN, routing_method_type, do_finalize, mDtypeElt, *runner, configToRun, - topk_weights, topk_ids, output, prerouted, fc1_only); + topk_weights, topk_ids, output, prerouted, fc1_only, tables_max_ctas); } std::vector const mSupportedTileN; @@ -1038,6 +1120,9 @@ TORCH_LIBRARY_FRAGMENT(trtllm, m) .def("run_moe_routing_tables", &tensorrt_llm::torch_ext::FP4BlockScaleMoeRunner::runRoutingTables) .def("run_moe_prerouted", &tensorrt_llm::torch_ext::FP4BlockScaleMoeRunner::runPrerouted) .def("run_moe_fc1", &tensorrt_llm::torch_ext::FP4BlockScaleMoeRunner::runFc1) + .def("run_moe_routing_tables_fc1", &tensorrt_llm::torch_ext::FP4BlockScaleMoeRunner::runRoutingTablesFc1) + .def("run_moe_bounded", &tensorrt_llm::torch_ext::FP4BlockScaleMoeRunner::runBounded) + .def("run_moe_bounded_fc1", &tensorrt_llm::torch_ext::FP4BlockScaleMoeRunner::runBoundedFc1) .def("run_moe_prerouted_fc1", &tensorrt_llm::torch_ext::FP4BlockScaleMoeRunner::runPreroutedFc1) .def("get_gemm2_kernel_name", &tensorrt_llm::torch_ext::FP4BlockScaleMoeRunner::getGemm2KernelName) .def("get_gemm2_kernel_options", &tensorrt_llm::torch_ext::FP4BlockScaleMoeRunner::getGemm2KernelOptions) diff --git a/tensorrt_llm/_torch/custom_ops/router_logit_partials.py b/tensorrt_llm/_torch/custom_ops/router_logit_partials.py index fecb65fae468..1221a1320dcf 100644 --- a/tensorrt_llm/_torch/custom_ops/router_logit_partials.py +++ b/tensorrt_llm/_torch/custom_ops/router_logit_partials.py @@ -14,9 +14,14 @@ import torch +from tensorrt_llm._utils import is_blackwell_datacenter + # Token counts served by partials (up to the hi GEN batch, 320 requests x 4 rows); the router GEMM keeps its # other paths outside them. MIN_ROWS = 65 +# Fewest rows for callers that opt in (``small_m``) on SM100/SM103: below them the small-M +# warp-MMA router GEMM is faster. +SMALL_M_MIN_ROWS = 12 MAX_ROWS = 1280 @@ -53,11 +58,13 @@ def num_splits(num_tokens: int, num_experts: int) -> int: return 8 if num_logits <= 256 * 384 else 4 if num_logits <= 768 * 384 else 2 -def applies(x: torch.Tensor, weight: torch.Tensor) -> bool: - """Whether ``router_logit_partials`` serves ``x @ weight.T``.""" +def applies(x: torch.Tensor, weight: torch.Tensor, small_m: bool = False) -> bool: + """Whether ``router_logit_partials`` serves ``x @ weight.T``; with ``small_m`` from + ``SMALL_M_MIN_ROWS`` rows on SM100/SM103.""" num_tokens, hidden = x.shape + min_rows = SMALL_M_MIN_ROWS if small_m and is_blackwell_datacenter() else MIN_ROWS return ( - MIN_ROWS <= num_tokens <= MAX_ROWS + min_rows <= num_tokens <= MAX_ROWS and x.is_cuda and x.dtype == torch.bfloat16 and weight.dtype == torch.bfloat16 diff --git a/tensorrt_llm/_torch/custom_ops/trtllm_gen_custom_ops.py b/tensorrt_llm/_torch/custom_ops/trtllm_gen_custom_ops.py index 6ffc16ed91c7..66104dfcd78c 100644 --- a/tensorrt_llm/_torch/custom_ops/trtllm_gen_custom_ops.py +++ b/tensorrt_llm/_torch/custom_ops/trtllm_gen_custom_ops.py @@ -450,6 +450,7 @@ class FP4BlockScaleMoERunner(TunableRunner): decode_tuning = False decode_early_release_rows = 0 decode_spare_sms = 0 + cute_fc2_rows = 0 def __init__(self, num_experts: int, @@ -467,7 +468,8 @@ def __init__(self, use_dp: bool = False, decode_tuning: bool = False, decode_early_release_rows: int = 0, - decode_spare_sms: int = 0): + decode_spare_sms: int = 0, + cute_fc2_rows: int = 0): self.num_experts = num_experts self.top_k = top_k @@ -486,6 +488,10 @@ def __init__(self, self.decode_tuning = decode_tuning self.decode_early_release_rows = decode_early_release_rows self.decode_spare_sms = decode_spare_sms + # Declared by the model (MoEDecodeOptions.cute_fc2_rows): un-finalized calls of up to that many rows run + # their FC2 on the CuTe DSL kernel without the other decode kernels (decode_moe.cute_fc2_opt_in). + self.cute_fc2_rows = cute_fc2_rows + self.use_dp = use_dp self.tuning_config = FP4BlockScaleMoERunner.get_tuning_config( self.num_experts // self.local_num_experts, @@ -511,17 +517,19 @@ def get_runner(self): return FP4BlockScaleMoERunner.runner_dict[instance_key] def forward( - self, - inputs: List[torch.Tensor], - tactic: List[int] = [-1, -1], - output: Optional[torch.Tensor] = None, - prerouted: Optional[Tuple[List[torch.Tensor], torch.Tensor, - torch.Tensor]] = None, - engine_state: Optional[torch.Tensor] = None, - lamport_out: Optional[torch.Tensor] = None, - candidates: Optional[torch.Tensor] = None, - routing_tables: Optional[torch.Tensor] = None, - routing_tiles: Tuple[int, ...] = (), + self, + inputs: List[torch.Tensor], + tactic: List[int] = [-1, -1], + output: Optional[torch.Tensor] = None, + prerouted: Optional[Tuple[List[torch.Tensor], torch.Tensor, + torch.Tensor]] = None, + engine_state: Optional[torch.Tensor] = None, + lamport_out: Optional[torch.Tensor] = None, + candidates: Optional[torch.Tensor] = None, + routing_tables: Optional[torch.Tensor] = None, + routing_tiles: Tuple[int, ...] = (), + dynamic_inputs: Optional[List[torch.Tensor]] = None, + routing_max_ctas: int = 0, ) -> torch.Tensor: """``prerouted``: (routing tables for ``tactic``'s tile, top-k ids, BF16 top-k weights); the tables number this rank's experts from 0 (-1: @@ -535,15 +543,30 @@ def forward( ``ENGINE``, which fills ``prerouted`` from them. ``routing_tables`` ([tiles, 5, width], one per tile of ``routing_tiles``) replace the routing kernel for tactics of those tiles; other tiles route in the - runner (the decode kernels do not take them).""" + runner (the decode kernels do not take them). ``dynamic_inputs``: + ``inputs`` with every expert's weights; ``routing_tables`` then assign + this call's share of all of them (with another tile's tactic replaced + by one of a table tile, as every rank must run the assignment); without + tables the call runs ``inputs``, the static slot range. + ``routing_max_ctas`` > 0 bounds the CTAs the tables assign: the GEMMs + launch that many.""" assert isinstance(tactic, list) + local_num_experts = self.local_num_experts + if dynamic_inputs is not None and routing_tables is not None: + inputs = dynamic_inputs + local_num_experts = dynamic_inputs[4].shape[0] + if tactic[0] not in routing_tiles: + tactic = self._table_tactic(inputs, local_num_experts, + routing_tiles) args = FP4BlockScaleMoEInputs(*inputs) kernel_runner = self.get_runner() # The positional arguments of the runner's run_moe / run_moe_prerouted # (fp4BlockScaleMoe.cpp; decode_moe.GEMM2_BIAS_ARG and its siblings - # name the ones its FC1-only entries drop). + # name the ones its FC1-only entries drop), then those of the entry's + # routing tables. run_args: Tuple[object, ...] + table_args: Tuple[object, ...] = () if prerouted is not None: tables, topk_ids, topk_weights = prerouted run_args = ( @@ -557,16 +580,18 @@ def forward( self.local_num_experts, self.routed_scaling_factor, self.routing_method_type, self.do_finalize, tactic, topk_weights, topk_ids, output, *tables, tactic[0]) - run = kernel_runner.run_moe_prerouted + entry = "run_moe_prerouted" else: num_experts, local_expert_offset = self.num_experts, self.local_expert_offset - if routing_tables is not None and self.local_num_experts != self.num_experts: + if routing_tables is not None and local_num_experts != self.num_experts: if tactic[0] in routing_tiles: # Tables number this rank's experts from 0: to the runner they are all its experts. - num_experts, local_expert_offset = self.local_num_experts, 0 + num_experts, local_expert_offset = local_num_experts, 0 else: # Routing in the runner needs the global numbering. routing_tables = None + elif routing_tables is not None: + local_expert_offset = 0 run_args = (args.routing_logits, args.routing_bias, args.hidden_states, args.hidden_states_scale, args.gemm1_weights, args.gemm1_weights_scale, @@ -577,24 +602,63 @@ def forward( args.output1_scale_gate_scalar, args.output2_scale_scalar, num_experts, self.top_k, self.n_group, self.topk_group, self.intermediate_size, - local_expert_offset, self.local_num_experts, + local_expert_offset, local_num_experts, self.routed_scaling_factor, self.routing_method_type, self.do_finalize, tactic, args.topk_weights, args.topk_ids, output) - run = kernel_runner.run_moe + entry = "run_moe" if routing_tables is not None: if self.decode_tuning or candidates is not None: raise ValueError( "routing tables do not combine with the decode kernels") - return kernel_runner.run_moe_routing_tables( - *run_args, routing_tables, list(routing_tiles)) - if not self.decode_tuning and candidates is None: - # Every model's call (no decode kernels declared): the runner's - # own kernels; a Lamport buffer only goes to ENGINE / CUTE_FC2. - return run(*run_args) - return self._forward_decode(args, kernel_runner, run, run_args, tactic, - output, prerouted, engine_state, - lamport_out, candidates) + entry = "run_moe_routing_tables" + table_args = (routing_tables, list(routing_tiles)) + if routing_max_ctas > 0: + entry = "run_moe_bounded" + table_args = (*table_args, routing_max_ctas) + run = getattr(kernel_runner, entry) + if self.decode_tuning or candidates is not None: + return self._forward_decode(args, kernel_runner, run, run_args, + tactic, output, prerouted, engine_state, + lamport_out, candidates) + if self.cute_fc2_rows > 0: + from ..moe.fused_moe.trtllm_gen import decode_moe + tile_k = decode_moe.cute_fc2_opt_in( + kernel_runner, + self.act_type, + tactic, + args, + top_k=self.top_k, + intermediate_size=self.intermediate_size, + rows=self.cute_fc2_rows, + use_dp=self.use_dp, + do_finalize=self.do_finalize, + output=output) + if tile_k is not None: + fc1 = getattr(kernel_runner, entry + "_fc1") + fc1_outputs = fc1(*decode_moe.fc1_only_args(run_args), + *table_args) + return decode_moe.run_cute_fc2(fc1_outputs, + args, + lamport_out, + cubin_tile_k=tile_k, + record=True) + # Every other call: the runner's own kernels; a Lamport buffer only + # goes to ENGINE / CUTE_FC2. + return run(*run_args, *table_args) + + def _table_tactic(self, inputs: List[torch.Tensor], local_num_experts: int, + routing_tiles: Tuple[int, ...]) -> List[int]: + """The first valid tactic of a tile in ``routing_tiles``.""" + args = FP4BlockScaleMoEInputs(*inputs) + for tactic in self.get_runner().get_valid_configs( + self.top_k, args.hidden_states.shape[1] * 2, + self.intermediate_size, local_num_experts, + args.hidden_states.shape[0]): + if tactic[0] in routing_tiles: + return list(tactic) + raise RuntimeError( + f"no MoE tactic of the routing tiles {routing_tiles}") def _forward_decode( self, @@ -650,8 +714,11 @@ def _forward_decode( if kernel == decode_moe.DecodeKernel.CUTE_FC2: fc1 = (kernel_runner.run_moe_prerouted_fc1 if prerouted is not None else kernel_runner.run_moe_fc1) + cubin_tile_k = decode_moe.fc2_cubin_tile_k(kernel_runner, + self.act_type, tactic) return decode_moe.run_cute_fc2( - fc1(*decode_moe.fc1_only_args(run_args)), args, lamport_out) + fc1(*decode_moe.fc1_only_args(run_args)), args, lamport_out, + cubin_tile_k) return run(*run_args) def get_valid_tactics(self, inputs: List[torch.Tensor], @@ -818,51 +885,54 @@ def lookup_tactic( return [int(tactic[0]), int(tactic[1])] -def _run_fp4_block_scale_moe( - routing_logits: Optional[torch.Tensor], - routing_bias: Optional[torch.Tensor], - hidden_states: torch.Tensor, - hidden_states_scale: torch.Tensor, - gemm1_weights: torch.Tensor, - gemm1_weights_scale: torch.Tensor, - gemm1_bias: torch.Tensor, - gemm1_alpha: torch.Tensor, - gemm1_beta: torch.Tensor, - gemm1_clamp_limit: torch.Tensor, - gemm2_weights: torch.Tensor, - gemm2_weights_scale: torch.Tensor, - gemm2_bias: torch.Tensor, - output1_scale_scalar: torch.Tensor, - output1_scale_gate_scalar: torch.Tensor, - output2_scale_scalar: torch.Tensor, - num_experts: int, - top_k: int, - n_group: Optional[int], - topk_group: Optional[int], - intermediate_size: int, - local_expert_offset: int, - local_num_experts: int, - routed_scaling_factor: Optional[float], - routing_method_type: int, - do_finalize: bool, - act_type: int = ActType_TrtllmGen.SwiGlu.value, - topk_weights: Optional[torch.Tensor] = None, - topk_ids: Optional[torch.Tensor] = None, - output: Optional[torch.Tensor] = None, - tune_max_num_tokens: int = 8192, - use_dp: bool = False, - prerouted_tables: Optional[torch.Tensor] = None, - prerouted_ids: Optional[torch.Tensor] = None, - prerouted_weights: Optional[torch.Tensor] = None, - prerouted_tactic: Optional[List[int]] = None, - prerouted_candidates: Optional[torch.Tensor] = None, - decode_tuning: bool = False, - decode_engine_state: Optional[torch.Tensor] = None, - lamport_fc2_out: Optional[torch.Tensor] = None, - decode_early_release_rows: int = 0, - decode_spare_sms: int = 0, - routing_tables: Optional[torch.Tensor] = None, - routing_tiles: Optional[List[int]] = None) -> List[torch.Tensor]: +def _run_fp4_block_scale_moe(routing_logits: Optional[torch.Tensor], + routing_bias: Optional[torch.Tensor], + hidden_states: torch.Tensor, + hidden_states_scale: torch.Tensor, + gemm1_weights: torch.Tensor, + gemm1_weights_scale: torch.Tensor, + gemm1_bias: torch.Tensor, + gemm1_alpha: torch.Tensor, + gemm1_beta: torch.Tensor, + gemm1_clamp_limit: torch.Tensor, + gemm2_weights: torch.Tensor, + gemm2_weights_scale: torch.Tensor, + gemm2_bias: torch.Tensor, + output1_scale_scalar: torch.Tensor, + output1_scale_gate_scalar: torch.Tensor, + output2_scale_scalar: torch.Tensor, + num_experts: int, + top_k: int, + n_group: Optional[int], + topk_group: Optional[int], + intermediate_size: int, + local_expert_offset: int, + local_num_experts: int, + routed_scaling_factor: Optional[float], + routing_method_type: int, + do_finalize: bool, + act_type: int = ActType_TrtllmGen.SwiGlu.value, + topk_weights: Optional[torch.Tensor] = None, + topk_ids: Optional[torch.Tensor] = None, + output: Optional[torch.Tensor] = None, + tune_max_num_tokens: int = 8192, + use_dp: bool = False, + prerouted_tables: Optional[torch.Tensor] = None, + prerouted_ids: Optional[torch.Tensor] = None, + prerouted_weights: Optional[torch.Tensor] = None, + prerouted_tactic: Optional[List[int]] = None, + prerouted_candidates: Optional[ + torch.Tensor] = None, + decode_tuning: bool = False, + decode_engine_state: Optional[torch.Tensor] = None, + lamport_fc2_out: Optional[torch.Tensor] = None, + decode_early_release_rows: int = 0, + decode_spare_sms: int = 0, + routing_tables: Optional[torch.Tensor] = None, + routing_tiles: Optional[List[int]] = None, + routing_max_ctas: int = 0, + cute_fc2_rows: int = 0, + dynamic_experts: int = 0) -> List[torch.Tensor]: """``decode_tuning``: see ``FP4BlockScaleMoERunner.get_tuning_config``. ``decode_engine_state``: the calling backend's decode MoE engine state @@ -884,7 +954,28 @@ def _run_fp4_block_scale_moe( ``routing_tables`` replace the routing kernel for tactics of the tiles in ``routing_tiles``. Unfinalized, a run on them returns an empty ``[0, tile]`` - permutation: the permutation is row 0 of that tile's table.""" + permutation: the permutation is row 0 of that tile's table. + ``routing_max_ctas`` > 0 bounds the CTAs the ``routing_tables`` assign. + + ``cute_fc2_rows``: ``MoEDecodeOptions.cute_fc2_rows`` (see + ``decode_moe.cute_fc2_opt_in``). ``dynamic_experts`` > 0 (dynamic expert + parallelism): the per-expert inputs hold that many experts and the + ``routing_tables`` assign this call's share of them; the tuner and runs + without the tables see the static slot range ``[local_expert_offset, + local_expert_offset + local_num_experts)``.""" + + full_experts = None + if dynamic_experts: + full_experts = (gemm1_weights, gemm1_weights_scale, gemm1_bias, + gemm1_alpha, gemm1_beta, gemm1_clamp_limit, + gemm2_weights, gemm2_weights_scale, gemm2_bias, + output1_scale_scalar, output1_scale_gate_scalar, + output2_scale_scalar) + (gemm1_weights, gemm1_weights_scale, gemm1_bias, gemm1_alpha, + gemm1_beta, gemm1_clamp_limit, gemm2_weights, gemm2_weights_scale, + gemm2_bias, output1_scale_scalar, output1_scale_gate_scalar, + output2_scale_scalar) = (None if t is None else t.narrow( + 0, local_expert_offset, local_num_experts) for t in full_experts) tuner = AutoTuner.get() kernel_runner = FP4BlockScaleMoERunner( @@ -904,6 +995,7 @@ def _run_fp4_block_scale_moe( decode_tuning=decode_tuning, decode_early_release_rows=decode_early_release_rows, decode_spare_sms=decode_spare_sms, + cute_fc2_rows=cute_fc2_rows, ) # Prepare dummy topk tensors and hook for AutoTuner profiling @@ -980,7 +1072,12 @@ def _run_fp4_block_scale_moe( table_kwargs = {} if routing_tables is not None: table_kwargs = dict(routing_tables=routing_tables, - routing_tiles=tuple(routing_tiles or ())) + routing_tiles=tuple(routing_tiles or ()), + routing_max_ctas=routing_max_ctas) + if full_experts is not None: + table_kwargs["dynamic_inputs"] = (input_tensors[:4] + + list(full_experts) + + input_tensors[16:]) result = kernel_runner( input_tensors, tactic=[-1, -1] if best_tactic == -1 else best_tactic, @@ -1003,46 +1100,49 @@ def _run_fp4_block_scale_moe( @torch.library.custom_op("trtllm::fp4_block_scale_moe_runner", mutates_args=()) -def fp4_block_scale_moe_runner( - routing_logits: Optional[torch.Tensor], - routing_bias: Optional[torch.Tensor], - hidden_states: torch.Tensor, - hidden_states_scale: torch.Tensor, - gemm1_weights: torch.Tensor, - gemm1_weights_scale: torch.Tensor, - gemm1_bias: torch.Tensor, - gemm1_alpha: torch.Tensor, - gemm1_beta: torch.Tensor, - gemm1_clamp_limit: torch.Tensor, - gemm2_weights: torch.Tensor, - gemm2_weights_scale: torch.Tensor, - gemm2_bias: torch.Tensor, - output1_scale_scalar: torch.Tensor, - output1_scale_gate_scalar: torch.Tensor, - output2_scale_scalar: torch.Tensor, - num_experts: int, - top_k: int, - n_group: Optional[int], - topk_group: Optional[int], - intermediate_size: int, - local_expert_offset: int, - local_num_experts: int, - routed_scaling_factor: Optional[float], - routing_method_type: int, - do_finalize: bool, - act_type: int = ActType_TrtllmGen.SwiGlu.value, - topk_weights: Optional[torch.Tensor] = None, - topk_ids: Optional[torch.Tensor] = None, - output: Optional[torch.Tensor] = None, - tune_max_num_tokens: int = 8192, - use_dp: bool = False, - prerouted_tables: Optional[torch.Tensor] = None, - prerouted_ids: Optional[torch.Tensor] = None, - prerouted_weights: Optional[torch.Tensor] = None, - prerouted_tactic: Optional[List[int]] = None, - decode_tuning: bool = False, - routing_tables: Optional[torch.Tensor] = None, - routing_tiles: Optional[List[int]] = None) -> List[torch.Tensor]: +def fp4_block_scale_moe_runner(routing_logits: Optional[torch.Tensor], + routing_bias: Optional[torch.Tensor], + hidden_states: torch.Tensor, + hidden_states_scale: torch.Tensor, + gemm1_weights: torch.Tensor, + gemm1_weights_scale: torch.Tensor, + gemm1_bias: torch.Tensor, + gemm1_alpha: torch.Tensor, + gemm1_beta: torch.Tensor, + gemm1_clamp_limit: torch.Tensor, + gemm2_weights: torch.Tensor, + gemm2_weights_scale: torch.Tensor, + gemm2_bias: torch.Tensor, + output1_scale_scalar: torch.Tensor, + output1_scale_gate_scalar: torch.Tensor, + output2_scale_scalar: torch.Tensor, + num_experts: int, + top_k: int, + n_group: Optional[int], + topk_group: Optional[int], + intermediate_size: int, + local_expert_offset: int, + local_num_experts: int, + routed_scaling_factor: Optional[float], + routing_method_type: int, + do_finalize: bool, + act_type: int = ActType_TrtllmGen.SwiGlu.value, + topk_weights: Optional[torch.Tensor] = None, + topk_ids: Optional[torch.Tensor] = None, + output: Optional[torch.Tensor] = None, + tune_max_num_tokens: int = 8192, + use_dp: bool = False, + prerouted_tables: Optional[torch.Tensor] = None, + prerouted_ids: Optional[torch.Tensor] = None, + prerouted_weights: Optional[torch.Tensor] = None, + prerouted_tactic: Optional[List[int]] = None, + decode_tuning: bool = False, + routing_tables: Optional[torch.Tensor] = None, + routing_tiles: Optional[List[int]] = None, + *, + routing_max_ctas: int = 0, + cute_fc2_rows: int = 0, + dynamic_experts: int = 0) -> List[torch.Tensor]: """The TRTLLM-Gen NVFP4 MoE runner (see ``_run_fp4_block_scale_moe``); functional: it writes no argument except ``output``, as on every model's path. The decode kernels that write state run in ``fp4_block_scale_moe_decode_runner``.""" @@ -1084,7 +1184,10 @@ def fp4_block_scale_moe_runner( prerouted_tactic=prerouted_tactic, decode_tuning=decode_tuning, routing_tables=routing_tables, - routing_tiles=routing_tiles) + routing_tiles=routing_tiles, + routing_max_ctas=routing_max_ctas, + cute_fc2_rows=cute_fc2_rows, + dynamic_experts=dynamic_experts) @torch.library.custom_op("trtllm::fp4_block_scale_moe_decode_runner", @@ -1252,7 +1355,11 @@ def _fp4_block_scale_moe_fake( decode_early_release_rows: int = 0, decode_spare_sms: int = 0, routing_tables: Optional[torch.Tensor] = None, - routing_tiles: Optional[List[int]] = None) -> List[torch.Tensor]: + routing_tiles: Optional[List[int]] = None, + *, + routing_max_ctas: int = 0, + cute_fc2_rows: int = 0, + dynamic_experts: int = 0) -> List[torch.Tensor]: """The fake of both ops, registered for each with the decode op's parameters (their defaults are the plain op's); the decode op's state arguments do not shape the outputs.""" if lamport_fc2_out is not None: diff --git a/tensorrt_llm/_torch/kernels/blackwell/moe_lowm_fc2.py b/tensorrt_llm/_torch/kernels/blackwell/moe_lowm_fc2.py index 9a7df8373fb9..01b94d0627d6 100644 --- a/tensorrt_llm/_torch/kernels/blackwell/moe_lowm_fc2.py +++ b/tensorrt_llm/_torch/kernels/blackwell/moe_lowm_fc2.py @@ -1,16 +1,16 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -"""Routed NVFP4 MoE FC2 for decode-sized batches, bit-identical to the trtllm-gen FC2 cubin -``bmm_Bfloat16_E2m1E2m1_Fp32_Ab16_Bb16_t128x8x256_*_dynB`` (Gemm2 of ``moe/trtllmGen/runner.cu``), with a shared-memory -and register footprint that fits ``CTAS_PER_SM`` CTAs per SM. +"""Routed NVFP4 MoE FC2 for decode-sized batches, bit-identical to the trtllm-gen tile-8 FC2 cubins +``bmm_Bfloat16_E2m1E2m1_Fp32_Ab16_Bb16_t128x8x*`` (Gemm2 of ``moe/trtllmGen/runner.cu``), with a shared-memory and +register footprint that fits ``CTAS_PER_SM`` CTAs per SM. ``out[p, h] = bf16_satfinite(scale[e] * sum_k act[p, k] * w2[e, h, k])`` for every permuted row ``p`` of a token tile (8 rows) of local expert ``e``. Operands and routing tables are the trtllm-gen MoE runner's buffers (``moe_lowm_fc2``): ``w2`` rows shuffled in 32-row blocks with 128x4 E4M3 scales, the FC1 output with 8x4 scales. Bit-exactness: the cubin's MMA (``tcgen05.mma.kind::mxf4nvf4.block_scale.scale_vec::4X``, M 128, N 8, K 64) in its K -order with K tiles of 256 (the zero-filled K tail issues the same MMAs), one FP32 ``mul.rn`` by ``scale[e]`` and -``cvt.rn.satfinite.bf16x2.f32``. +order, the +0 of the cubin's zero-filled K tail where the kernel has none of its own, one FP32 ``mul.rn`` by +``scale[e]`` and ``cvt.rn.satfinite.bf16x2.f32``. Work: a persistent grid walks the (m tile, token tile) pairs. Warp 0 streams weights by TMA before the PDL wait, warp 1 activations after it, warp 2 issues the MMAs into two TMEM accumulators, warp 3 L2-prefetches later tiles' weights and @@ -19,7 +19,7 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Optional +from typing import TYPE_CHECKING, Optional, Tuple import cuda.bindings.driver as cuda import cutlass @@ -49,7 +49,7 @@ TILE_M = 128 TILE_N = 8 -TILE_K = 256 # the cubin's K tile (K order and zero-filled tail MMAs are defined by it) +TILE_K = 256 SF_VEC = 16 EPI_WARP0 = 4 NUM_ACC = 2 @@ -88,13 +88,24 @@ def _prefetch_bulk_l2(addr: Int64, nbytes: Int32) -> None: ) +def _scale_pack_bf16x2_tail(lo, hi, s) -> Int32: + """Adds the +0 of the cubins' zero-filled K-tail MMAs first (a -0 accumulator becomes +0).""" + return cute.arch.inline_ptx( + "{ .reg .f32 a, b; add.rn.f32 a, {$r0}, 0f00000000; add.rn.f32 b, {$r1}, 0f00000000;" + " mul.rn.f32 a, a, {$r2}; mul.rn.f32 b, b, {$r2}; cvt.rn.satfinite.bf16x2.f32 {$w0}, b, a; }", + write_only_types=[Int32], + read_only_args=[lo, hi, s], + ) + + class MoeLowMFc2Nvfp4: """Routed NVFP4 FC2, tile 128 (hidden) x 8 (rows) x 256 (K), ``NUM_STAGES`` K stages per CTA.""" - def __init__(self, k_tiles: int, k_groups: int, use_pdl: bool = True): + def __init__(self, k_tiles: int, k_groups: int, zero_tail: bool, use_pdl: bool = True): self.use_pdl = use_pdl self.k_tiles = k_tiles self.k_groups = k_groups # 4-scale groups per activation row (I / 64) + self.zero_tail = zero_tail self.tile_k = TILE_K self.gps = TILE_K // (4 * SF_VEC) # 4-scale groups per K tile self.num_stages = NUM_STAGES @@ -793,10 +804,11 @@ def epilogue( r = y * TILE_N + j if lead: if r < limit: - _st_global_b32( - c_addr + (Int64(r) * Int64(h_total) + col) * 2, - _scale_pack_bf16x2(rAcc[j], partner, s), - ) + if cutlass.const_expr(self.zero_tail): + packed = _scale_pack_bf16x2_tail(rAcc[j], partner, s) + else: + packed = _scale_pack_bf16x2(rAcc[j], partner, s) + _st_global_b32(c_addr + (Int64(r) * Int64(h_total) + col) * 2, packed) _COMPILED = {} @@ -811,6 +823,14 @@ def num_sms(device: Optional[torch.device] = None) -> int: return torch.cuda.get_device_properties(device).multi_processor_count - sm_reserve() +def supports(w2_shape: Tuple[int, ...], cubin_k_tile: int) -> bool: + """Whether :func:`moe_lowm_fc2` reproduces the FC2 cubin of tile K ``cubin_k_tile`` on uint8 FC2 weights + [E, H, I / 2].""" + _, h, half_k = w2_shape + k = 2 * half_k + return h % TILE_M == 0 and k % (4 * SF_VEC) == 0 and cubin_k_tile % TILE_K == 0 + + def moe_lowm_fc2( act: torch.Tensor, act_sf: torch.Tensor, @@ -821,18 +841,23 @@ def moe_lowm_fc2( cta_limit: torch.Tensor, num_non_exiting: torch.Tensor, out: torch.Tensor, + cubin_k_tile: Optional[int] = None, ) -> torch.Tensor: - """FC2 of the trtllm-gen MoE path. ``act`` [rows, I/2] uint8 (E2M1 x2), ``act_sf`` 8x4 E4M3 (uint8), - ``w2`` [E, H, I/2] uint8, ``w2_sf`` [E, H, I/16] (128x4), ``scale`` [E] fp32, tables int32 (``cta_batch`` / - ``cta_limit`` per token tile, ``num_non_exiting`` [1]), ``out`` [padded rows, H] bf16 with at least the total padded - rows (rows of a tile past its limit are not written).""" + """FC2 of the trtllm-gen MoE path, bit for bit the FC2 cubin of tile K ``cubin_k_tile`` (None: the kernel's). + ``act`` [rows, I/2] uint8 (E2M1 x2), ``act_sf`` 8x4 E4M3 (uint8), ``w2`` [E, H, I/2] uint8, ``w2_sf`` + [E, H, I/16] (128x4), ``scale`` [E] fp32, tables int32 (``cta_batch`` / ``cta_limit`` per token tile, + ``num_non_exiting`` [1]), ``out`` [padded rows, H] bf16 with at least the total padded rows (rows of a tile past + its limit are not written).""" import torch + cubin_k_tile = TILE_K if cubin_k_tile is None else cubin_k_tile rows, half_k = act.shape e, h, half_k2 = w2.shape k = 2 * half_k - if half_k2 != half_k or h % TILE_M or k % (4 * SF_VEC): - raise ValueError(f"unsupported FC2 shape rows {rows} H {h} I {k} E {e}") + if half_k2 != half_k or not supports(w2.shape, cubin_k_tile): + raise ValueError( + f"unsupported FC2 shape rows {rows} H {h} I {k} E {e}, cubin K tile {cubin_k_tile}" + ) if ( out.dim() != 2 or out.shape[1] != h @@ -840,6 +865,8 @@ def moe_lowm_fc2( or not out.is_contiguous() ): raise ValueError("out must be a contiguous bf16 [padded rows, H] tensor") + # A cubin's zero-filled K tail adds an exact +0, which the kernel re-applies when it has no tail of its own. + zero_tail = k % cubin_k_tile != 0 and k % TILE_K == 0 grid_ctas = num_sms(act.device) * CTAS_PER_SM ptrs = ( gmem_ptr(w2, cutlass.Float4E2M1FN, 32), @@ -858,12 +885,13 @@ def moe_lowm_fc2( problem = (Int32(h), Int32(k), Int32(e), Int32(rows)) stream = cuda.CUstream(torch.cuda.current_stream().cuda_stream) use_pdl = get_env_enable_pdl() - fn = _COMPILED.get((k, use_pdl)) + key = (k, zero_tail, use_pdl) + fn = _COMPILED.get(key) if fn is None: if torch.cuda.is_current_stream_capturing(): raise RuntimeError("compile the low-M MoE FC2 before CUDA graph capture") - kern = MoeLowMFc2Nvfp4(-(-k // TILE_K), k // (4 * SF_VEC), use_pdl) + kern = MoeLowMFc2Nvfp4(-(-k // TILE_K), k // (4 * SF_VEC), zero_tail, use_pdl) fn = cute.compile(kern, *ptrs, *addrs, problem, Int32(grid_ctas), stream) - _COMPILED[(k, use_pdl)] = fn + _COMPILED[key] = fn fn(*ptrs, *addrs, problem, Int32(grid_ctas), stream) return out diff --git a/tensorrt_llm/_torch/model_config.py b/tensorrt_llm/_torch/model_config.py index a89fa5451bb7..13af4a6e7245 100644 --- a/tensorrt_llm/_torch/model_config.py +++ b/tensorrt_llm/_torch/model_config.py @@ -441,6 +441,8 @@ class ModelConfig(Generic[TConfig]): replicate_embedding: bool = False # Batch sizes of the generation CUDA graphs (empty without them). cuda_graph_batch_sizes: Tuple[int, ...] = () + # The executor's largest batch, in requests (None when unknown). + max_batch_size: Optional[int] = None # If true, enable min-latency mode. Currently only used for Llama4. enable_min_latency: bool = False diff --git a/tensorrt_llm/_torch/models/modeling_deepseekv4.py b/tensorrt_llm/_torch/models/modeling_deepseekv4.py index 0f8a3b44a493..c9a6ea65f891 100644 --- a/tensorrt_llm/_torch/models/modeling_deepseekv4.py +++ b/tensorrt_llm/_torch/models/modeling_deepseekv4.py @@ -1544,11 +1544,14 @@ def __init__( apply_routing: bool = False, moe_backend: str = "CUTLASS", has_vl_bias: bool = False, + small_m_logit_partials: bool = False, ): super().__init__() self.weight = nn.Parameter( torch.empty((num_experts, hidden_size), dtype=dtype), requires_grad=False ) + # The model opted into partials from ``router_logit_partials.SMALL_M_MIN_ROWS`` rows. + self.small_m_logit_partials = small_m_logit_partials self.moe_backend = moe_backend bias_dtype = torch.float32 @@ -1615,7 +1618,9 @@ def forward( # An empty attention-DP peer still joins expert communication, but # the router's cuBLAS fallback does not accept an empty GEMM. return hidden_states.new_empty((0, self.weight.shape[0]), dtype=torch.float32) - if partials and router_partials.applies(hidden_states, self.weight): + if partials and router_partials.applies( + hidden_states, self.weight, small_m=self.small_m_logit_partials + ): return router_partials.router_logit_partials(hidden_states, self.weight) return router_gemm_autotuned(hidden_states, self.weight) @@ -1808,6 +1813,9 @@ def __init__( apply_routing=False, moe_backend=model_config.moe_backend, has_vl_bias=bool(getattr(config, "use_vision_bias", False)), + small_m_logit_partials=bool( + model_config.extra_attrs.get("moe_router_partials_small_m", False) + ), ) experts_quant_config = self._get_experts_quant_config(model_config, layer_idx) if override_quant_config is not None and experts_quant_config is model_config.quant_config: diff --git a/tensorrt_llm/_torch/models/modeling_deepseekv41.py b/tensorrt_llm/_torch/models/modeling_deepseekv41.py index e33446684744..68ded6123132 100644 --- a/tensorrt_llm/_torch/models/modeling_deepseekv41.py +++ b/tensorrt_llm/_torch/models/modeling_deepseekv41.py @@ -18,7 +18,7 @@ import json import os from collections.abc import Callable -from dataclasses import dataclass, field +from dataclasses import dataclass, field, replace from pathlib import Path from typing import TYPE_CHECKING, Any, Dict, List, Optional, Sequence, Tuple, cast @@ -70,6 +70,7 @@ mhc_split_enabled, ) from ..modules.multi_stream_utils import do_multi_stream +from ..moe.fused_moe.impl_contract import MOE_DECODE_OPTIONS, MoEDecodeOptions from ..moe.fused_moe.moe_scheduler import routes_padding_nowhere from ..pyexecutor.breakable_cuda_graph import eager_on_graph, is_in_breakable_cuda_graph from ..speculative import SpecMetadata @@ -334,6 +335,9 @@ class _AttentionDPEngramEmbeddings: _ENGRAM_PRECOMPUTE_MAX_ROWS = 64 # Batches with fewer tokens on the busiest rank, decode included, keep the model-stream path. _ENGRAM_CONTEXT_MIN_TOKENS = 256 +# MoE calls of up to this many rows (decode sizes, where the 8-row FC2 cubin tiles run in rounds) take the CuTe DSL +# FC2 (MoEDecodeOptions.cute_fc2_rows). +_MOE_CUTE_FC2_ROWS = 16 @dataclass(frozen=True) @@ -1522,6 +1526,17 @@ class DeepseekV41Model(DeepseekV4Model): _prologue_stream: torch.cuda.Stream | None = None def __init__(self, model_config: ModelConfig[PretrainedConfig], *args, **kwargs): + # Its NVFP4 MoEs run the FC2 of small un-finalized calls as the CuTe DSL kernel and route decode + # steps in one cluster. + model_config.extra_attrs[MOE_DECODE_OPTIONS] = replace( + MoEDecodeOptions.of(model_config.extra_attrs), + cute_fc2_rows=_MOE_CUTE_FC2_ROWS, + one_cluster_route=True, + ) + # Batch-1 attention-TP workers split each MoE call's experts over the two EP ranks. + model_config.extra_attrs["moe_dynamic_ep"] = True + # The router logits come as K-chunk partials from 12 rows per rank (SM100/SM103). + model_config.extra_attrs["moe_router_partials_small_m"] = True super().__init__(model_config, *args, **kwargs) self._decoder_replay_observed = False self._decoder_replay_reuse_warning_emitted = False diff --git a/tensorrt_llm/_torch/moe/fused_moe/MOE_DEVELOPER_GUIDE.md b/tensorrt_llm/_torch/moe/fused_moe/MOE_DEVELOPER_GUIDE.md index edce1f03ccd4..1e4b26b5a4e3 100644 --- a/tensorrt_llm/_torch/moe/fused_moe/MOE_DEVELOPER_GUIDE.md +++ b/tensorrt_llm/_torch/moe/fused_moe/MOE_DEVELOPER_GUIDE.md @@ -200,7 +200,7 @@ A staged routing override (e.g. the layer-wise benchmark's balanced replacement) `MoERunContext.lamport_fc2_out` is the hand-off to a caller whose all-reduce polls the un-finalized FC2 rows (the MNNVL MoE-output fold). It is passed only to one un-finalized chunk without communication of a backend that declares `takes_lamport_fc2_out` (`TrtllmTrtllmGenNvfp4Impl`). Such a `run_moe` may write its FC2 rows into the buffer and then returns that buffer as the rows (the `ENGINE` and `CUTE_FC2` decode kernels); otherwise it returns rows of its own and leaves the buffer untouched (`CUBIN`), and `decode_moe.rows_in_lamport` tells the two apart. `decode_moe.LamportFc2Buffer` owns the protocol: the buffer holds 0xFFFFFFFF wherever FC2 has not written, the kernels write each word of a real row exactly once with a value that is never 0xFFFFFFFF, and the all-reduce resets each word it reads. Because a custom-op output may not alias an input, the FP4 op returns an empty first output for rows it wrote into the buffer and `moe_op_backend` substitutes the buffer. -`MoEDecodeOptions` (`impl_contract.py`) is how a model declares MoE decode kernels at construction, through `model_config.extra_attrs[MOE_DECODE_OPTIONS]`: decode-step tuning buckets and the decode kernels of the TRTLLM-Gen FP4 op (`fp4_block_scale_moe_decode_runner`, `decode_moe.select`: `ENGINE`, `CUTE_FC2`, `CUBIN`), the engine's early release rows, the CuTe DSL evict-first FC2 rows, and the TRTLLM-Gen BF16 decode MoE engine (`bf16_decode_engine`). The SMs the decode engine leaves to a shared expert are not an option: the model asks for them per forward through the hook below. The defaults are the stock paths, which every model that declares nothing keeps. +`MoEDecodeOptions` (`impl_contract.py`) is how a model declares MoE decode kernels at construction, through `model_config.extra_attrs[MOE_DECODE_OPTIONS]`: decode-step tuning buckets and the decode kernels of the TRTLLM-Gen FP4 op (`fp4_block_scale_moe_decode_runner`, `decode_moe.select`: `ENGINE`, `CUTE_FC2`, `CUBIN`), the engine's early release rows, the CuTe DSL evict-first FC2 rows, the TRTLLM-Gen BF16 decode MoE engine (`bf16_decode_engine`), `cute_fc2_rows` (without `tuning`, un-finalized attention-TP calls of up to that many rows run the CuTe FC2 alone, `decode_moe.cute_fc2_opt_in`, on the NVFP4 op's routing-table entries too), and `one_cluster_route` (the TRTLLM-Gen NVFP4 leaf routes table launches of the shapes `dsv4_route_one.applies` takes in one cluster). The SMs the decode engine leaves to a shared expert are not an option: the model asks for them per forward through the hook below. The defaults are the stock paths, which every model that declares nothing keeps. A model that orders work around the routing asks `ConfigurableMoE.routes_with_sort_tables(num_tokens)` instead of re-deriving these conditions. Likewise, a producer that can emit the routed experts' NVFP4 input (e.g. from a GEMM epilogue) asks `ConfigurableMoE.nvfp4_input_scale(num_tokens)`: the global scale of an `Fp4QuantizedTensor` input (linear scale factors) that the forward takes as is, or `None` when the forward needs an unquantized input (the backend declares no `MoEImplBase.prequantized_nvfp4_input_scale()`, or a comm strategy, EPLB, `apply_router_weight_on_input` or more than one chunk). `ConfigurableMoE.quantize_nvfp4_input(x)` quantizes as the backend would. diff --git a/tensorrt_llm/_torch/moe/fused_moe/configurable_moe.py b/tensorrt_llm/_torch/moe/fused_moe/configurable_moe.py index 2d7ef34d4bd5..323e95caa7dd 100644 --- a/tensorrt_llm/_torch/moe/fused_moe/configurable_moe.py +++ b/tensorrt_llm/_torch/moe/fused_moe/configurable_moe.py @@ -63,6 +63,7 @@ from .activation import install_activation_params from .communication import AllGatherReduceScatter, Communication, CommunicationFactory from .communication.nccl_ep import NcclEP +from .impl_environment import collect_moe_environment from .moe_scheduler import MoEScheduler, create_moe_scheduler # Attributes that ConfigurableMoE owns (computed in MoE.__init__ from real @@ -82,8 +83,13 @@ "slot_start", "slot_end", "expert_size_per_partition", + # A dynamic-EP layer's static partition, else None (``_maybe_dynamic_expert_parallel_layout``). + "dynamic_ep", ) +# 4: a dynamic-EP rank holds twice its static routed weights, at most a quarter of the bank. +_DYNAMIC_EP_MIN_MOE_TP = 4 + def _dwdp_ineligibility(moe: "ConfigurableMoE") -> Optional[str]: """Why DWDP cannot manage ``moe``'s layer, or None when it can. @@ -434,6 +440,7 @@ def _create_and_sync_backend( # this rank's experts, so it is sized here, before the sync below # mirrors the layout onto the backend and before its weights exist. self._decide_dwdp() + self._maybe_dynamic_expert_parallel_layout(model_config) # Mirror wrapper-owned EPLB / layer-id state onto the backend so any # backend code path that reads e.g. ``self.layer_load_balancer`` or @@ -456,6 +463,44 @@ def _create_and_sync_backend( self.create_weights() return backend_model_config + def _dynamic_expert_parallelism_applies(self, model_config: ModelConfig) -> bool: + """Whether each call splits its experts over the two EP ranks (attention TP, SM100/SM103): + an opted-in model (``moe_dynamic_ep``), batch-1 steps within ``dynamic_ep_max_rows``.""" + if not model_config.extra_attrs.get("moe_dynamic_ep", False): + return False + spec = model_config.spec_config + return ( + self.backend is not None + and model_config.max_batch_size == 1 + and (spec.tokens_per_gen_step if spec is not None else 1) + <= getattr(type(self.backend), "dynamic_ep_max_rows", 0) + and not self.use_dp + and self.ep_size == 2 + and self.tp_size >= _DYNAMIC_EP_MIN_MOE_TP + and self.layer_load_balancer is None + and self.num_slots == self.num_experts + and self.num_experts % self.ep_size == 0 + and get_global_dwdp_manager() is None + and getattr(self.routing_method, "sqrt_softplus_bias_selection", False) + and collect_moe_environment().sm in (100, 103) + ) + + def _maybe_dynamic_expert_parallel_layout(self, model_config: ModelConfig) -> None: + """Dynamic expert parallelism: every EP rank holds its TP shard of all experts, and + ``dynamic_ep`` is the static partition ``(slot_start, count, ep_rank, ep_size)``.""" + self.dynamic_ep = None + if not self._dynamic_expert_parallelism_applies(model_config): + return + self.dynamic_ep = ( + self.slot_start, + self.expert_size_per_partition, + self.ep_rank, + self.ep_size, + ) + self.expert_size_per_partition = self.num_experts + self.slot_start, self.slot_end = 0, self.num_experts + self.initial_local_expert_ids = list(self.initial_global_assignments) + def _reject_non_divisible_ep_backend(self) -> None: """Enforce the non-divisible-EP contract on the resolved backend. diff --git a/tensorrt_llm/_torch/moe/fused_moe/impl_contract.py b/tensorrt_llm/_torch/moe/fused_moe/impl_contract.py index 756c884342e2..b20acb41cafd 100644 --- a/tensorrt_llm/_torch/moe/fused_moe/impl_contract.py +++ b/tensorrt_llm/_torch/moe/fused_moe/impl_contract.py @@ -84,6 +84,12 @@ class MoEDecodeOptions: fc2_weights_evict_first_rows: int = 0 # TRTLLM-Gen BF16: logits-routed un-finalized SwiGLU runs of up to 32 rows take the BF16 decode MoE engine. bf16_decode_engine: bool = False + # TRTLLM-Gen NVFP4 op without ``tuning``: un-finalized attention-TP calls of up to this many rows run FC2 on the + # CuTe DSL kernel where it reproduces the tactic's cubin (trtllm_gen.decode_moe.cute_fc2_opt_in; 0: none). + cute_fc2_rows: int = 0 + # TRTLLM-Gen NVFP4 on the DS-V4 route kernel's tables: launches of the shapes dsv4_route_one.applies takes route + # in one cluster. + one_cluster_route: bool = False @classmethod def of(cls, extra_attrs: Dict) -> "MoEDecodeOptions": @@ -729,10 +735,11 @@ class MoECommPlan: @dataclass(frozen=True) class MoERoutingTables: """Routing tables in the kernel's layout, one entry per tile of ``tiles``; a tactic with - another tile routes itself.""" + another tile routes itself. ``max_ctas`` > 0 bounds the CTAs any of them assigns.""" tables: torch.Tensor tiles: Tuple[int, ...] + max_ctas: int = 0 @dataclass(frozen=True) diff --git a/tensorrt_llm/_torch/moe/fused_moe/moe_op_backend.py b/tensorrt_llm/_torch/moe/fused_moe/moe_op_backend.py index 1e382eefd623..005846fc97ae 100644 --- a/tensorrt_llm/_torch/moe/fused_moe/moe_op_backend.py +++ b/tensorrt_llm/_torch/moe/fused_moe/moe_op_backend.py @@ -174,6 +174,8 @@ def run_fp4_block_scale_moe( decode_early_release_rows: int = 0, decode_spare_sms: int = 0, routing_tables: Optional[MoERoutingTables] = None, + cute_fc2_rows: int = 0, + dynamic_experts: int = 0, ) -> List[torch.Tensor]: """Run FP4 block scale MoE computation. ``prerouted``: routing the caller computed (native op backend only). ``decode_tuning``: the native NVFP4 op @@ -182,7 +184,11 @@ def run_fp4_block_scale_moe( ``lamport_fc2_out`` / ``decode_early_release_rows`` / ``decode_spare_sms``: see ``fp4_block_scale_moe_decode_runner``. ``routing_tables`` replace the kernel's routing pass for tactics of their tiles - (calls without the decode kernels only). + (calls without the decode kernels only). ``cute_fc2_rows``: the model's + ``MoEDecodeOptions.cute_fc2_rows`` for the native NVFP4 op. + ``dynamic_experts`` > 0: the per-expert inputs hold that many experts, of which + ``[local_expert_offset, local_expert_offset + local_num_experts)`` is this rank's static + slot range, and ``routing_tables`` assign this call's share of all of them. """ raise NotImplementedError @@ -360,6 +366,8 @@ def run_fp4_block_scale_moe( decode_early_release_rows=0, decode_spare_sms=0, routing_tables=None, + cute_fc2_rows=0, + dynamic_experts=0, ): # The native runners take the block scales as one flat linear-layout # tensor (``fp4BlockScaleMoe.cpp`` checks ``dim() == 1``); the @@ -442,8 +450,10 @@ def run_fp4_block_scale_moe( or isinstance(prerouted, EngineRouting) ) if decode_call: - if routing_tables is not None: - raise ValueError("routing tables do not combine with the decode kernels") + if routing_tables is not None or dynamic_experts: + raise ValueError( + "routing tables and dynamic experts do not combine with the decode kernels" + ) fp4_op = torch.ops.trtllm.fp4_block_scale_moe_decode_runner op_kwargs = dict( prerouted_candidates=( @@ -461,6 +471,9 @@ def run_fp4_block_scale_moe( routing_tiles=None if routing_tables is None else list(routing_tables.tiles), + routing_max_ctas=0 if routing_tables is None else routing_tables.max_ctas, + cute_fc2_rows=cute_fc2_rows, + dynamic_experts=dynamic_experts, ) outputs = fp4_op( router_logits, diff --git a/tensorrt_llm/_torch/moe/fused_moe/trtllm_gen/base.py b/tensorrt_llm/_torch/moe/fused_moe/trtllm_gen/base.py index 989075ac1f9a..0d76f42c50d1 100644 --- a/tensorrt_llm/_torch/moe/fused_moe/trtllm_gen/base.py +++ b/tensorrt_llm/_torch/moe/fused_moe/trtllm_gen/base.py @@ -114,6 +114,8 @@ class TrtllmGenFusedMoEBase(MoEImplBase): decode_tuning: bool = False decode_early_release_rows: int = 0 + cute_fc2_rows: int = 0 + one_cluster_route: bool = False def __init_subclass__(cls, **kwargs: object) -> None: """Take the provider off the descriptor a leaf already publishes. @@ -215,10 +217,13 @@ def __init__( # Cached for autotune profile sizing (forward path passes # tune_max_num_tokens to the MoE op). self.max_num_tokens = model_config.max_num_tokens - # Declared by the model (MoEDecodeOptions): the FP4 block-scale op's decode tuning and kernels. + # Declared by the model (MoEDecodeOptions): the FP4 block-scale op's decode tuning and kernels, or its + # CuTe DSL FC2 alone, and the one-cluster route kernel. decode = MoEDecodeOptions.of(model_config.extra_attrs) self.decode_tuning = decode.tuning self.decode_early_release_rows = decode.early_release_rows + self.cute_fc2_rows = decode.cute_fc2_rows + self.one_cluster_route = decode.one_cluster_route self.op_backend: MoEOpBackend = get_op_backend(self.provider) diff --git a/tensorrt_llm/_torch/moe/fused_moe/trtllm_gen/decode_moe.py b/tensorrt_llm/_torch/moe/fused_moe/trtllm_gen/decode_moe.py index 09c16bb7c821..0572e0ef4d47 100644 --- a/tensorrt_llm/_torch/moe/fused_moe/trtllm_gen/decode_moe.py +++ b/tensorrt_llm/_torch/moe/fused_moe/trtllm_gen/decode_moe.py @@ -11,18 +11,24 @@ * ``CUBIN``: the runner's own FC1 and FC2 (also where it runs its fine-grained-sync pair, which has no FC1-only entry: ``TLLM_USE_FINE_GRAINED_SYNC`` with such a cubin for the shape). +A model that declares only ``MoEDecodeOptions.cute_fc2_rows`` takes ``CUTE_FC2`` alone (:func:`cute_fc2_opt_in`), on the +NVFP4 runner's entries with routing tables too. + Lamport FC2 (:class:`LamportFc2Buffer`): ``ENGINE`` / ``CUTE_FC2`` store nothing before their PDL wait, release their dependents only after it and write each word of a real row once (``cvt.rn.satfinite.bf16x2.f32``, never 0xFFFFFFFF), so the MoE-output all-reduce can poll their rows instead of waiting for FC2. """ import enum +from dataclasses import dataclass from types import SimpleNamespace from typing import TYPE_CHECKING, Dict, List, Mapping, Optional, Sequence, Tuple import torch +from tensorrt_llm._torch.cute_dsl_utils import IS_CUTLASS_DSL_AVAILABLE from tensorrt_llm._torch.utils import ActType_TrtllmGen +from tensorrt_llm._utils import is_blackwell_datacenter from .decode_front import max_num_tiles from .kernel_inputs import get_data_or_none, to_trtllm_gen_act_type @@ -46,7 +52,8 @@ #: The FC2 cubin options ``moe_lowm_fc2`` reproduces bit for bit (``get_gemm2_kernel_options`` of the C++ runner): #: E2m1 x E2m1 -> FP32 -> BF16 in tiles of 128 x TILE_N with M128 N8 K64 MMAs over the whole K in order (one CTA per -#: tile, no split-K). The tile K, stage count, unrolling and tile scheduler only change when those MMAs issue. +#: tile, no split-K). The stage count, unrolling and tile scheduler only change when those MMAs issue; the tile K sets +#: the zero-filled K tail the kernel re-applies (``moe_lowm_fc2.supports``). _CUTE_FC2_OPTIONS = { "dtypeA": "E2m1", "dtypeB": "E2m1", @@ -76,37 +83,53 @@ class DecodeKernel(enum.Enum): ENGINE = 2 -#: (act type, tile, config) -> whether ``moe_lowm_fc2`` reproduces that tactic's FC2 cubin. The C++ runners are -#: shared per act type (``FP4BlockScaleMoERunner.get_runner``), so the key names the cubin. -_FC2_REPRODUCED: Dict[Tuple[int, int, int], bool] = {} +#: (act type, tile, config) -> the tile K of that tactic's FC2 cubin where ``moe_lowm_fc2`` reproduces it, else None. +#: The C++ runners are shared per act type (``FP4BlockScaleMoERunner.get_runner``), so the key names the cubin. +_FC2_REPRODUCED: Dict[Tuple[int, int, int], Optional[int]] = {} + + +def fc2_cubin_tile_k( + kernel_runner: torch.ScriptObject, act_type: int, tactic: List[int] +) -> Optional[int]: + """The tile K of the tactic's FC2 cubin where ``moe_lowm_fc2`` reproduces it, else None.""" + key = (int(act_type), int(tactic[0]), int(tactic[1])) + if key not in _FC2_REPRODUCED: + options = kernel_runner.get_gemm2_kernel_options(key[1], key[2]) + _FC2_REPRODUCED[key] = int(options["tileK"]) if cute_fc2_reproduces(options) else None + return _FC2_REPRODUCED[key] -def _cute_fc2_fits( +def cute_fc2_tile_k( kernel_runner: torch.ScriptObject, act_type: int, tactic: List[int], args: "FP4BlockScaleMoEInputs", top_k: int, intermediate_size: int, -) -> bool: - if len(tactic) != 2 or tactic[0] != TILE_N or tactic[1] < 0: - return False + max_tokens: int = MAX_TOKENS, +) -> Optional[int]: + """The tile K of the tactic's FC2 cubin where ``moe_lowm_fc2`` stands in for it on a call of up to ``max_tokens`` + tokens, else None.""" + if len(tactic) != 2 or tactic[0] != TILE_N or tactic[1] < 0 or not IS_CUTLASS_DSL_AVAILABLE: + return None x, w2, w2_sf = args.hidden_states, args.gemm2_weights, args.gemm2_weights_scale - if x.shape[0] > MAX_TOKENS or w2.dim() != 3 or w2_sf.dim() != 3: - return False + if x.shape[0] > max_tokens or w2.dim() != 3 or w2_sf.dim() != 3: + return None if w2.shape[2] * 2 != intermediate_size: - return False - key = (int(act_type), int(tactic[0]), int(tactic[1])) - reproduced = _FC2_REPRODUCED.get(key) - if reproduced is None: - reproduced = _FC2_REPRODUCED[key] = cute_fc2_reproduces( - kernel_runner.get_gemm2_kernel_options(key[1], key[2]) - ) + return None + tile_k = fc2_cubin_tile_k(kernel_runner, act_type, tactic) + if tile_k is None: + return None + from tensorrt_llm._torch.kernels.blackwell.moe_lowm_fc2 import supports + + if not supports(w2.shape, tile_k): + return None # The CuTe FC2 stands in for the tuned tactic's FC2; the runner runs its fine-grained-sync pair instead (which # has no FC1-only entry) only where TLLM_USE_FINE_GRAINED_SYNC is set and such a cubin exists for this shape. - return reproduced and not kernel_runner.uses_fine_grained_sync( - key[1], top_k, 2 * x.shape[1], intermediate_size, w2.shape[0], x.shape[0] + fine_grained = kernel_runner.uses_fine_grained_sync( + tactic[0], top_k, 2 * x.shape[1], intermediate_size, w2.shape[0], x.shape[0] ) + return None if fine_grained else tile_k def _engine_fits(args: "FP4BlockScaleMoEInputs", act_type: int, top_k: int) -> bool: @@ -248,11 +271,42 @@ def select( return DecodeKernel.ENGINE if do_finalize or output is not None or args.gemm2_bias is not None: return DecodeKernel.CUBIN - if _cute_fc2_fits(kernel_runner, act_type, tactic, args, top_k, intermediate_size): + if cute_fc2_tile_k(kernel_runner, act_type, tactic, args, top_k, intermediate_size) is not None: return DecodeKernel.CUTE_FC2 return DecodeKernel.CUBIN +def cute_fc2_opt_in( + kernel_runner: torch.ScriptObject, + act_type: int, + tactic: List[int], + args: "FP4BlockScaleMoEInputs", + *, + top_k: int, + intermediate_size: int, + rows: int, + use_dp: bool, + do_finalize: bool, + output: Optional[torch.Tensor], +) -> Optional[int]: + """:func:`cute_fc2_tile_k` for a model's ``MoEDecodeOptions.cute_fc2_rows`` (``rows``): un-finalized attention-TP + calls of up to that many tokens on SM 10.0 / 10.3, without FC2 bias or output tensor.""" + _LAST_FC2.ptr, _LAST_FC2.node = 0, None + if rows <= 0 or use_dp or do_finalize or output is not None or args.gemm2_bias is not None: + return None + if not is_blackwell_datacenter(): + return None + return cute_fc2_tile_k( + kernel_runner, + act_type, + tactic, + args, + top_k, + intermediate_size, + max_tokens=rows, + ) + + def n_max_for(num_rows: int) -> int: """MMA N = rows per segment. Each ring stage reserves N x 128 B of activation room, so a smaller N leaves more stages for the weight stream; an expert with more rows than N splits into segments whose weights are read again, @@ -371,8 +425,11 @@ def run_cute_fc2( fc1_outputs: List[torch.Tensor], args: "FP4BlockScaleMoEInputs", lamport_out: Optional[torch.Tensor], + cubin_tile_k: Optional[int] = None, + record: bool = False, ) -> List[torch.Tensor]: - """``CUTE_FC2`` on the FC1-only runner's outputs; returns the runner's ``do_finalize=False`` triple.""" + """``CUTE_FC2`` on the FC1-only runner's outputs, bit for bit the FC2 cubin of tile K ``cubin_tile_k`` (None: the + kernel's); returns the runner's ``do_finalize=False`` triple. ``record``: the rows :func:`precedes` vouches for.""" from tensorrt_llm._torch.kernels.blackwell.moe_lowm_fc2 import moe_lowm_fc2 ( @@ -398,10 +455,67 @@ def run_cute_fc2( cta_limit, num_ctas.view(-1), out, + cubin_k_tile=cubin_tile_k, ) + if record: + state = _capture_state() + _LAST_FC2.ptr = out.data_ptr() + _LAST_FC2.node = (state[0], state[1][0]) if state and len(state[1]) == 1 else None return [out, expert_weights, expanded_idx_to_permuted_idx] +@dataclass +class _Fc2Record: + """A CuTe FC2 launch: its output address and, under graph capture, (capture id, kernel node).""" + + ptr: int = 0 + node: Optional[Tuple[int, int]] = None + + +#: The last recorded CuTe FC2 (:func:`run_cute_fc2`). +_LAST_FC2 = _Fc2Record() + + +def _capture_state() -> Optional[Tuple[int, List[int]]]: + """(capture id, dependency node addresses) of the current stream while a graph is captured.""" + if not torch.cuda.is_current_stream_capturing(): + return None + from cuda.bindings import driver + + res = driver.cuStreamGetCaptureInfo(driver.CUstream(torch.cuda.current_stream().cuda_stream)) + if res[0] != driver.CUresult.CUDA_SUCCESS: + return None + if res[1] != driver.CUstreamCaptureStatus.CU_STREAM_CAPTURE_STATUS_ACTIVE: + return None + deps = next((x for x in res[3:] if isinstance(x, (list, tuple))), None) + if deps is None: + return None + return int(res[2]), [_node_id(d) for d in deps] + + +def _node_id(node: object) -> int: + try: + return int(node) + except TypeError: + return int(node.getPtr()) + + +def precedes(fc2: torch.Tensor) -> Tuple[bool, str]: + """(Whether ``fc2`` is the last recorded CuTe FC2's output and that launch is a dependency of the current stream's + next launch in the captured graph, reason). The FC2 releases its dependents after its own wait.""" + # Each FC2 launch vouches for one boundary at most. + ptr, node = _LAST_FC2.ptr, _LAST_FC2.node + _LAST_FC2.ptr, _LAST_FC2.node = 0, None + if not ptr or fc2.data_ptr() != ptr: + return False, "rows not from the last CuTe FC2" + state = _capture_state() + if state is None: + return False, "not captured" + if node is None or node[0] != state[0] or node[1] not in state[1]: + return False, "CuTe FC2 not a dependency of the boundary" + return True, "behind the CuTe FC2" + + def rows_in_lamport(rows: torch.Tensor, lamport_out: Optional[torch.Tensor]) -> bool: """Whether an un-finalized call's FC2 ``rows`` are the Lamport buffer ``lamport_out`` (``ENGINE`` / ``CUTE_FC2`` wrote them there); a ``CUBIN`` call returns rows of its own and leaves the buffer untouched.""" diff --git a/tensorrt_llm/_torch/moe/fused_moe/trtllm_gen/fp4_block_scale.py b/tensorrt_llm/_torch/moe/fused_moe/trtllm_gen/fp4_block_scale.py index 8c38ad18ac73..8dbb32b3db78 100644 --- a/tensorrt_llm/_torch/moe/fused_moe/trtllm_gen/fp4_block_scale.py +++ b/tensorrt_llm/_torch/moe/fused_moe/trtllm_gen/fp4_block_scale.py @@ -247,6 +247,13 @@ def run_moe( output1_scale_scalar = get_data_or_none(self, "fc31_scale_c") output1_scale_gate_scalar = get_data_or_none(self, "fc31_alpha") output2_scale_scalar = get_data_or_none(self, "fc2_alpha") + # Dynamic EP: the weights hold every expert; calls without tables run the static range. + local_offset, local_count = self.slot_start, self.expert_size_per_partition + dynamic_ep = getattr(self, "dynamic_ep", None) + dynamic_kwargs = {} + if dynamic_ep is not None: + local_offset, local_count = dynamic_ep[0], dynamic_ep[1] + dynamic_kwargs = {"dynamic_experts": self.expert_size_per_partition} outputs = self.op_backend.run_fp4_block_scale_moe( k.router_logits, @@ -270,8 +277,8 @@ def run_moe( k.n_group, k.topk_group, intermediate_size_per_partition_padded, - self.slot_start, - self.expert_size_per_partition, + local_offset, + local_count, k.routed_scaling_factor, self.routing_method.routing_method_type, do_finalize=k.do_finalize, @@ -293,6 +300,8 @@ def run_moe( decode_early_release_rows=self.decode_early_release_rows, decode_spare_sms=self._concurrent_sm_reserve, routing_tables=ctx.routing_tables, + cute_fc2_rows=self.cute_fc2_rows, + **dynamic_kwargs, ) if not k.do_finalize: diff --git a/tensorrt_llm/_torch/moe/fused_moe/trtllm_gen/trtllm_nvfp4.py b/tensorrt_llm/_torch/moe/fused_moe/trtllm_gen/trtllm_nvfp4.py index eba067470da5..bc0605dcb29e 100644 --- a/tensorrt_llm/_torch/moe/fused_moe/trtllm_gen/trtllm_nvfp4.py +++ b/tensorrt_llm/_torch/moe/fused_moe/trtllm_gen/trtllm_nvfp4.py @@ -34,9 +34,11 @@ if IS_CUTLASS_DSL_AVAILABLE: from ....moe.kernels.blackwell.dsv4_route_quant import ( ROUTING_TABLE_TILES, + ROUTING_TABLES_MAX_TOKENS, can_build_routing_tables, dsv4_route, dsv4_route_nvfp4_quant, + routing_table_max_ctas, ) @@ -59,6 +61,9 @@ class TrtllmTrtllmGenNvfp4Impl(TRTLLMGenNvfp4Base): #: The native op's ``lamport_fc2_out``. takes_lamport_fc2_out = True + #: Rows up to which the route kernel's tables split each call's experts over the EP ranks. + dynamic_ep_max_rows = ROUTING_TABLES_MAX_TOKENS if IS_CUTLASS_DSL_AVAILABLE else 0 + #: Whether routing runs as one launch, fused with quantization, and with routing tables; set #: after loading. _fuses_route = False @@ -111,6 +116,25 @@ def _routing_table_experts(self, rows: int) -> tuple[int, int] | None: return self.slot_start, self.expert_size_per_partition return None + def _table_scope(self, rows: int) -> tuple[bool, dict]: + """Whether a run of ``rows`` tokens gets routing tables, and the route kernel's scope for + them: this rank's slot range, or with dynamic expert parallelism its rank and EP size.""" + local_experts = self._routing_table_experts(rows) + if local_experts is None: + return False, {} + dynamic_ep = getattr(self, "dynamic_ep", None) + if dynamic_ep is not None: + return True, {"dynamic_ep": (dynamic_ep[2], dynamic_ep[3])} + return True, {"local_experts": local_experts} + + def _routing_tables( + self, tables: torch.Tensor, tiles: tuple[int, ...], rows: int, scope: dict + ) -> MoERoutingTables: + max_ctas = routing_table_max_ctas( + rows, self.routing_method.top_k, self.num_experts, scope.get("dynamic_ep") + ) + return MoERoutingTables(tables, tiles, max_ctas) + def try_fused_route( self, x: Fp4QuantizedTensor, router_logits: torch.Tensor ) -> MoEFusedRouteQuant | None: @@ -120,8 +144,7 @@ def try_fused_route( if not self._fuses_route or x.is_sf_swizzled or self.fc31_act_scale is not None: return None rows = x.shape[0] - local_experts = self._routing_table_experts(rows) - with_tables = local_experts is not None + with_tables, scope = self._table_scope(rows) tiles = self._routing_table_tiles(rows) ids, weights, tables = dsv4_route( router_logits, @@ -131,15 +154,18 @@ def try_fused_route( self.input_requirement.routing_scales_dtype, self.hidden_size, with_routing_tables=with_tables, - local_experts=local_experts, routing_tiles=tiles, + one_cluster=self.one_cluster_route, + **scope, ) return MoEFusedRouteQuant( ids, weights, x.fp4_tensor, x.scaling_factor.view(rows, -1), - routing_tables=MoERoutingTables(tables, tiles) if with_tables else None, + routing_tables=self._routing_tables(tables, tiles, rows, scope) + if with_tables + else None, ) def try_fused_route_quant( @@ -149,8 +175,7 @@ def try_fused_route_quant( routing tables for small batches.""" if not self._fuses_route_quant: return None - local_experts = self._routing_table_experts(x.shape[0]) - with_tables = local_experts is not None + with_tables, scope = self._table_scope(x.shape[0]) tiles = self._routing_table_tiles(x.shape[0]) ids, weights, x_fp4, x_sf, tables = dsv4_route_nvfp4_quant( router_logits, @@ -161,13 +186,16 @@ def try_fused_route_quant( self.routing_method.routed_scaling_factor, self.input_requirement.routing_scales_dtype, with_routing_tables=with_tables, - local_experts=local_experts, routing_tiles=tiles, + one_cluster=self.one_cluster_route, + **scope, ) return MoEFusedRouteQuant( ids, weights, x_fp4, x_sf, - routing_tables=MoERoutingTables(tables, tiles) if with_tables else None, + routing_tables=self._routing_tables(tables, tiles, x.shape[0], scope) + if with_tables + else None, ) diff --git a/tensorrt_llm/_torch/moe/kernels/blackwell/dsv4_route_one.py b/tensorrt_llm/_torch/moe/kernels/blackwell/dsv4_route_one.py new file mode 100644 index 000000000000..c741fcacf568 --- /dev/null +++ b/tensorrt_llm/_torch/moe/kernels/blackwell/dsv4_route_one.py @@ -0,0 +1,604 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""DeepSeek-V4 decode routing + TRTLLM-Gen routing tables in one 8-block cluster (NVRTC, first +eager call); the CuTe DSL route kernel's bits except the row order inside an expert's block.""" + +from __future__ import annotations + +import ctypes +import os +import threading +from typing import Optional + +import torch + +from tensorrt_llm._utils import get_sm_version + +MAX_TOKENS = 8 # a block per token in the 8-block cluster +NUM_EXPERTS = 384 +TOP_K = 6 +MAX_TILES = 3 +_CLUSTER = 8 +_THREADS = 384 + +_SRC = r""" +#include + +#define CLUSTER 8 +#define THREADS 384 // one thread per expert +#define NWARPS (THREADS / 32) +#define NEXP 384 +#define TOPK 6 +#define KPAD 512 // keys order equal selections by KPAD - 1 - expert: the lower expert first +#define NCAND (NWARPS * TOPK) // every warp's top 6 +#define MAX_ROWS CLUSTER // a token per block +#define MAX_PAIRS (MAX_ROWS * TOPK) +#define KEY_NONE ((long long)0x8000000000000000ll) +#define FULL 0xFFFFFFFFu + +namespace route { + +__device__ __forceinline__ float mul_rn(float a, float b) { + float r; + asm("mul.rn.f32 %0, %1, %2;" : "=f"(r) : "f"(a), "f"(b)); + return r; +} + +__device__ __forceinline__ float add_rn(float a, float b) { + float r; + asm("add.rn.f32 %0, %1, %2;" : "=f"(r) : "f"(a), "f"(b)); + return r; +} + +__device__ __forceinline__ float div_rn(float a, float b) { + float r; + asm("div.rn.f32 %0, %1, %2;" : "=f"(r) : "f"(a), "f"(b)); + return r; +} + +__device__ __forceinline__ float rcp_approx_ftz(float v) { + float r; + asm("rcp.approx.ftz.f32 %0, %1;" : "=f"(r) : "f"(v)); + return r; +} + +__device__ __forceinline__ float abs_f32(float v) { + float r; + asm("abs.f32 %0, %1;" : "=f"(r) : "f"(v)); + return r; +} + +__device__ __forceinline__ float max_f32(float a, float b) { + float r; + asm("max.f32 %0, %1, %2;" : "=f"(r) : "f"(a), "f"(b)); + return r; +} + +// sqrt(softplus(l)), threshold 20: libdevice's expf / log1pf instruction sequences (flush to zero, no contraction), +// branch-free, then sqrt.rn. +__device__ __forceinline__ float route_score(float l) { + float s; + asm("{\n\t" + ".reg .pred p1, p2, p3, p4;\n\t" + ".reg .b32 c1, c2, c3, c4, c5, c6, t5, t6, t9, t10, t11, t13, t15, t16, t17, e, t19, t20, t21, t22, t23, t26;\n\t" + ".reg .b32 t27, t28, t29, t32, t34, t36, t38, t40, t42, t44, t46, t47, t48, lp, t51, t52, t53, sp;\n\t" + "mov.b32 c1, 0f3F000000;\n\t" + "mov.b32 c2, 0f3BBB989D;\n\t" + "fma.rn.ftz.f32 t5, %1, c2, c1;\n\t" + "cvt.ftz.sat.f32.f32 t6, t5;\n\t" + "mov.b32 c3, 0f4B400001;\n\t" + "mov.b32 c4, 0f437C0000;\n\t" + "fma.rm.ftz.f32 t9, t6, c4, c3;\n\t" + "add.rn.ftz.f32 t10, t9, 0fCB40007F;\n\t" + "neg.ftz.f32 t11, t10;\n\t" + "mov.b32 c5, 0f3FB8AA3B;\n\t" + "fma.rn.ftz.f32 t13, %1, c5, t11;\n\t" + "mov.b32 c6, 0f32A57060;\n\t" + "fma.rn.ftz.f32 t15, %1, c6, t13;\n\t" + "shl.b32 t16, t9, 23;\n\t" + "ex2.approx.ftz.f32 t17, t15;\n\t" + "mul.rn.ftz.f32 e, t17, t16;\n\t" + "mov.b32 c1, 0f3F800000;\n\t" + "add.rz.ftz.f32 t19, e, c1;\n\t" + "add.s32 t20, t19, -1061158912;\n\t" + "and.b32 t21, t20, -8388608;\n\t" + "sub.s32 t22, e, t21;\n\t" + "sub.s32 t23, 1082130432, t21;\n\t" + "mov.b32 c1, 0fBF800000;\n\t" + "mov.b32 c2, 0f3E800000;\n\t" + "fma.rn.ftz.f32 t26, c2, t23, c1;\n\t" + "add.rn.ftz.f32 t27, t26, t22;\n\t" + "cvt.rn.f32.s32 t28, t21;\n\t" + "mul.rn.ftz.f32 t29, t28, 0f34000000;\n\t" + "mov.b32 c1, 0f3DD80012;\n\t" + "mov.b32 c2, 0fBD39BF78;\n\t" + "fma.rn.ftz.f32 t32, c2, t27, c1;\n\t" + "mov.b32 c1, 0fBE0778E0;\n\t" + "fma.rn.ftz.f32 t34, t32, t27, c1;\n\t" + "mov.b32 c1, 0f3E146475;\n\t" + "fma.rn.ftz.f32 t36, t34, t27, c1;\n\t" + "mov.b32 c1, 0fBE2A68DD;\n\t" + "fma.rn.ftz.f32 t38, t36, t27, c1;\n\t" + "mov.b32 c1, 0f3E4CAF9E;\n\t" + "fma.rn.ftz.f32 t40, t38, t27, c1;\n\t" + "mov.b32 c1, 0fBE800042;\n\t" + "fma.rn.ftz.f32 t42, t40, t27, c1;\n\t" + "mov.b32 c1, 0f3EAAAAE6;\n\t" + "fma.rn.ftz.f32 t44, t42, t27, c1;\n\t" + "mov.b32 c1, 0fBF000000;\n\t" + "fma.rn.ftz.f32 t46, t44, t27, c1;\n\t" + "mul.rn.ftz.f32 t47, t27, t46;\n\t" + "fma.rn.ftz.f32 t48, t47, t27, t27;\n\t" + "mov.b32 c1, 0f3F317218;\n\t" + "fma.rn.ftz.f32 lp, t29, c1, t48;\n\t" + "setp.lt.u32 p2, e, 2139095040;\n\t" + "setp.gt.s32 p3, e, -1082130432;\n\t" + "mov.b32 c1, 0f7F800000;\n\t" + "fma.rn.ftz.f32 t51, e, c1, c1;\n\t" + "selp.f32 t52, t51, lp, p3;\n\t" + "setp.eq.ftz.f32 p4, e, 0f00000000;\n\t" + "selp.f32 t53, 0f80000000, t52, p4;\n\t" + "selp.f32 lp, lp, t53, p2;\n\t" + "setp.gt.ftz.f32 p1, %1, 0f41A00000;\n\t" + "selp.f32 sp, %1, lp, p1;\n\t" + "sqrt.rn.f32 %0, sp;\n\t" + "}" + : "=f"(s) + : "f"(l)); + return s; +} + +// Float bits in signed-integer order (NaN above +inf, as the route kernel's keys). +__device__ __forceinline__ int ordered_bits(float v) { + const int bits = __float_as_int(v); + return bits < 0 ? (bits ^ 0x7FFFFFFF) : bits; +} + +__device__ __forceinline__ unsigned short to_bf16_rn(float v) { + unsigned short b; + asm("cvt.rn.bf16.f32 %0, %1;" : "=h"(b) : "f"(v)); + return b; +} + +// One 16-element NVFP4 block of BF16 inputs (fp4_quantize: E2M1 codes, element 2i in the low nibble of byte i, and the +// UE4M3 block scale). +__device__ __forceinline__ void quant16(uint4 lo, uint4 hi, float global_scale, uint2* codes, unsigned char* sf) { + const float rcp6 = rcp_approx_ftz(6.0f); + const float rcp_gs = rcp_approx_ftz(mul_rn(1.0f, global_scale)); + const unsigned w[8] = {lo.x, lo.y, lo.z, lo.w, hi.x, hi.y, hi.z, hi.w}; + float v[16]; +#pragma unroll + for (int i = 0; i < 8; ++i) { + v[2 * i] = __uint_as_float(w[i] << 16); + v[2 * i + 1] = __uint_as_float(w[i] & 0xFFFF0000u); + } + float vmax = abs_f32(v[0]); +#pragma unroll + for (int i = 1; i < 16; ++i) vmax = max_f32(vmax, abs_f32(v[i])); + const float s = mul_rn(global_scale, mul_rn(vmax, rcp6)); + unsigned short s2; + asm("cvt.rn.satfinite.e4m3x2.f32 %0, %1, %2;" : "=h"(s2) : "f"(0.0f), "f"(s)); + const unsigned char s8 = (unsigned char)(s2 & 0xFF); + float sfv; + asm("{\n\t.reg .b32 h2;\n\t.reg .b16 l16, h16;\n\t" + "cvt.rn.f16x2.e4m3x2 h2, %1;\n\t" + "mov.b32 {l16, h16}, h2;\n\t" + "cvt.f32.f16 %0, l16;\n\t}" + : "=f"(sfv) + : "h"((unsigned short)s8)); + float out_scale; + asm("{\n\t.reg .pred nz;\n\t.reg .f32 r;\n\t" + "setp.neu.f32 nz, %1, 0f00000000;\n\t" + "mul.rn.f32 r, %2, %3;\n\t" + "rcp.approx.ftz.f32 r, r;\n\t" + "selp.f32 %0, r, 0f00000000, nz;\n\t}" + : "=f"(out_scale) + : "f"(vmax), "f"(sfv), "f"(rcp_gs)); + unsigned q[2] = {0u, 0u}; +#pragma unroll + for (int j = 0; j < 8; ++j) { + const float a = mul_rn(v[2 * j], out_scale), b = mul_rn(v[2 * j + 1], out_scale); + unsigned byte; + asm("{ .reg .b8 t; cvt.rn.satfinite.e2m1x2.f32 t, %1, %2; cvt.u32.u8 %0, t; }" : "=r"(byte) : "f"(b), "f"(a)); + q[j >> 2] |= byte << (8 * (j & 3)); + } + *codes = make_uint2(q[0], q[1]); + *sf = s8; +} + +} // namespace route + +__device__ __forceinline__ unsigned smem_u32(const void* p) { return (unsigned)__cvta_generic_to_shared(p); } +__device__ __forceinline__ unsigned cluster_addr(unsigned local, unsigned rank) { + unsigned r; + asm volatile("mapa.shared::cluster.u32 %0, %1, %2;" : "=r"(r) : "r"(local), "r"(rank)); + return r; +} + +// The largest of the warp's keys (selection bits, then the lower expert), in every lane. +__device__ __forceinline__ long long warp_max_key(long long key) { + const int hi = (int)(key >> 32); + const int top = __reduce_max_sync(FULL, hi); + const unsigned low = __reduce_max_sync(FULL, hi == top ? (unsigned)(key & 0xFFFFFFFFll) : 0u); + return ((long long)top << 32) | low; +} + +// The routing tables by one warp (an expert's picks fit one CTA: m <= every tile): a pick per lane and pass, s_cnt +// [NEXP] and s_bits [NEXP / 32] zeroed. A pick's row is its expert's pick count before it (any order is valid); this +// rank's experts in use get CTAs in expert order. +__device__ __forceinline__ void tables_warp(const int* s_pick, int* s_cnt, unsigned* s_bits, int m, int* tables, + int width, int num_tiles, int tile0, int tile1, int tile2, + int local_start, int num_local, int dyn_rank, int dyn_size) { + const int lane = threadIdx.x & 31, n = m * TOPK; + int e[2], rank[2] = {0, 0}; +#pragma unroll + for (int h = 0; h < 2; ++h) { + e[h] = lane + 32 * h < n ? s_pick[lane + 32 * h] : -1; + if (e[h] >= 0) { + rank[h] = atomicAdd(&s_cnt[e[h]], 1); + atomicOr(&s_bits[e[h] >> 5], 1u << (e[h] & 31)); + } + } + __syncwarp(); + // Lane w holds used-expert bits w; excl: experts in use below them. + const unsigned bits = lane < NEXP / 32 ? s_bits[lane] : 0u; + int incl = __popc(bits); +#pragma unroll + for (int o = 1; o < 32; o <<= 1) { + const int t = __shfl_up_sync(FULL, incl, o); + incl += lane >= o ? t : 0; + } + const int excl = incl - __popc(bits); + const int total = __shfl_sync(FULL, incl, 31); + // Experts in use below x, for any x in [0, NEXP]; every lane shuffles. + auto used_before = [&](int x) { + const int w = x >> 5; + const unsigned below = __shfl_sync(FULL, bits, w) & ((1u << (x & 31)) - 1u); + return __shfl_sync(FULL, excl, w) + __popc(below); + }; + // As the CuTe kernel's home_first_owner for two ranks: a rank keeps its range's first ceil(total / 2) experts in use. + const int lower = used_before(NEXP / 2), cap = (total + 1) >> 1; + const int mine_lower = dyn_rank == 0 ? min(lower, cap) : max(lower - cap, 0); + const int mine_upper = dyn_rank == 1 ? min(total - lower, cap) : max(total - lower - cap, 0); + const int first = used_before(local_start); + const int ctas = dyn_size == 2 ? mine_lower + mine_upper : used_before(local_start + num_local) - first; + bool mine[2]; + int cta[2], cnt[2]; +#pragma unroll + for (int h = 0; h < 2; ++h) { + const int below = used_before(max(e[h], 0)); + if (dyn_size == 2) { + const int home = e[h] >= NEXP / 2, idx = below - (home ? lower : 0), moved = idx >= cap; + mine[h] = e[h] >= 0 && (moved ? 1 - home : home) == dyn_rank; + cta[h] = (home ? mine_lower : 0) + (moved ? idx - cap : idx); + } else { + mine[h] = e[h] >= local_start && e[h] < local_start + num_local; + cta[h] = below - first; + } + cnt[h] = mine[h] ? s_cnt[e[h]] : 0; + } + for (int t = 0; t < num_tiles; ++t) { + const int tile = t == 0 ? tile0 : (t == 1 ? tile1 : tile2); + int* const e2p = tables + (long long)t * 5 * width; + int* const p2t = e2p + width; + int* const cta_expert = e2p + 2 * width; + int* const cta_limit = e2p + 3 * width; + int* const totals = e2p + 4 * width; +#pragma unroll + for (int h = 0; h < 2; ++h) { + const int i = lane + 32 * h; + if (i < n) { + if (mine[h]) { + const int permuted = cta[h] * tile + rank[h]; + e2p[i] = permuted; + p2t[permuted] = i / TOPK; + if (rank[h] == 0) { + cta_expert[cta[h]] = e[h] - local_start; + cta_limit[cta[h]] = cta[h] * tile + cnt[h]; + } + } else { + e2p[i] = -1; + } + } + } + if (lane == 0) { + totals[0] = ctas; + totals[1] = ctas * tile; + } + } +} + +// tables: [num_tiles, 5, width] (expanded -> permuted, permuted -> token, CTA -> expert, CTA -> row limit, +// (CTAs, padded rows)), experts numbered from local_start; null routes (and quantizes) only. With dyn_size == 2 both +// ranks hold every expert and the tables cover rank dyn_rank's share of the used ones (the CuTe kernel's +// home_first_owner). Static inputs (bias, global scale) are read before the dependency wait, the logits and x after it. +extern "C" __global__ void __cluster_dims__(CLUSTER, 1, 1) __launch_bounds__(THREADS, 1) dsv4_route_one( + const float* logits, const float* __restrict__ bias, const __nv_bfloat16* x, + const float* __restrict__ global_scale, int* ids, void* weights_out, unsigned char* xq, unsigned char* xsf, + float rsf, long long stride_x, int m, int hidden, int weights_bf16, int* tables, int width, int num_tiles, + int tile0, int tile1, int tile2, int local_start, int num_local, int dyn_rank, int dyn_size) { + __shared__ float s_sc[NEXP]; + __shared__ long long s_ck[NCAND]; + __shared__ __align__(8) unsigned long long s_bar; // block 0: completes once every pick has landed + __shared__ int s_pick[MAX_PAIRS]; + __shared__ int s_cnt[NEXP]; + __shared__ unsigned s_bits[NEXP / 32]; + const int cta = blockIdx.x; + const int tid = threadIdx.x, warp = tid >> 5, lane = tid & 31; + const bool with_tables = tables != nullptr; + const int n = m * TOPK; + const float my_bias = bias[tid]; + const float gs = xq != nullptr ? *global_scale : 0.0f; + if (with_tables) { + if (cta == 0) { + s_cnt[tid] = 0; + if (tid < NEXP / 32) s_bits[tid] = 0; + if (tid == 0) { + asm volatile("mbarrier.init.shared::cta.b64 [%0], 1;" ::"r"(smem_u32(&s_bar))); + asm volatile("mbarrier.arrive.expect_tx.shared::cta.b64 _, [%0], %1;" ::"r"(smem_u32(&s_bar)), "r"(n * 4) + : "memory"); + asm volatile("fence.mbarrier_init.release.cluster;" ::: "memory"); + } + } + asm volatile("barrier.cluster.arrive.relaxed.aligned;" ::: "memory"); + asm volatile("barrier.cluster.wait.acquire.aligned;" ::: "memory"); + } +#ifdef USE_PDL + asm volatile("griddepcontrol.wait;" ::: "memory"); +#endif + // The expert GEMM that follows reads nothing before its own dependency wait: it may launch now. + asm volatile("griddepcontrol.launch_dependents;" ::: "memory"); + const int row = cta; + if (row < m) { + const float sc = route::route_score(logits[(long long)row * NEXP + tid]); + s_sc[tid] = sc; + long long key = ((long long)route::ordered_bits(route::add_rn(sc, my_bias)) << 32) | (unsigned)(KPAD - 1 - tid); +#pragma unroll + for (int k = 0; k < TOPK; ++k) { + const long long win = warp_max_key(key); + if (lane == 0) s_ck[warp * TOPK + k] = win; + key = key == win ? KEY_NONE : key; + } + __syncthreads(); + if (warp == 0) { + // Lane l holds candidates l, l + 32, l + 64 in descending order; each maximum's winner drops its first. + long long c3[3]; +#pragma unroll + for (int j = 0; j < 3; ++j) c3[j] = lane + 32 * j < NCAND ? s_ck[lane + 32 * j] : KEY_NONE; +#pragma unroll + for (int i = 1; i < 3; ++i) { +#pragma unroll + for (int j = i; j > 0; --j) { + const long long a = c3[j - 1], b = c3[j]; + c3[j - 1] = a > b ? a : b; + c3[j] = a > b ? b : a; + } + } + int ek[TOPK]; +#pragma unroll + for (int k = 0; k < TOPK; ++k) { + const long long win = warp_max_key(c3[0]); + ek[k] = KPAD - 1 - (int)(unsigned)(win & 0xFFFFFFFFll); + if (c3[0] == win) { + c3[0] = c3[1]; + c3[1] = c3[2]; + c3[2] = KEY_NONE; + } + } + float p[TOPK]; +#pragma unroll + for (int k = 0; k < TOPK; ++k) p[k] = s_sc[ek[k]]; + int e = ek[0]; + float sk = p[0]; +#pragma unroll + for (int k = 1; k < TOPK; ++k) { + if (lane == k) { + e = ek[k]; + sk = p[k]; + } + } + if (lane < TOPK) { + // The route kernel's warp sum of the six scores: ((p0 + p4) + (p2 + 0)) + ((p1 + p5) + (p3 + 0)). + const float total = route::add_rn(route::add_rn(route::add_rn(p[0], p[4]), route::add_rn(p[2], 0.0f)), + route::add_rn(route::add_rn(p[1], p[5]), route::add_rn(p[3], 0.0f))); + const float w = route::mul_rn(route::div_rn(sk, route::add_rn(total, 1e-20f)), rsf); + if (with_tables) { + asm volatile("st.async.shared::cluster.mbarrier::complete_tx::bytes.s32 [%0], %1, [%2];" ::"r"( + cluster_addr(smem_u32(&s_pick[row * TOPK + lane]), 0)), + "r"(e), "r"(cluster_addr(smem_u32(&s_bar), 0)) + : "memory"); + } + ids[row * TOPK + lane] = e; + if (weights_bf16) { + reinterpret_cast(weights_out)[row * TOPK + lane] = route::to_bf16_rn(w); + } else { + reinterpret_cast(weights_out)[row * TOPK + lane] = w; + } + } + } + } + if (cta > 0) { + if (xq != nullptr) { + const int nb = hidden / 16; + for (int q = (cta - 1) * THREADS + tid; q < m * nb; q += (CLUSTER - 1) * THREADS) { + const int r = q / nb, b = q - r * nb; + const uint4* src = reinterpret_cast(x + r * stride_x + (long long)b * 16); + const uint4 lo = src[0], hi = src[1]; + uint2 codes; + unsigned char sf; + route::quant16(lo, hi, gs, &codes, &sf); + *reinterpret_cast(xq + (long long)r * (hidden / 2) + b * 8) = codes; + xsf[(long long)r * nb + b] = sf; + } + } + return; + } + if (!with_tables) return; + // ---- block 0: the tables, from shared memory ---- + asm volatile( + "{\n\t.reg .pred p;\n\tW_%=:\n\tmbarrier.try_wait.parity.acquire.cluster.shared::cta.b64 p, [%0], 0;\n\t" + "@!p bra W_%=;\n\t}" ::"r"(smem_u32(&s_bar)) + : "memory"); + if (warp == 0) { + tables_warp(s_pick, s_cnt, s_bits, m, tables, width, num_tiles, tile0, tile1, tile2, local_start, num_local, + dyn_rank, dyn_size); + } +} +""" + + +class _Kernel: + def __init__(self, device_index: int, pdl: bool): + from cuda.bindings import driver as cu + from cuda.bindings import nvrtc + + def check(res): + err = res[0] + ok = ( + err == cu.CUresult.CUDA_SUCCESS + if isinstance(err, cu.CUresult) + else err == nvrtc.nvrtcResult.NVRTC_SUCCESS + ) + if not ok: + raise RuntimeError(f"dsv4_route_one: {err}") + return res[1] if len(res) == 2 else res[1:] + + self._cu, self._check = cu, check + prog = check(nvrtc.nvrtcCreateProgram(_SRC.encode(), b"dsv4_route_one.cu", 0, [], [])) + major, minor = torch.cuda.get_device_capability(device_index) + cuda_home = os.environ.get("CUDA_HOME") or os.environ.get("CUDA_PATH") or "/usr/local/cuda" + # The architecture-specific target has the E2M1 / E4M3 conversions. + opts = [ + f"--gpu-architecture=sm_{major}{minor}a".encode(), + b"-std=c++17", + f"--include-path={cuda_home}/include".encode(), + ] + if pdl: + opts.append(b"-DUSE_PDL") + if nvrtc.nvrtcCompileProgram(prog, len(opts), opts)[0] != nvrtc.nvrtcResult.NVRTC_SUCCESS: + size = check(nvrtc.nvrtcGetProgramLogSize(prog)) + log = b" " * size + nvrtc.nvrtcGetProgramLog(prog, log) + raise RuntimeError("dsv4_route_one: NVRTC failed:\n" + log.decode(errors="replace")) + cubin = b" " * check(nvrtc.nvrtcGetCUBINSize(prog)) + check(nvrtc.nvrtcGetCUBIN(prog, cubin)) + nvrtc.nvrtcDestroyProgram(prog) + # cuModuleLoadData needs the device's primary context current. + torch.zeros(1, device=torch.device("cuda", device_index)) + self.module = check(cu.cuModuleLoadData(cubin)) + self.fn = check(cu.cuModuleGetFunction(self.module, b"dsv4_route_one")) + self.pdl = pdl + + def launch(self, args) -> None: + cu = self._cu + cfg = cu.CUlaunchConfig() + cfg.gridDimX, cfg.gridDimY, cfg.gridDimZ = _CLUSTER, 1, 1 + cfg.blockDimX, cfg.blockDimY, cfg.blockDimZ = _THREADS, 1, 1 + cfg.sharedMemBytes = 0 + cfg.hStream = cu.CUstream(torch.cuda.current_stream().cuda_stream) + cfg.numAttrs = 0 + if self.pdl: + attr = cu.CUlaunchAttribute() + attr.id = cu.CUlaunchAttributeID.CU_LAUNCH_ATTRIBUTE_PROGRAMMATIC_STREAM_SERIALIZATION + attr.value.programmaticStreamSerializationAllowed = 1 + cfg.attrs = [attr] + cfg.numAttrs = 1 + ptrs = (ctypes.c_void_p * len(args))(*[ctypes.addressof(a) for a in args]) + self._check(cu.cuLaunchKernelEx(cfg, self.fn, ctypes.addressof(ptrs), 0)) + + +_kernels: dict[tuple[int, bool], _Kernel] = {} +_lock = threading.Lock() +_unavailable = False + + +def _kernel(device_index: int, pdl: bool) -> Optional[_Kernel]: + """The device's kernel, compiled at the first eager call (never inside a graph capture).""" + global _unavailable + key = (device_index, pdl) + kernel = _kernels.get(key) + if kernel is not None or _unavailable or torch.cuda.is_current_stream_capturing(): + return kernel + with _lock: + kernel = _kernels.get(key) + if kernel is None: + try: + kernel = _Kernel(*key) + except (RuntimeError, ImportError) as e: + _unavailable = True + from tensorrt_llm.logger import logger + + logger.warning(f"DeepSeek-V4 one-cluster route kernel unavailable ({e})") + return None + _kernels[key] = kernel + return kernel + + +def applies(num_tokens: int, num_experts: int, top_k: int, routing_tiles: tuple[int, ...]) -> bool: + """Whether a routing-table launch of this shape takes the one-cluster kernel.""" + return ( + 0 < num_tokens <= MAX_TOKENS + and num_experts == NUM_EXPERTS + and top_k == TOP_K + and 0 < len(routing_tiles) <= MAX_TILES + and get_sm_version() in (100, 103) + ) + + +def route_one( + logits: torch.Tensor, + bias: torch.Tensor, + routed_scaling_factor: float, + ids: torch.Tensor, + weights: torch.Tensor, + tables: torch.Tensor, + routing_tiles: tuple[int, ...], + local_start: int, + num_local: int, + pdl: bool, + dynamic_ep: Optional[tuple[int, int]] = None, + x: Optional[torch.Tensor] = None, + global_scale: Optional[torch.Tensor] = None, + x_fp4: Optional[torch.Tensor] = None, + x_sf: Optional[torch.Tensor] = None, +) -> bool: + """Route (and with ``x`` quantize) as ``dsv4_route`` / ``dsv4_route_nvfp4_quant`` with tables; + False leaves the call to them (an input layout it does not take, or no compiled kernel).""" + num_tokens = logits.shape[0] + if ( + logits.dtype != torch.float32 + or not logits.is_contiguous() + or bias.dtype != torch.float32 + or not bias.is_contiguous() + or weights.dtype not in (torch.float32, torch.bfloat16) + or not tables.is_contiguous() + ): + return False + if x is not None and ( + x.dtype != torch.bfloat16 + or x.stride(1) != 1 + or (x.stride(0) * x.element_size()) % 16 + or x.data_ptr() % 16 + or x.shape[1] % 16 + or global_scale.dtype != torch.float32 + ): + return False + kernel = _kernel(logits.device.index, pdl) + if kernel is None: + return False + + def ptr(t: Optional[torch.Tensor]) -> ctypes.c_uint64: + return ctypes.c_uint64(0 if t is None else t.data_ptr()) + + tiles = tuple(routing_tiles) + (routing_tiles[-1],) * (MAX_TILES - len(routing_tiles)) + args = [ + ptr(logits), ptr(bias), ptr(x), ptr(global_scale), ptr(ids), ptr(weights), ptr(x_fp4), ptr(x_sf), + ctypes.c_float(routed_scaling_factor), ctypes.c_int64(0 if x is None else x.stride(0)), + ctypes.c_int32(num_tokens), ctypes.c_int32(0 if x is None else x.shape[1]), + ctypes.c_int32(1 if weights.dtype == torch.bfloat16 else 0), ptr(tables), + ctypes.c_int32(tables.shape[2]), ctypes.c_int32(len(routing_tiles)), + *(ctypes.c_int32(t) for t in tiles), ctypes.c_int32(local_start), ctypes.c_int32(num_local), + *(ctypes.c_int32(v) for v in (dynamic_ep or (0, 0))), + ] # fmt: skip + kernel.launch(args) + return True diff --git a/tensorrt_llm/_torch/moe/kernels/blackwell/dsv4_route_quant.py b/tensorrt_llm/_torch/moe/kernels/blackwell/dsv4_route_quant.py index a4deee8bbf4d..56cf5bbe32b5 100644 --- a/tensorrt_llm/_torch/moe/kernels/blackwell/dsv4_route_quant.py +++ b/tensorrt_llm/_torch/moe/kernels/blackwell/dsv4_route_quant.py @@ -16,6 +16,8 @@ from tensorrt_llm._torch.kernels.blackwell.utils import TRTLLM_ENABLE_PDL, griddepcontrol_wait +from . import dsv4_route_one as route_one + try: from cuda.bindings import driver as cuda except ImportError: @@ -197,9 +199,11 @@ class DSv4RouteNvfp4QuantKernel: a flag, a live-row bound, with ``count_mask`` a row mask, and rows with all-zero logits skipped). ``mxfp8`` also writes each token as MXFP8. Without ``quant`` the launch only routes (an input the producer already quantized). With ``num_local`` the tables cover the experts - ``[local_start, local_start + num_local)`` of an expert-parallel rank, numbered from 0. ``pdl`` - launches it as a programmatic dependent of the previous kernel. With ``splits`` > 1 the logits - are K-chunk partials ``[splits, tokens, experts]``, summed s = 0 .. splits-1 as they load. + ``[local_start, local_start + num_local)`` of an expert-parallel rank, numbered from 0; with + ``dynamic_ep`` = (rank, 2) both ranks hold all experts and the tables cover this rank's share of + the used ones (``home_first_owner``). ``pdl`` launches it as a programmatic dependent of the + previous kernel. With ``splits`` > 1 the logits are K-chunk partials ``[splits, tokens, + experts]``, summed s = 0 .. splits-1 as they load. """ group_size = 16 @@ -222,6 +226,7 @@ def __init__( pdl: bool = False, cta_scoring: bool = True, splits: int = 1, + dynamic_ep: tuple[int, int] = (0, 0), ): warp = cute.arch.WARP_SIZE num_local = num_experts if num_local is None else num_local @@ -250,6 +255,7 @@ def __init__( self.num_local = num_local self.pdl = pdl self.splits = splits + self.dynamic_ep_rank, self.dynamic_ep_size = dynamic_ep # The experts a thread scores for one token, and a lane holds when picking. self.experts_per_thread = (num_experts + self.num_threads - 1) // self.num_threads self.experts_per_lane = num_experts // warp @@ -383,6 +389,10 @@ def kernel( (len(self.routing_tiles), self.num_threads // cute.arch.WARP_SIZE) ), ) + # Dynamic EP: the used experts below each expert, then whether this rank runs it. + assigned_s = experts_s + if cutlass.const_expr(self.dynamic_ep_size > 1): + assigned_s = smem.allocate_tensor(Int32, cute.make_layout(self.num_local)) nonzero_s = smem.allocate_tensor( Int32, cute.make_layout(self.num_threads // cute.arch.WARP_SIZE) ) @@ -400,6 +410,8 @@ def kernel( scores_s, experts_s, warp_ctas_s, + assigned_s, + nonzero_s, tidx, ) elif row < self.num_rows(logits): @@ -802,6 +814,23 @@ def counts_row( counted = Int32(0) return counted + @cute.jit + def home_first_owner( + self, below_s: cute.Tensor, total: Int32, below: Int32, expert: Int32 + ) -> Int32: + """The EP rank of the two that runs used ``expert``: each keeps up to ceil(used / 2) of its + half's used experts, lowest first, and gives the rest to the other.""" + half = self.num_experts // 2 + home = Int32(0) + kept = below + if expert >= Int32(half): + home = Int32(1) + kept = below - below_s[half] + owner = home + if kept >= (total + Int32(1)) // Int32(2): + owner = Int32(1) - home + return owner + @cute.jit def route_with_tables( self, @@ -815,13 +844,16 @@ def route_with_tables( scores_s: cute.Tensor, experts: cute.Tensor, warp_ctas: cute.Tensor, + assigned: cute.Tensor, + warp_used: cute.Tensor, tidx: Int32, ): """Route every token (thread ``e`` scores expert ``e`` of every token, then warp ``t`` picks token ``t``), then write ``tables[t]`` for tile ``t``: expanded-to-permuted, permuted-to-token, CTA experts, CTA limits, (CTAs, padded rows). Experts are numbered from ``local_start``; a pick of another rank's expert maps to -1. ``experts`` holds the - local expert histogram, then one tile's first CTAs.""" + local expert histogram, then one tile's first CTAs; with ``dynamic_ep`` ``assigned`` holds + the used experts below each expert, then whether this rank runs it.""" warp_size = cute.arch.WARP_SIZE num_warps = self.num_threads // warp_size warp = tidx // warp_size @@ -869,6 +901,42 @@ def route_with_tables( count = Int32(0) if tidx < self.num_local: count = experts[tidx] + if cutlass.const_expr(self.dynamic_ep_size > 1): + used = Int32(0) + if count > Int32(0): + used = Int32(1) + below = used + for offset in (1, 2, 4, 8, 16): + lower = cute.arch.shuffle_sync_up(below, offset) + if lane >= offset: + below = below + lower + if lane == warp_size - 1: + warp_used[warp] = below + cute.arch.barrier() + below = below - used + total = Int32(0) + for w in cutlass.range_constexpr(num_warps): + if w < warp: + below = below + warp_used[w] + total = total + warp_used[w] + if tidx < self.num_local: + assigned[tidx] = below + cute.arch.barrier() + mine = Int32(0) + if used != Int32(0): + if self.home_first_owner(assigned, total, below, tidx) == Int32( + self.dynamic_ep_rank + ): + mine = Int32(1) + cute.arch.barrier() + if mine == Int32(0): + count = Int32(0) + if tidx < self.num_local: + assigned[tidx] = mine + cute.arch.barrier() + if pick_rank >= Int32(0): + if assigned[pick_expert] == Int32(0): + pick_rank = Int32(-1) # All tiles at once: each expert's CTA count, scanned within the warp, then over warps. owned = [(count + tile - 1) // tile for tile in self.routing_tiles] scanned = list(owned) @@ -1009,6 +1077,7 @@ def _compile( pdl: bool = False, cta_scoring: bool = True, splits: int = 1, + dynamic_ep: tuple[int, int] = (0, 0), ): tokens = cute.sym_int() # A launch bucket has its own row count, at least the tokens'. @@ -1074,6 +1143,7 @@ def scalar(enabled): pdl=pdl, cta_scoring=cta_scoring, splits=splits, + dynamic_ep=dynamic_ep, ), logits, cute.runtime.make_fake_compact_tensor(Float32, (num_experts,), stride_order=(0,)), @@ -1123,6 +1193,29 @@ def _max_ctas(num_tokens: int, top_k: int, num_experts: int, tile: int) -> int: return filled + (expanded - filled) // tile +def routing_table_max_ctas(num_tokens: int, top_k: int, num_experts: int, dynamic_ep) -> int: + """The most CTAs a rank's tables of the two-rank dynamic split assign: half of the used experts, + rounded up, as a table's rows fit one CTA per expert; 0 without it, the kernels' worst case.""" + if dynamic_ep is None: + return 0 + return (min(num_tokens * top_k, num_experts) + 1) // 2 + + +def _check_dynamic_ep( + dynamic_ep: Optional[tuple[int, int]], + local_experts: Optional[tuple[int, int]], + with_routing_tables: bool, +) -> None: + if dynamic_ep is not None and ( + tuple(dynamic_ep) not in ((0, 2), (1, 2)) + or local_experts is not None + or not with_routing_tables + ): + raise ValueError( + f"dynamic expert parallelism {dynamic_ep} needs 2 ranks and tables over every expert" + ) + + def _local_range(local_experts: Optional[tuple[int, int]], num_experts: int) -> tuple[int, int]: first, count = (0, num_experts) if local_experts is None else local_experts if not (0 <= first and 0 < count and first + count <= num_experts): @@ -1166,11 +1259,15 @@ def dsv4_route_nvfp4_quant( replicas: bool = False, local_experts: Optional[tuple[int, int]] = None, routing_tiles: tuple[int, ...] = ROUTING_TABLE_TILES, + dynamic_ep: Optional[tuple[int, int]] = None, + one_cluster: bool = False, ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, Optional[torch.Tensor]]: """DeepSeek-V4 routing and NVFP4 input quantization in one launch, bitwise ``routing.apply`` then ``fp4_quantize``; ``with_routing_tables`` also returns ``run_moe``'s routing tables for ``routing_tiles``, over the experts ``local_experts`` = (first, count) of an expert-parallel - rank if given. + rank if given, or with ``dynamic_ep`` = (rank, 2) over this rank's share of the experts in use + (every rank holding every expert). ``one_cluster``: a table launch of a shape + ``dsv4_route_one.applies`` takes routes in one cluster. ``staged`` = a launch bucket's (ids, weights, NVFP4 rows, scale rows) with at least as many rows as tokens: the launch also writes the ids there and writes the rest there instead, returning @@ -1239,12 +1336,38 @@ def dsv4_route_nvfp4_quant( raise ValueError(f"MXFP8 buffers are too small for {num_tokens} rows of {hidden_size}") x_fp8 = x_fp8.view(torch.int32) local_start, num_local = _local_range(local_experts, num_experts) + _check_dynamic_ep(dynamic_ep, local_experts, with_routing_tables) tables = ( _routing_tables(num_tokens, num_local, top_k, device, num_experts, routing_tiles) if with_routing_tables else None ) routing_tiles = routing_tiles if with_routing_tables else () + if ( + one_cluster + and tables is not None + and splits == 1 + and mxfp8 is None + and route_one.applies(num_tokens, num_experts, top_k, routing_tiles) + and route_one.route_one( + logits, + selection_bias, + routed_scaling_factor, + ids, + weights, + tables, + routing_tiles, + local_start, + num_local, + pdl=False, + dynamic_ep=dynamic_ep, + x=x, + global_scale=global_scale.view(1), + x_fp4=x_fp4, + x_sf=x_sf, + ) + ): + return ids, weights, x_fp4.view(torch.uint8), x_sf, tables if num_tokens > 0: _compile( num_experts, @@ -1262,6 +1385,7 @@ def dsv4_route_nvfp4_quant( num_local=num_local, cta_scoring=_cta_scoring(num_tokens, num_experts), splits=splits, + dynamic_ep=tuple(dynamic_ep) if dynamic_ep else (0, 0), )( logits, selection_bias, @@ -1299,11 +1423,13 @@ def dsv4_route( with_routing_tables: bool = False, local_experts: Optional[tuple[int, int]] = None, routing_tiles: tuple[int, ...] = ROUTING_TABLE_TILES, + dynamic_ep: Optional[tuple[int, int]] = None, + one_cluster: bool = False, ) -> tuple[torch.Tensor, torch.Tensor, Optional[torch.Tensor]]: """DeepSeek-V4 routing in one launch, bitwise ``routing.apply`` with the weights in ``weights_dtype``, for an input already quantized; ``with_routing_tables`` also returns - ``run_moe``'s routing tables for ``routing_tiles`` (as ``dsv4_route_nvfp4_quant``). It launches - as a programmatic dependent of the router GEMM.""" + ``run_moe``'s routing tables for ``routing_tiles`` (as ``dsv4_route_nvfp4_quant``, also for + ``one_cluster``). It launches as a programmatic dependent of the router GEMM.""" if not isinstance(router_logits, torch.Tensor): raise TypeError("dsv4_route takes [tokens, experts] router logits") num_tokens, num_experts = router_logits.shape @@ -1311,12 +1437,32 @@ def dsv4_route( ids = torch.empty((num_tokens, top_k), dtype=torch.int32, device=device) weights = torch.empty((num_tokens, top_k), dtype=weights_dtype, device=device) local_start, num_local = _local_range(local_experts, num_experts) + _check_dynamic_ep(dynamic_ep, local_experts, with_routing_tables) tables = ( _routing_tables(num_tokens, num_local, top_k, device, num_experts, routing_tiles) if with_routing_tables else None ) routing_tiles = routing_tiles if with_routing_tables else () + if ( + one_cluster + and tables is not None + and route_one.applies(num_tokens, num_experts, top_k, routing_tiles) + and route_one.route_one( + router_logits, + selection_bias, + routed_scaling_factor, + ids, + weights, + tables, + routing_tiles, + local_start, + num_local, + pdl=TRTLLM_ENABLE_PDL, + dynamic_ep=dynamic_ep, + ) + ): + return ids, weights, tables if num_tokens > 0: _compile( num_experts, @@ -1329,6 +1475,7 @@ def dsv4_route( num_local=num_local, pdl=TRTLLM_ENABLE_PDL, cta_scoring=_cta_scoring(num_tokens, num_experts), + dynamic_ep=tuple(dynamic_ep) if dynamic_ep else (0, 0), )( router_logits, selection_bias, diff --git a/tensorrt_llm/_torch/pyexecutor/model_loader.py b/tensorrt_llm/_torch/pyexecutor/model_loader.py index 8b512a4446ea..b804c47102c9 100644 --- a/tensorrt_llm/_torch/pyexecutor/model_loader.py +++ b/tensorrt_llm/_torch/pyexecutor/model_loader.py @@ -1811,6 +1811,7 @@ def _load_and_validate_config( replicate_embedding=self.llm_args.replicate_embedding, cuda_graph_batch_sizes=captured_cuda_graph_batch_sizes( self.llm_args, self.max_num_tokens, self.spec_config), + max_batch_size=self.llm_args.max_batch_size, mm_encoder_only=self.llm_args.mm_encoder_only, disable_mm_encoder=self.llm_args.disable_mm_encoder, attn_backend=self.llm_args.attn_backend, diff --git a/tests/integration/defs/.test_durations b/tests/integration/defs/.test_durations index 1159f758495c..d6cdae06c929 100644 --- a/tests/integration/defs/.test_durations +++ b/tests/integration/defs/.test_durations @@ -2621,6 +2621,8 @@ "test_unittests.py::test_unittests_v2[unittest/_torch/moe/test_moe_decode_front.py]": 100.59344092570038, "unittest/_torch/moe/test_moe_load_balancer.py": 21.09670667356441, "test_unittests.py::test_unittests_v2[unittest/_torch/moe/test_moe_load_balancer.py]": 21.09670667356441, + "unittest/_torch/moe/test_moe_ep_dynamic.py": 93.97603980099503, + "test_unittests.py::test_unittests_v2[unittest/_torch/moe/test_moe_ep_dynamic.py]": 93.97603980099503, "unittest/_torch/moe/test_moe_lowm_fc2.py": 28.246704595185996, "test_unittests.py::test_unittests_v2[unittest/_torch/moe/test_moe_lowm_fc2.py]": 28.246704595185996, "unittest/_torch/moe/test_moe_module.py::test_a_tactic_builds_the_implementation_it_names": 26.606316666666665, diff --git a/tests/integration/test_lists/test-db/l0_gb200_multi_gpus.yml b/tests/integration/test_lists/test-db/l0_gb200_multi_gpus.yml index 9a387918635b..b525db7462b4 100644 --- a/tests/integration/test_lists/test-db/l0_gb200_multi_gpus.yml +++ b/tests/integration/test_lists/test-db/l0_gb200_multi_gpus.yml @@ -37,6 +37,8 @@ l0_gb200_multi_gpus: # Synthetic weights cover Engram head/row shards and TP/EP shared-expert collectives. - unittest/_torch/multi_gpu/test_engram_sharding.py::test_engram_shard_roundtrip -k "world:4" - unittest/_torch/moe/test_deepseek_v41_shared_moe.py + # Dynamic expert parallelism at attention TP against the static expert split. + - unittest/_torch/moe/test_moe_ep_dynamic.py # Two-rank cases include uneven/empty attention-DP batches and bounded CSA2 replay. - unittest/_torch/multi_gpu/test_deepseek_v41_attention_dp.py::test_attention_dp_engram[world2-row-sharded] - unittest/_torch/multi_gpu/test_deepseek_v41_attention_dp.py::test_attention_dp_decoder_bounded_replay[world2] diff --git a/tests/integration/test_lists/test-db/l0_gb300_multi_gpus.yml b/tests/integration/test_lists/test-db/l0_gb300_multi_gpus.yml index d9f7b82e7396..75ae00a3ee74 100644 --- a/tests/integration/test_lists/test-db/l0_gb300_multi_gpus.yml +++ b/tests/integration/test_lists/test-db/l0_gb300_multi_gpus.yml @@ -162,6 +162,8 @@ l0_gb300_multi_gpus: - accuracy/test_llm_api_pytorch.py::TestDeepSeekV4Flash::test_mixed_breakable_cuda_graph[dp4] TIMEOUT (120) - accuracy/test_llm_api_pytorch.py::TestDeepSeekV4Pro::test_gsm8k_full_accuracy[dp4] TIMEOUT (240) - accuracy/test_llm_api_pytorch.py::TestDeepSeekV4ProDSpark::test_gsm8k_megamoe_deepgemm[dp4] TIMEOUT (240) + # DeepSeek-V4.1 on SM103: dynamic expert parallelism at attention TP against the static expert split. + - unittest/_torch/moe/test_moe_ep_dynamic.py # DeepSeek-V4.1 on SM103: MegaMoE serving path, online expert placement, attention-DP # graph passes and breakable prefill graphs against eager prefill. - unittest/_torch/moe/test_megamoe_e2e.py diff --git a/tests/unittest/_torch/modeling/test_modeling_deepseekv4.py b/tests/unittest/_torch/modeling/test_modeling_deepseekv4.py index ec08d5a9b0ff..af9dd2aa0c43 100644 --- a/tests/unittest/_torch/modeling/test_modeling_deepseekv4.py +++ b/tests/unittest/_torch/modeling/test_modeling_deepseekv4.py @@ -1144,6 +1144,7 @@ def test_deepseek_v4_moe_allreduce_is_mnnvl_eligible(monkeypatch: pytest.MonkeyP moe_backend="TRTLLM", quant_config=QuantConfig(), use_cute_dsl_blockscaling_mm=False, + extra_attrs={}, ) moe = v4.DeepseekV4MoE( num_experts=4, diff --git a/tests/unittest/_torch/moe/test_dsv4_route_quant.py b/tests/unittest/_torch/moe/test_dsv4_route_quant.py index 9b1887038919..0df739bfdecc 100644 --- a/tests/unittest/_torch/moe/test_dsv4_route_quant.py +++ b/tests/unittest/_torch/moe/test_dsv4_route_quant.py @@ -208,3 +208,95 @@ def run(tactic, routing_tables): e2p = [out[2].flatten()[: num_tokens * TOP_K].long() for out in (expected, got)] rows = [out[0][e] for out, e in zip((expected, got), e2p)] torch.testing.assert_close(rows[1], rows[0], atol=0, rtol=0) + + +def _assert_same_tables(got, want, ids, top_k, local_start, routing_tiles): + """Both are TRTLLM-Gen routing tables of ``ids``, up to the row order inside an expert's block.""" + flat = ids.flatten().long() + n = flat.numel() + for t, tile in enumerate(routing_tiles): + num_ctas = int(want[t, 4, 0]) + assert got[t, 4, :2].tolist() == want[t, 4, :2].tolist() + for row in (2, 3): + assert torch.equal(got[t, row, :num_ctas], want[t, row, :num_ctas]) + assert torch.equal(got[t, 0, :n] >= 0, want[t, 0, :n] >= 0) + here = want[t, 0, :n] >= 0 + tokens = torch.arange(n, device=ids.device)[here] // top_k + for tables in (got, want): + e2p = tables[t, 0, :n][here].long() + assert e2p.unique().numel() == e2p.numel() + assert torch.equal(tables[t, 2, e2p // tile].long(), flat[here] - local_start) + assert torch.equal(tables[t, 1, e2p].long(), tokens) + + +@pytest.mark.parametrize("scope,num_tokens", [("ep_rank1", 6)]) +@torch.inference_mode() +def test_one_cluster_route_matches_the_cute_kernel(scope, num_tokens, monkeypatch): + """The one-cluster kernel gives the CuTe DSL kernel's routing, NVFP4 input and routing tables (rows of an + expert in any order), eager and replayed in a CUDA graph.""" + from tensorrt_llm._torch.moe.kernels.blackwell import dsv4_route_one + from tensorrt_llm._torch.moe.kernels.blackwell.dsv4_route_quant import ( + ROUTING_TABLE_TILES, + dsv4_route, + dsv4_route_nvfp4_quant, + ) + + if torch.cuda.get_device_capability() not in ((10, 0), (10, 3)): + pytest.skip("the one-cluster route kernel targets SM100/SM103") + kwargs, local_start = {}, 0 + if scope.startswith("ep_rank"): + local_start = int(scope[-1]) * (NUM_EXPERTS // 2) + kwargs = {"local_experts": (local_start, NUM_EXPERTS // 2)} + logits, bias, x, global_scale = _clustered_inputs(num_tokens, seed=10 + num_tokens) + # Ties, NaN, infinite and very negative logits. + logits[0, 40:60] = 2.0 + if num_tokens > 2: + logits[1, 7] = float("nan") + logits[2, 300:305] = float("inf") + logits[num_tokens - 1, ::3] = -100.0 + launched = [] + launch = dsv4_route_one.route_one + monkeypatch.setattr( + dsv4_route_one, "route_one", lambda *a, **k: launched.append(1) or launch(*a, **k) + ) + + def run(one_cluster, route_only, weights_dtype): + if route_only: + return dsv4_route( + logits, + bias, + TOP_K, + SCALING, + weights_dtype, + HIDDEN, + with_routing_tables=True, + one_cluster=one_cluster, + **kwargs, + ) + return dsv4_route_nvfp4_quant( + logits, bias, x, global_scale, TOP_K, SCALING, weights_dtype, with_routing_tables=True, + one_cluster=one_cluster, **kwargs, + ) # fmt: skip + + for route_only, weights_dtype in ((True, torch.float32), (False, torch.bfloat16)): + *want, want_tables = run(False, route_only, weights_dtype) + assert not launched + *got, got_tables = run(True, route_only, weights_dtype) + assert len(launched) == 1 + launched.clear() + _assert_equal(got, want) + _assert_same_tables( + got_tables, want_tables, got[0], TOP_K, local_start, ROUTING_TABLE_TILES + ) + + # Captured once, replayed on new logits written into the captured input. + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph): + *captured, captured_tables = run(True, True, torch.float32) + logits.copy_(torch.randn_like(logits) * 4) + graph.replay() + *want, want_tables = run(False, True, torch.float32) + _assert_equal(captured, want) + _assert_same_tables( + captured_tables, want_tables, captured[0], TOP_K, local_start, ROUTING_TABLE_TILES + ) diff --git a/tests/unittest/_torch/moe/test_megamoe_e2e.py b/tests/unittest/_torch/moe/test_megamoe_e2e.py index fbea45fcf39c..1859c5cc3c15 100644 --- a/tests/unittest/_torch/moe/test_megamoe_e2e.py +++ b/tests/unittest/_torch/moe/test_megamoe_e2e.py @@ -1,9 +1,9 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -"""DeepSeek-V4.1-Flash MegaMoE end to end on four GPUs (attention DP, EP4) at the mid (150 rows per rank) and hi -(1,280) decode shapes on the delivered path: the FP8 shared expert fused into the kernel, router logits as K-chunk -partials, routing and quantization straight into the launch bucket and the default tactics; and the DSpark draft -bank re-encoded from MXFP4 to NVFP4. +"""DeepSeek-V4.1-Flash MegaMoE end to end on four GPUs (attention DP, EP4) at the s8 (48 rows per rank), mid +(150) and hi (1,280) decode shapes on the delivered path: the FP8 shared expert fused into the kernel, router logits +as K-chunk partials, routing and quantization straight into the launch bucket and the default tactics; and the +DSpark draft bank re-encoded from MXFP4 to NVFP4. Against the reference: the routed experts' per-expert NVFP4 math, the fused shared expert within 2% of the separate one's error against FP32, the partials' ordered sum against the router GEMM, and the draft layer against FP32 math on @@ -51,8 +51,12 @@ _CLAMP = 10.0 _SCALING = 1.5 _MAX_NUM_TOKENS = 1280 -# Per-rank rows: the full mid and hi shapes, then each with an idle rank and a one-row (or short) rank. -_SHAPES = {"mid": ([150] * 4, [150, 0, 75, 1]), "hi": ([1280] * 4, [1280, 640, 0, 33])} +# Per-rank rows: the full s8, mid and hi shapes, then mid and hi with an idle rank and a one-row (or short) rank. +_SHAPES = { + "s8": ([48] * 4,), + "mid": ([150] * 4, [150, 0, 75, 1]), + "hi": ([1280] * 4, [1280, 640, 0, 33]), +} # Gate-bias variants of the full shapes: two hot experts, no rows for rank 2's experts, and only the first 24 of every # rank's 96 experts live, so the phase-interleaved streams end in front of empty experts. _VARIANTS = ("base", "hot", "no_rank2", "trailing_empty") @@ -363,6 +367,8 @@ def counted_init(self, *args, **kwargs): moe_max_num_tokens=_MAX_NUM_TOKENS, megamoe_fuse_shared_expert=True, ) + # DeepSeek-V4.1's opt-in: router partials from 12 rows per rank (the s8 shape). + model_config.extra_attrs["moe_router_partials_small_m"] = True with torch.device("cuda", rank), torch.inference_mode(): torch.manual_seed(1701) @@ -430,11 +436,12 @@ def build(layer_idx: int, fuse: bool) -> DeepseekV4MoE: torch.manual_seed(1702 + rank) calls = [] for shape, patterns in _SHAPES.items(): - if one_round and shape != "mid": - continue for pattern, counts in enumerate(patterns): for variant in _VARIANTS if pattern == 0 else ("base",): + # Both passes draw every input, so the one-round pass gets the same mid inputs. x = torch.randn((counts[rank], _HIDDEN_SIZE), dtype=torch.bfloat16) + if one_round and shape != "mid": + continue label = f"{shape} {counts} {variant}" calls.append((label, layers[len(calls) % 2], biases[variant], x, counts)) diff --git a/tests/unittest/_torch/moe/test_moe_ep_dynamic.py b/tests/unittest/_torch/moe/test_moe_ep_dynamic.py new file mode 100644 index 000000000000..1c291ff991eb --- /dev/null +++ b/tests/unittest/_torch/moe/test_moe_ep_dynamic.py @@ -0,0 +1,233 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Dynamic expert parallelism on the DS-V4.1 MoE at attention TP against the static expert split, with +either route kernel, eager and replayed in a CUDA graph.""" + +import itertools +import pickle +import sys +from contextlib import ExitStack + +import cloudpickle +import pytest +import torch +from _torch.moe import test_deepseek_v41_parallel_moe as parallel_moe +from _torch.moe.quantize_utils import NVFP4QuantizeUtil +from _torch.moe.test_deepseek_v41_parallel_moe import ( + _CLAMP, + _HIDDEN_SIZE, + _INTERMEDIATE_SIZE, + _NUM_EXPERTS, + _ROUTED_SCALE, + _TOP_K, + _local_mpi_topology, +) +from _torch.moe.test_deepseek_v41_shared_moe import _nvfp4_input +from mpi4py import MPI +from mpi4py.futures import MPIPoolExecutor +from transformers import PretrainedConfig + +from tensorrt_llm._torch.autotuner import autotune +from tensorrt_llm._torch.model_config import ModelConfig +from tensorrt_llm._torch.models.modeling_deepseekv4 import DeepseekV4MoE +from tensorrt_llm._torch.models.modeling_deepseekv41 import _MOE_CUTE_FC2_ROWS +from tensorrt_llm._torch.moe.fused_moe import configurable_moe +from tensorrt_llm._torch.moe.fused_moe.impl_contract import MOE_DECODE_OPTIONS, MoEDecodeOptions +from tensorrt_llm._torch.moe.kernels.blackwell import dsv4_route_one +from tensorrt_llm._torch.nccl_window_tensor_scope import nccl_window_tensor_scope +from tensorrt_llm._torch.utils import AuxStreamType +from tensorrt_llm._utils import is_blackwell_datacenter, mpi_rank, mpi_world_size +from tensorrt_llm.mapping import Mapping +from tensorrt_llm.models.modeling_utils import QuantAlgo, QuantConfig + +# Workers unpickle this module's functions by value: they must not reference the parallel_moe module. +parallel_moe_executor = parallel_moe.parallel_moe_executor +cloudpickle.register_pickle_by_value(sys.modules[__name__]) +MPI.pickle.__init__(cloudpickle.dumps, cloudpickle.loads, pickle.HIGHEST_PROTOCOL) + +_INPUT_RANGE = 4.0 + + +def _rows(num_rows: int, seed: int) -> torch.Tensor: + generator = torch.Generator(device="cuda").manual_seed(seed) + x = torch.randn(num_rows, _HIDDEN_SIZE, device="cuda", generator=generator) + return x.clamp(-_INPUT_RANGE, _INPUT_RANGE).to(torch.bfloat16) + + +def _routed(moe: DeepseekV4MoE, x: torch.Tensor, fp4_input: bool, do_finalize: bool): + fp4 = _nvfp4_input(x, moe.experts.backend.fc31_input_scale) if fp4_input else None + return moe.compute_routed_output(x, fp4, None, None, do_finalize=do_finalize) + + +def _partial(output) -> torch.Tensor: + """An un-finalized run's rows summed per token on this rank (permutation -1: another rank's).""" + rows, weights = output[0], output[1] + permutation = output[2].flatten()[: weights.numel()].view(weights.shape) + gathered = rows[permutation.clamp(min=0).long()].float() + gathered = torch.where((permutation >= 0)[..., None], gathered, 0.0) + return (gathered * weights.float()[..., None]).sum(1).to(rows.dtype) + + +def _moves(moe: DeepseekV4MoE, x: torch.Tensor) -> bool: + """Whether the home-first split moves an expert: one rank's half holds over ceil(used / 2).""" + used = moe.gate.routing_method.apply(moe.gate(x))[0].unique() + lower = int((used < _NUM_EXPERTS // 2).sum()) + return max(lower, used.numel() - lower) > (used.numel() + 1) // 2 + + +def _close(label: str, got: torch.Tensor, want: torch.Tensor) -> None: + """Moved experts round the per-rank BF16 partials in another grouping.""" + scale = want.float().abs().max().item() + max_abs = (got.float() - want.float()).abs().max().item() + assert torch.isfinite(got).all() and 0 < scale and max_abs <= 2**-6 * scale, (label, max_abs) + + +def _run_dynamic_ep() -> None: + local_rank, local_size = _local_mpi_topology() + torch.cuda.set_device(local_rank) + world_size = mpi_world_size() + mapping = Mapping( + world_size=world_size, + rank=mpi_rank(), + gpus_per_node=local_size, + tp_size=world_size, + moe_ep_size=2, + moe_tp_size=world_size // 2, + ) + routed_quant_config = QuantConfig(quant_algo=QuantAlgo.NVFP4) + model_config = ModelConfig( + pretrained_config=PretrainedConfig( + hidden_size=_HIDDEN_SIZE, + intermediate_size=_INTERMEDIATE_SIZE, + num_experts=_NUM_EXPERTS, + n_group=1, + topk_group=1, + routed_scaling_factor=_ROUTED_SCALE, + n_hash_layers=0, + vocab_size=129280, + swiglu_limit=_CLAMP, + torch_dtype=torch.bfloat16, + ), + mapping=mapping, + quant_config=QuantConfig(quant_algo=QuantAlgo.FP8_BLOCK_SCALES, group_size=128), + moe_backend="TRTLLM", + max_num_tokens=256, + max_batch_size=1, + ) + # DeepSeek-V4.1's opt-ins: small un-finalized NVFP4 FC2s as the CuTe DSL kernel, the one-cluster + # route kernel, dynamic EP. + model_config.extra_attrs[MOE_DECODE_OPTIONS] = MoEDecodeOptions( + cute_fc2_rows=_MOE_CUTE_FC2_ROWS, one_cluster_route=True + ) + model_config.extra_attrs["moe_dynamic_ep"] = True + + with ( + torch.device(f"cuda:{local_rank}"), + torch.inference_mode(), + pytest.MonkeyPatch.context() as env, + ExitStack() as stack, + ): + torch.manual_seed(1701) + gate_weight = torch.randn(_NUM_EXPERTS, _HIDDEN_SIZE) / _HIDDEN_SIZE**0.5 + gate_bias = torch.randn(_NUM_EXPERTS, dtype=torch.float32) * 0.05 + routed_weights = NVFP4QuantizeUtil( + num_experts=_NUM_EXPERTS, + dtype=torch.bfloat16, + intermediate_size=_INTERMEDIATE_SIZE, + hidden_size=_HIDDEN_SIZE, + quant_config=routed_quant_config, + swiglu_alpha=1.0, + swiglu_beta=0.0, + swiglu_limit=_CLAMP, + ).create_weights(x_sf_global=torch.tensor(448.0 * 6.0 / _INPUT_RANGE)) + modules = [] + # The production gate wants MoE TP 4 or more: this world (MoE TP 2) loads the static split, + # then the dynamic one with the bound lowered. + for min_moe_tp in (4, 2): + env.setattr(configurable_moe, "_DYNAMIC_EP_MIN_MOE_TP", min_moe_tp) + moe = DeepseekV4MoE( + num_experts=_NUM_EXPERTS, + top_k=_TOP_K, + hidden_size=_HIDDEN_SIZE, + intermediate_size=_INTERMEDIATE_SIZE, + shared_expert_intermediate_size=_INTERMEDIATE_SIZE, + aux_stream_dict={AuxStreamType.MoeShared: torch.cuda.Stream()}, + dtype=torch.bfloat16, + model_config=model_config, + override_quant_config=routed_quant_config, + layer_idx=0, + ) + stack.enter_context(moe.experts) + moe.gate.weight.copy_(gate_weight) + moe.gate.e_score_correction_bias.copy_(gate_bias) + moe.experts.load_weights([dict(routed_weights)]) + moe.experts.post_load_weights() + modules.append(moe) + static, dynamic = modules + assert static.experts.dynamic_ep is None and dynamic.experts.dynamic_ep is not None + + def all_reduced(output) -> torch.Tensor: + return static.allreduce(output if torch.is_tensor(output) else _partial(output)) + + # At 1 and 6 rows (routing tables) an input whose split keeps every expert home and one that + # moves some; 16 rows run the static split in both modules. + cases = [ + next(x for x in (_rows(n, s) for s in range(1, 200)) if _moves(static, x) == moves) + for n, moves in itertools.product((1, 6), (False, True)) + ] + [_rows(16, seed=1)] + x = torch.empty(16, _HIDDEN_SIZE, dtype=torch.bfloat16) + with nccl_window_tensor_scope(x): + with autotune(): + for case in cases: + x[: len(case)].copy_(case) + for moe in modules: + _routed(moe, x[: len(case)], True, False) + # Captured once, replayed on new rows written into the captured input. + rows = x[:6] + rows.copy_(_rows(6, seed=1)) + _routed(dynamic, rows, True, False) + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph): + captured = _routed(dynamic, rows, True, False) + for seed in (2, 3, 4): + rows.copy_(_rows(6, seed)) + graph.replay() + want = all_reduced(_routed(static, rows, True, False)) + _close(f"graph replay, seed {seed}", all_reduced(captured), want) + + for one_cluster in (True, False): + if not one_cluster: + env.setattr(dsv4_route_one, "applies", lambda *args: False) + for case, fp4_input, do_finalize in itertools.product( + cases, (True, False), (True, False) + ): + rows = x[: len(case)] + rows.copy_(case) + label = f"{len(case)} rows, one-cluster {one_cluster}, fp4 {fp4_input}, " + label += f"finalized {do_finalize}" + want = all_reduced(_routed(static, rows, fp4_input, do_finalize)) + got = all_reduced(_routed(dynamic, rows, fp4_input, do_finalize)) + if len(case) > 8 or not _moves(static, rows): + assert torch.equal(got, want), label + else: + _close(label, got, want) + torch.cuda.synchronize() + + +@pytest.mark.skipif( + not torch.cuda.is_available() or not is_blackwell_datacenter(), + reason="dynamic expert parallelism runs on SM100/SM103", +) +@pytest.mark.threadleak(enabled=False) +@pytest.mark.parametrize( + "parallel_moe_executor", [pytest.param(4, id="tp4-moetp2-ep2")], indirect=True +) +def test_moe_ep_dynamic_matches_static_split(parallel_moe_executor: MPIPoolExecutor | None) -> None: + if parallel_moe_executor is None: + _run_dynamic_ep() + return + results = [ + parallel_moe_executor.submit(_run_dynamic_ep) + for _ in range(parallel_moe_executor.num_workers) + ] + assert all(result.result() is None for result in results) diff --git a/tests/unittest/_torch/moe/test_moe_lowm_fc2.py b/tests/unittest/_torch/moe/test_moe_lowm_fc2.py index 024894f528a9..d22a82fbf205 100644 --- a/tests/unittest/_torch/moe/test_moe_lowm_fc2.py +++ b/tests/unittest/_torch/moe/test_moe_lowm_fc2.py @@ -1,7 +1,8 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 """The decode-sized CuTe DSL FC2 (decode_moe CUTE_FC2) after the FC1-only trtllm-gen runner vs the runner's own FC2 -cubin: bit-identical un-finalized outputs (gemm2 rows, expert weights, expanded -> permuted index).""" +cubin: bit-identical un-finalized outputs (gemm2 rows, expert weights, expanded -> permuted index), on the runner's +routing or a route kernel's tables, eager and replayed in a CUDA graph.""" from types import SimpleNamespace from typing import NamedTuple @@ -226,10 +227,16 @@ def test_fc2_cubin_options_match_the_cubin_names(): "m,shape", [(m, _ALL_LOCAL) for m in (1, 6, 8, 16)] + [(m, _ALL_LOCAL._replace(num_experts=192, local=192)) for m in (1, 6, 8, 16)] + # 768 columns: the 512-column K tiles of some FC2 cubins end in a zero-filled tail the kernel re-applies. + + [(6, _ALL_LOCAL._replace(inter=768))] + [(m, s) for s in (_EP_LOCAL, _EP_REMOTE) for m in (56, 77, 112, 126)], ) def test_fc1_only_then_cute_fc2_is_bitwise(m, shape, kind): - from tensorrt_llm._torch.moe.fused_moe.trtllm_gen.decode_moe import fc1_only_args, run_cute_fc2 + from tensorrt_llm._torch.moe.fused_moe.trtllm_gen.decode_moe import ( + fc1_only_args, + fc2_cubin_tile_k, + run_cute_fc2, + ) runner = _runner() ids, w, ins = _inputs(m, shape, kind) @@ -239,7 +246,12 @@ def test_fc1_only_then_cute_fc2_is_bitwise(m, shape, kind): for tactic in _bitwise_tactics(runner, m, shape): common = _common(shape, ins, ids, w, list(tactic)) ref = runner.run_moe(*common) - got = run_cute_fc2(runner.run_moe_fc1(*fc1_only_args(common)), fc2_args, None) + got = run_cute_fc2( + runner.run_moe_fc1(*fc1_only_args(common)), + fc2_args, + None, + cubin_tile_k=fc2_cubin_tile_k(runner, 0, tactic), + ) torch.cuda.synchronize() _assert_same_expert_rows(got, ref) @@ -391,3 +403,137 @@ def test_both_fp4_ops_trace_through_the_one_fake(): assert out.shape == (4, 128) and out.dtype == torch.bfloat16, op assert G.fp4_block_scale_moe_runner._abstract_fn is G._fp4_block_scale_moe_fake assert G.fp4_block_scale_moe_decode_runner._abstract_fn is G._fp4_block_scale_moe_fake + + +# DeepSeek-V4.1-Flash with EP2: 384 experts (192 per EP rank), top-6, hidden 5120, routed scale 2.5; 576 (TP4) or +# 1152 (TP2) intermediate columns per rank. +_DSV41_EP_RANK = _Shape(384, 192, 5120, 576, 6, 6) +_DSV41_ROUTED_SCALE = 2.5 + + +def _dsv41_inputs(num_tokens, shape, local_offset, seed): + """FP4BlockScaleMoERunner inputs of a DeepSeek-V4.1 EP rank, routed as DeepSeek-V4.1 routes, and its tables.""" + from tensorrt_llm._torch.moe.kernels.blackwell.dsv4_route_quant import ( + ROUTING_TABLE_TILES, + can_build_routing_tables, + dsv4_route_nvfp4_quant, + ) + + generator = torch.Generator(device="cuda").manual_seed(seed) + e, inter, hidden = shape.local, shape.inter, shape.hidden + + def randn(*size, scale=1.0): + return torch.randn(*size, device="cuda", generator=generator) * scale + + def packed(*size): + return torch.randint(0, 256, size, dtype=torch.uint8, device="cuda", generator=generator) + + def scales(*size): # E4M3 in [0.25, 2] + codes = torch.randint( + 0x28, 0x41, size, dtype=torch.uint8, device="cuda", generator=generator + ) + return codes.view(torch.float8_e4m3fn) + + logits, bias, x = ( + randn(num_tokens, shape.num_experts, scale=4), + randn(shape.num_experts, scale=0.5), + randn(num_tokens, hidden), + ) + global_scale = torch.tensor([448.0 * 6.0 / 20.0], device="cuda") + with_tables = can_build_routing_tables(num_tokens, e, shape.num_experts) + ids, weights, x_fp4, x_sf, tables = dsv4_route_nvfp4_quant( + logits, + bias, + x.bfloat16(), + global_scale, + shape.top_k, + _DSV41_ROUTED_SCALE, + torch.bfloat16, + with_routing_tables=with_tables, + local_experts=(local_offset, e) if with_tables else None, + one_cluster=True, + ) + alpha2 = torch.rand(e, device="cuda", generator=generator) * 1e-3 + 1e-4 + one = torch.full((e,), 1e-4, device="cuda") + inputs = [ + None, None, x_fp4, x_sf.flatten().view(torch.float8_e4m3fn), + packed(e, 2 * inter, hidden // 2), scales(e, 2 * inter, hidden // 16), + None, None, None, torch.full((e,), 1e5, device="cuda"), + packed(e, hidden, inter // 2), scales(e, hidden, inter // 16), + None, one, one, alpha2, weights, ids, + ] # fmt: skip + table_kwargs = ( + dict(routing_tables=tables, routing_tiles=ROUTING_TABLE_TILES) if with_tables else {} + ) + return inputs, table_kwargs + + +def _assert_same_table_rows(got, ref, table_kwargs, num_tokens, top_k): + """Same expert row per (token, k), each through its run's permutation: row 0 of the routing table its tile ran on + (an empty [0, tile] placeholder names it), else the one it returns; routes to the other EP rank have none.""" + + def rows(outputs): + permutation = outputs[2] + if permutation.numel() == 0: + tiles = table_kwargs["routing_tiles"] + permutation = table_kwargs["routing_tables"][tiles.index(permutation.shape[1]), 0] + permutation = permutation.flatten()[: num_tokens * top_k] + valid = permutation >= 0 + return valid, outputs[0][permutation[valid].long()] + + valid, got_rows = rows(got) + want_valid, want_rows = rows(ref) + assert torch.equal(valid, want_valid) and int(valid.sum()) > 0 + assert torch.equal(got_rows.view(torch.int16), want_rows.view(torch.int16)) + + +@pytest.mark.parametrize("num_tokens,inter,local_offset", [(6, 576, 0)]) +@torch.inference_mode() +def test_cute_fc2_opt_in_matches_the_fc2_cubin(num_tokens, inter, local_offset, monkeypatch): + """A model that declares ``MoEDecodeOptions.cute_fc2_rows`` (DeepSeek-V4.1): FP4BlockScaleMoERunner calls on the + one-cluster route kernel's tables run the CuTe FC2 after the FC1-only entry, bit for bit the FC2 cubin, eager and + replayed in a CUDA graph on new activations and routes written into the captured inputs.""" + from tensorrt_llm._torch.custom_ops.trtllm_gen_custom_ops import FP4BlockScaleMoERunner + from tensorrt_llm._torch.models.modeling_deepseekv41 import _MOE_CUTE_FC2_ROWS + from tensorrt_llm._torch.moe.fused_moe.trtllm_gen import decode_moe + + shape = _DSV41_EP_RANK._replace(inter=inter) + inputs, table_kwargs = _dsv41_inputs( + num_tokens, shape, local_offset, seed=num_tokens + local_offset + ) + + def runner(cute_fc2_rows): + return FP4BlockScaleMoERunner( + shape.num_experts, shape.top_k, None, None, inter, local_offset, shape.local, + _DSV41_ROUTED_SCALE, 1, False, 0, cute_fc2_rows=cute_fc2_rows, + ) # fmt: skip + + cute, cubin = runner(_MOE_CUTE_FC2_ROWS), runner(0) + calls = [] + run_cute_fc2 = decode_moe.run_cute_fc2 + monkeypatch.setattr( + decode_moe, "run_cute_fc2", lambda *a, **kw: calls.append(1) or run_cute_fc2(*a, **kw) + ) + for tactic in _bitwise_tactics(cute.get_runner(), num_tokens, shape)[:3]: + tactic = list(tactic) + expected = cubin.forward(inputs, tactic=tactic, **table_kwargs) + assert not calls + got = cute.forward(inputs, tactic=tactic, **table_kwargs) + assert len(calls) == 1 + _assert_same_table_rows(got, expected, table_kwargs, num_tokens, shape.top_k) + + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph): + captured = cute.forward(inputs, tactic=tactic, **table_kwargs) + new_inputs, new_tables = _dsv41_inputs( + num_tokens, shape, local_offset, seed=100 + num_tokens + ) + for dst, src in zip(inputs, new_inputs): + if dst is not None and dst.data_ptr() != src.data_ptr(): + dst.copy_(src) + if table_kwargs: + table_kwargs["routing_tables"].copy_(new_tables["routing_tables"]) + graph.replay() + expected = cubin.forward(inputs, tactic=tactic, **table_kwargs) + _assert_same_table_rows(captured, expected, table_kwargs, num_tokens, shape.top_k) + calls.clear()