Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
77 changes: 45 additions & 32 deletions csrc/fused_moe/monomoe/monomoe_binding.cu
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
* Licensed under the Apache License, Version 2.0.
*/

#include <type_traits>

#include "monomoe_wrapper.cuh"

// Declaration of the launcher function template (defined and explicitly
Expand All @@ -29,58 +31,69 @@ void monomoe_topk_launcher(TensorView activations_in, TensorView router_logits,

namespace {

// Does the (E, N, K) weight-shape signature and the token cap match this Dims
// variant? The kernel is hard-specialized to a fixed shape, so the runtime
// tensors must match it exactly before we launch — otherwise the kernel would
// read/write out of bounds. Keyed on the up/down weight shapes (which pin
// E, N, K) plus the BS token cap from `activations_in`.
// Does the (E, N, K) weight-shape signature match this Dims variant? The
// kernel is hard-specialized per shape, so the runtime tensors must match
// exactly before launch (otherwise the kernel reads/writes out of bounds).
template <class Dims>
bool shape_matches(const TensorView& activations_in, const TensorView& expert_weights_up,
const TensorView& expert_weights_down) {
return activations_in.ndim() == 2 && activations_in.size(0) <= Dims::BS &&
activations_in.size(1) == Dims::K && //
return activations_in.ndim() == 2 && activations_in.size(1) == Dims::K &&
expert_weights_up.ndim() == 3 && expert_weights_up.size(0) == Dims::NUM_EXPERTS &&
expert_weights_up.size(1) == 2 * Dims::N && expert_weights_up.size(2) == Dims::K && //
expert_weights_up.size(1) == 2 * Dims::N && expert_weights_up.size(2) == Dims::K &&
expert_weights_down.ndim() == 3 && expert_weights_down.size(0) == Dims::NUM_EXPERTS &&
expert_weights_down.size(1) == Dims::K && expert_weights_down.size(2) == Dims::N;
}

} // namespace

// Single top-K MoE entry point: dispatch on the runtime tensor shape to the
// matching hard-specialized Dims variant. Today there is exactly one variant
// (BS8 / E256 / Qwen3.5-35B block-FP8 WGMMA+TMA); a new shape gets a new
// `if` branch plus its explicit instantiation in monomoe_wrapper.cuh.
// TEMP_FP8_OFFSET regression anchor (design doc §4): the down-activation TMA
// descriptor addresses `spec->temp_fp8` as `scratchpad_ptr + TEMP_FP8_OFFSET`,
// so that constant must equal `offsetof(MoEGemmSpec<Dims>, temp_fp8)`; new
// fields go at the tail of MoEGemmSpec<Dims>.
static_assert(
offsetof(::monomoe::MoEGemmSpec<::monomoe::Dims_BS8_E256_N512_K2048_BlockFP8_WGMMA_TMA>,
temp_fp8) ==
::monomoe::MoEGemmSpec<
::monomoe::Dims_BS8_E256_N512_K2048_BlockFP8_WGMMA_TMA>::TEMP_FP8_OFFSET,
"TEMP_FP8_OFFSET must match offsetof(MoEGemmSpec<Dims>, temp_fp8).");

// Top-K MoE entry point: validate the runtime tensor shape and token count,
// then launch the single hard-specialized Dims variant. BS8 serves M <= 8.
void monomoe_topk(TensorView activations_in, TensorView router_logits, TensorView expert_weights_up,
TensorView expert_scales_up, TensorView expert_weights_down,
TensorView expert_scales_down, TensorView activations_out, TensorView scratchpad,
int64_t top_k, int64_t scoring_func, bool renormalize) {
using Qwen35 = monomoe::Dims_BS8_E256_Qwen3_5_35B_BlockFP8_WGMMA_TMA;
if (shape_matches<Qwen35>(activations_in, expert_weights_up, expert_weights_down)) {
monomoe_topk_launcher<Qwen35>(activations_in, router_logits, expert_weights_up,
expert_scales_up, expert_weights_down, expert_scales_down,
activations_out, scratchpad, top_k, scoring_func, renormalize);
using Dims = ::monomoe::Dims_BS8_E256_N512_K2048_BlockFP8_WGMMA_TMA;
const int64_t m = activations_in.ndim() == 2 ? activations_in.size(0) : -1;

if (!shape_matches<Dims>(activations_in, expert_weights_up, expert_weights_down)) {
TVM_FFI_ICHECK(false) << "monomoe_topk: this module is built for E=" << Dims::NUM_EXPERTS
<< ", N=" << Dims::N << ", K=" << Dims::K << " but got activations_in=["
<< m << ", " << (activations_in.ndim() == 2 ? activations_in.size(1) : -1)
<< "], expert_weights_up.dim0="
<< (expert_weights_up.ndim() == 3 ? expert_weights_up.size(0) : -1)
<< ".";
return;
}
TVM_FFI_ICHECK(false) << "monomoe_topk: no kernel for this shape. Supported: E="
<< Qwen35::NUM_EXPERTS << ", N=" << Qwen35::N << ", K=" << Qwen35::K
<< ", BS<=" << Qwen35::BS << " (got activations_in=["
<< activations_in.size(0) << ", "
<< (activations_in.ndim() == 2 ? activations_in.size(1) : -1)
<< "], expert_weights_up.dim0="
<< (expert_weights_up.ndim() == 3 ? expert_weights_up.size(0) : -1) << ").";

if (m < 1 || m > static_cast<int64_t>(Dims::BS)) {
TVM_FFI_ICHECK(false) << "monomoe_topk: token count M=" << m
<< " out of range for E=" << Dims::NUM_EXPERTS << ", N=" << Dims::N
<< ", K=" << Dims::K << " (supported 1 <= M <= " << Dims::BS << ").";
return;
}

monomoe_topk_launcher<Dims>(activations_in, router_logits, expert_weights_up, expert_scales_up,
expert_weights_down, expert_scales_down, activations_out, scratchpad,
top_k, scoring_func, renormalize);
}

// Scratchpad size (bytes). Exported so Python sizes the global scratchpad from
// the authoritative `sizeof(MoEGemmSpec<Dims>)` rather than re-deriving the
// struct layout (which would silently desync if any field is added — see the
// TEMP_FP8_OFFSET regression anchor in monomoe_wrapper.cuh). The kernel's
// barrier counters live at the tail of this struct, so the buffer MUST be at
// least this large. With a single Dims variant this is its size; once more
// variants exist, size to the max so any shape fits the same buffer.
// Scratchpad size (bytes) for the single Dims variant, sourced from
// sizeof(MoEGemmSpec<Dims>) so the buffer can never desync from the kernel's
// struct layout.
int64_t monomoe_scratchpad_size() {
return static_cast<int64_t>(
sizeof(monomoe::MoEGemmSpec<monomoe::Dims_BS8_E256_Qwen3_5_35B_BlockFP8_WGMMA_TMA>));
sizeof(::monomoe::MoEGemmSpec<::monomoe::Dims_BS8_E256_N512_K2048_BlockFP8_WGMMA_TMA>));
}

TVM_FFI_DLL_EXPORT_TYPED_FUNC(monomoe_topk, monomoe_topk);
Expand Down
65 changes: 36 additions & 29 deletions csrc/fused_moe/monomoe/monomoe_wrapper.cuh
Original file line number Diff line number Diff line change
Expand Up @@ -20,20 +20,15 @@

// TEMP_FP8_OFFSET regression anchor: the down-activation TMA descriptor
// addresses `spec->temp_fp8` as `scratchpad_ptr + TEMP_FP8_OFFSET`, so that
// constant must equal `offsetof(MoEGemmSpec<Dims>, temp_fp8)`. New fields
// MUST be appended after temp_fp8 or this fires (docs/design_docs/monomoe_kernel.md §4).
static_assert(offsetof(monomoe::MoEGemmSpec<monomoe::Dims_BS8_E256_Qwen3_5_35B_BlockFP8_WGMMA_TMA>,
temp_fp8) ==
monomoe::MoEGemmSpec<
monomoe::Dims_BS8_E256_Qwen3_5_35B_BlockFP8_WGMMA_TMA>::TEMP_FP8_OFFSET,
"TEMP_FP8_OFFSET must match offsetof(MoEGemmSpec<Dims>, temp_fp8) for "
"Dims_BS8_E256_Qwen3_5_35B_BlockFP8_WGMMA_TMA. Do not insert fields "
"before temp_fp8; grid_barrier / partial_barrier belong at the tail of "
"MoEGemmSpec<Dims>.");
// constant must equal `offsetof(MoEGemmSpec<Dims>, temp_fp8)`. The check is
// emitted once per instantiated config (a generated per-config static_assert
// in monomoe_binding.cu, since the layout is Dims-dependent), so it lives
// there rather than being hard-coded to one shape here
// (docs/design_docs/monomoe_kernel.md §4).

/**
* @brief Host launcher for `moe_kernel_topk`, parameterized on the compile-time
* @p Dims shape variant with runtime top_k / scoring_func / renormalize.
* @brief Host launcher for `moe_kernel_topk<Dims>`, with runtime top_k /
* scoring_func / renormalize.
*
* Design doc: docs/design_docs/monomoe_kernel.md (section numbers below).
* Checks the co-residency invariant (§3), zero-inits the scratchpad on first
Expand Down Expand Up @@ -94,14 +89,23 @@ void monomoe_topk_launcher(TensorView activations_in, TensorView router_logits,
CUtensorMap activations_desc{};
CUtensorMap down_weights_desc{};
CUtensorMap down_activations_desc{};
if constexpr (use_tma_v<Dims>) {
if constexpr (use_tma<Dims>::value) {
up_weights_desc = create_up_weight_tma_desc(
reinterpret_cast<const void*>(expert_weights_up_ptr), Dims::NUM_EXPERTS, Dims::N, Dims::K);
// Row extent = the REAL token count, not Dims::BS: the TMA engine
// bounds-checks against globalDim and zero-fills out-of-bounds box rows,
// so for M < BS the routing-window load reads exactly M rows and
// hardware-zeros the phantom rows. Under CUDA graphs the descriptor is
// captured per graph (one graph per batch size), so the baked-in M
// always matches replays.
activations_desc = create_activations_tma_desc(
reinterpret_cast<const void*>(activations_in_ptr), Dims::BS, Dims::HIDDEN_STATES);
down_weights_desc = create_down_weight_tma_desc(
reinterpret_cast<const void*>(expert_weights_down_ptr), Dims::NUM_EXPERTS,
Dims::HIDDEN_STATES, Dims::N, /*row_box=*/MoECoreDims<Dims>::DOWN_COL_TILE);
reinterpret_cast<const void*>(activations_in_ptr), num_tokens, Dims::HIDDEN_STATES);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
// row_box pinned to 128: DOWN_COL_TILE can exceed the 256-row TMA boxDim
// cap (e.g. 384), so the kernel issues one 128-row TMA per M-atom.
down_weights_desc =
create_down_weight_tma_desc(reinterpret_cast<const void*>(expert_weights_down_ptr),
Dims::NUM_EXPERTS, Dims::HIDDEN_STATES, Dims::N,
/*row_box=*/128u);
// Down-activation descriptor reads `spec->temp_fp8` inside the
// scratchpad: base + compile-time offset (docs/design_docs/monomoe_kernel.md §4).
const void* temp_fp8_ptr =
Expand All @@ -113,19 +117,19 @@ void monomoe_topk_launcher(TensorView activations_in, TensorView router_logits,
const cudaStream_t stream = get_stream(activations_in.device());
CUDA_CHECK(cudaFuncSetAttribute(moe_kernel_topk<Dims>,
cudaFuncAttributeMaxDynamicSharedMemorySize, shmem_size));
// Co-residency invariant (docs/design_docs/monomoe_kernel.md §3): the barrier spin only avoids
// deadlock if GRID_SIZE <= SM count. Single cheap query off the hot path.
// Co-residency invariant (design doc §3): the sentinel/flag handoffs spin
// on values other blocks publish, so every block must be scheduled for the
// kernel's full lifetime — GRID_SIZE <= SM count.
int sm_count = 0;
cudaDeviceGetAttribute(&sm_count, cudaDevAttrMultiProcessorCount,
activations_in.device().device_id);
TVM_FFI_ICHECK(Dims::KernelConfig::GRID_SIZE <= static_cast<uint32_t>(sm_count))
<< "monomoe requires GRID_SIZE (=" << Dims::KernelConfig::GRID_SIZE
<< ") <= SM count (=" << sm_count << ") for software grid barrier co-residency invariant.";
// First-use scratchpad zero-init (docs/design_docs/monomoe_kernel.md §4): the barrier counters
// must start at 0; the ping-pong reset is self-maintaining thereafter.
// Key the guard on buffer identity (ptr, size, device) — a process-wide
// one-shot flag would leave a second distinct scratchpad with
// uninitialized counters and deadlock the spin.
<< ") <= SM count (=" << sm_count << ") for the co-residency invariant.";
// First-use scratchpad zero-init (design doc §4): establishes the 0.0f
// scale sentinel, launch_flip = 0, and down_ready = 0. All are
// self-maintaining afterwards (parity double-buffer refills). Keyed on
// buffer identity so each distinct scratchpad is initialized exactly once.
{
static const void* _zeroed_ptr = nullptr;
static size_t _zeroed_size = 0;
Expand All @@ -140,6 +144,9 @@ void monomoe_topk_launcher(TensorView activations_in, TensorView router_logits,
}
}

// Standard launch: cross-block ordering comes from the in-kernel
// sentinel/flag handoffs (design doc §2), which is what lets the kernel be
// captured into a CUDA Graph.
moe_kernel_topk<Dims><<<dim3(Dims::KernelConfig::GRID_SIZE, 1, 1),
dim3(Dims::KernelConfig::BLOCK_SIZE, 1, 1), shmem_size, stream>>>(
activations_in_ptr, num_tokens, router_logits_ptr, expert_weights_up_ptr,
Expand All @@ -149,10 +156,10 @@ void monomoe_topk_launcher(TensorView activations_in, TensorView router_logits,
CUDA_CHECK(cudaGetLastError());
}
// Explicit instantiation for the only BS8 variant (TMA + WGMMA +
// SWIZZLE_128B); materializes the launcher symbol that monomoe_binding.cu
// exports through TVM-FFI.
template void monomoe_topk_launcher<monomoe::Dims_BS8_E256_Qwen3_5_35B_BlockFP8_WGMMA_TMA>(
// Explicit instantiation of the launcher for the single hard-specialized
// shape (E=256, N=512, K=2048, block-wise FP8, BS8). This is byte-identical
// to the pre-tuning shipped kernel (formerly config 0).
template void monomoe_topk_launcher<::monomoe::Dims_BS8_E256_N512_K2048_BlockFP8_WGMMA_TMA>(
TensorView activations_in, TensorView router_logits, TensorView expert_weights_up,
TensorView expert_scales_up, TensorView expert_weights_down, TensorView expert_scales_down,
TensorView activations_out, TensorView scratchpad, int64_t top_k, int64_t scoring_func,
Expand Down
Loading
Loading