|
| 1 | +/* |
| 2 | + * Copyright (c) 2022-2026, NVIDIA CORPORATION. All rights reserved. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | +#include "flashinfer/trtllm/fused_moe/RoutingCustomPolicy.cuh" |
| 17 | +#include "flashinfer/trtllm/fused_moe/RoutingKernel.h" |
| 18 | + |
| 19 | +namespace moe::dev::routing { |
| 20 | +namespace routingCustom { |
| 21 | +// Forward declarations of launch functions |
| 22 | +void launchBlockKernel(Data const& data, uint32_t numThreadsHist, void* stream); |
| 23 | +void launchClusterKernel(Data const& data, void* stream); |
| 24 | +void launchCoopKernel(Data const& data, int numBlocksCoop, uint32_t numThreadsHist, void* stream); |
| 25 | +void launchInitExpertCounts(Data const& data, uint32_t numThreadsHist, void* stream); |
| 26 | +void launchHistogramKernel(Data const& data, int numBlocksHistogram, uint32_t numThreadsHist, |
| 27 | + void* stream); |
| 28 | +void launchOffsetsKernel(Data const& data, int numBlocksOffsets, uint32_t numThreadsHist, |
| 29 | + void* stream); |
| 30 | +} // namespace routingCustom |
| 31 | + |
| 32 | +//////////////////////////////////////////////////////////////////////////////////////////////////// |
| 33 | + |
| 34 | +// Implementation of shared post-topK pipeline for all routing methods. |
| 35 | +// When topK is already computed (mPtrTopKIds or mPtrTopKPacked), we don't need |
| 36 | +// routing-method-specific logic, so all methods can use the same workflow. |
| 37 | +// This function handles all path selection: single-block, single-cluster, coop, multi-kernel. |
| 38 | +template <typename DataType> |
| 39 | +void runPostTopKPipeline(DataType const& data, uint32_t /*numThreadsHist*/, void* stream) { |
| 40 | + // Convert to routingCustom::Data for launching (kernels are shared) |
| 41 | + routingCustom::Data customData; |
| 42 | + // Copy base fields |
| 43 | + static_cast<DataBase&>(customData) = static_cast<DataBase const&>(data); |
| 44 | + // Set routingCustom-specific defaults (not needed for utility kernels) |
| 45 | + customData.mDtypeOutput = data.mDtypeOutput; |
| 46 | + // The post-TopK kernels don't read routing logits (mPtrInput), only mPtrTopKPacked. |
| 47 | + // Set mDtypeInput = mDtypeOutput so the dispatched template is <OutputT, OutputT>, |
| 48 | + // avoiding an unnecessary mixed-type instantiation. |
| 49 | + customData.mDtypeInput = data.mDtypeOutput; |
| 50 | + customData.mPreprocessType = RoutingPreprocessType::None; |
| 51 | + customData.mPostprocessType = RoutingPostprocessType::Softmax; |
| 52 | + |
| 53 | + // Recompute numThreadsHist using routingCustom's expert tiers, since we launch custom kernels. |
| 54 | + // Different routing methods (DeepSeek, Llama4) may have different expert tier thresholds |
| 55 | + // that don't match routingCustom's tiers (128, 512, 2048). |
| 56 | + uint32_t const numThreadsHist = |
| 57 | + std::min(1024u, static_cast<uint32_t>(routingCustom::getMaxNumExperts(data.mNumExperts))); |
| 58 | + |
| 59 | + // Determine which path to use based on token count |
| 60 | + bool const useSingleBlock = data.mNumTokens <= routingCustom::BlockKernelMaxNumTokens; |
| 61 | + bool const useSingleCluster = data.mNumTokens <= routingCustom::MaxNumTokensSingleClusterScores; |
| 62 | + |
| 63 | + // PDL overlap control: the LAST routing kernel must disable overlap so the consumer |
| 64 | + // GEMM (which may lack cudaGridDependencySynchronize) can't start early. |
| 65 | + // Use a separate copy for the last kernel to avoid mutating customData. |
| 66 | + routingCustom::Data lastKernelData = customData; |
| 67 | + lastKernelData.mPdlOverlapWithNext = false; |
| 68 | + |
| 69 | + if (useSingleBlock) { |
| 70 | + // Single-block path: fuses all steps (histogram, offsets, permutation) |
| 71 | + routingCustom::launchBlockKernel(lastKernelData, numThreadsHist, stream); |
| 72 | + } else if (useSingleCluster) { |
| 73 | + // Single-cluster path: uses distributed shared memory |
| 74 | + routingCustom::launchClusterKernel(lastKernelData, stream); |
| 75 | + } else { |
| 76 | + // Check if we can use the coop path (more efficient for medium token counts) |
| 77 | + // Coop kernel requires SM90+ (grid-sync) and MaxNumExperts <= 1024. |
| 78 | + static int const smMajor = tensorrt_llm::common::getSMVersion() / 10; |
| 79 | + bool const canUseCoop = |
| 80 | + (smMajor >= 9) && (data.mNumExperts <= 1024) && (data.mPtrPermutedIdxSize != nullptr); |
| 81 | + bool useCoop = false; |
| 82 | + int numBlocksCoop = 0; |
| 83 | + |
| 84 | + if (canUseCoop) { |
| 85 | + // Number of blocks we can use in the cooperative kernel |
| 86 | + static int const smCount = tensorrt_llm::common::getMultiProcessorCount(); |
| 87 | + // WAR: Reserve 8 SMs for overlapping kernels. |
| 88 | + numBlocksCoop = smCount - 8; |
| 89 | + // Maximum number of tokens supported by the kernel using a cooperative launch. |
| 90 | + // The number of blocks must be: |
| 91 | + // >= ⌈(numTokens * topK) / (MaxExpandedIdxPerThread * NumThreads)⌉ |
| 92 | + // MaxExpandedIdxPerThread = 64 (from coop kernel) |
| 93 | + int const maxTokensCoop = (numBlocksCoop * numThreadsHist * 64) / data.mTopK; |
| 94 | + useCoop = (data.mNumTokens <= maxTokensCoop); |
| 95 | + } |
| 96 | + |
| 97 | + if (useCoop) { |
| 98 | + // Coop path: cooperative launch fuses histogram + offsets (more efficient). |
| 99 | + // The coop kernel atomicAdds to mPtrExpertCounts, so we must zero it first. |
| 100 | + routingCustom::launchInitExpertCounts(customData, numThreadsHist, stream); |
| 101 | + routingCustom::launchCoopKernel(lastKernelData, numBlocksCoop, numThreadsHist, stream); |
| 102 | + } else { |
| 103 | + // Large-token path: multi-kernel pipeline |
| 104 | + FLASHINFER_CHECK(data.mPtrExpertCounts != nullptr, |
| 105 | + "When #tokens is large, `mPtrExpertCounts` is a required input."); |
| 106 | + |
| 107 | + // Step 1: Reset expert counts |
| 108 | + routingCustom::launchInitExpertCounts(customData, numThreadsHist, stream); |
| 109 | + |
| 110 | + // Step 2-3: Histogram + Offsets |
| 111 | + int32_t const expandedIdxSize = data.mNumTokens * data.mTopK; |
| 112 | + int32_t const histogramEltsPerBlock = 8 * numThreadsHist; |
| 113 | + int32_t const offsetEltsPerBlock = |
| 114 | + routing::NumEltsPerOffsetTilePerThread * numThreadsHist; |
| 115 | + int32_t const maxNumBlocks = 1024; |
| 116 | + |
| 117 | + int const numBlocksHistogram = std::min( |
| 118 | + (expandedIdxSize + histogramEltsPerBlock - 1) / histogramEltsPerBlock, maxNumBlocks); |
| 119 | + int const numBlocksOffsets = std::min( |
| 120 | + (expandedIdxSize + offsetEltsPerBlock - 1) / offsetEltsPerBlock, maxNumBlocks); |
| 121 | + |
| 122 | + routingCustom::launchHistogramKernel(customData, numBlocksHistogram, numThreadsHist, stream); |
| 123 | + routingCustom::launchOffsetsKernel(lastKernelData, numBlocksOffsets, numThreadsHist, stream); |
| 124 | + } |
| 125 | + } |
| 126 | +} |
| 127 | + |
| 128 | +// Explicit instantiations for the three routing method Data types |
| 129 | +template void runPostTopKPipeline<routingCustom::Data>(routingCustom::Data const&, uint32_t, |
| 130 | + void*); |
| 131 | +template void runPostTopKPipeline<routingDeepSeek::Data>(routingDeepSeek::Data const&, uint32_t, |
| 132 | + void*); |
| 133 | +template void runPostTopKPipeline<routingLlama4::Data>(routingLlama4::Data const&, uint32_t, |
| 134 | + void*); |
| 135 | + |
| 136 | +//////////////////////////////////////////////////////////////////////////////////////////////////// |
| 137 | + |
| 138 | +} // namespace moe::dev::routing |
0 commit comments