diff --git a/csrc/fused_moe/monomoe/monomoe_binding.cu b/csrc/fused_moe/monomoe/monomoe_binding.cu index 15cf734a0fe..2b0a9010964 100644 --- a/csrc/fused_moe/monomoe/monomoe_binding.cu +++ b/csrc/fused_moe/monomoe/monomoe_binding.cu @@ -14,6 +14,8 @@ * Licensed under the Apache License, Version 2.0. */ +#include + #include "monomoe_wrapper.cuh" // Declaration of the launcher function template (defined and explicitly @@ -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 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, temp_fp8)`; new +// fields go at the tail of MoEGemmSpec. +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, 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(activations_in, expert_weights_up, expert_weights_down)) { - monomoe_topk_launcher(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(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(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(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)` 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) so the buffer can never desync from the kernel's +// struct layout. int64_t monomoe_scratchpad_size() { return static_cast( - sizeof(monomoe::MoEGemmSpec)); + sizeof(::monomoe::MoEGemmSpec<::monomoe::Dims_BS8_E256_N512_K2048_BlockFP8_WGMMA_TMA>)); } TVM_FFI_DLL_EXPORT_TYPED_FUNC(monomoe_topk, monomoe_topk); diff --git a/csrc/fused_moe/monomoe/monomoe_wrapper.cuh b/csrc/fused_moe/monomoe/monomoe_wrapper.cuh index 88cc4a45f2b..a94c92f849a 100644 --- a/csrc/fused_moe/monomoe/monomoe_wrapper.cuh +++ b/csrc/fused_moe/monomoe/monomoe_wrapper.cuh @@ -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, 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, - temp_fp8) == - monomoe::MoEGemmSpec< - monomoe::Dims_BS8_E256_Qwen3_5_35B_BlockFP8_WGMMA_TMA>::TEMP_FP8_OFFSET, - "TEMP_FP8_OFFSET must match offsetof(MoEGemmSpec, 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."); +// constant must equal `offsetof(MoEGemmSpec, 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`, 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 @@ -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) { + if constexpr (use_tma::value) { up_weights_desc = create_up_weight_tma_desc( reinterpret_cast(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(activations_in_ptr), Dims::BS, Dims::HIDDEN_STATES); - down_weights_desc = create_down_weight_tma_desc( - reinterpret_cast(expert_weights_down_ptr), Dims::NUM_EXPERTS, - Dims::HIDDEN_STATES, Dims::N, /*row_box=*/MoECoreDims::DOWN_COL_TILE); + reinterpret_cast(activations_in_ptr), num_tokens, Dims::HIDDEN_STATES); + // 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(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 = @@ -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, 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(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; @@ -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<<>>( activations_in_ptr, num_tokens, router_logits_ptr, expert_weights_up_ptr, @@ -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( +// 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, diff --git a/csrc/fused_moe/monomoe/src/moe.cuh b/csrc/fused_moe/monomoe/src/moe.cuh index bf95794d44b..f0f91198d62 100644 --- a/csrc/fused_moe/monomoe/src/moe.cuh +++ b/csrc/fused_moe/monomoe/src/moe.cuh @@ -11,7 +11,6 @@ #define INSIDE_MONOMOE_IMPLEMENTATION #include "moe_down_projection.cuh" -#include "moe_grid_barrier.h" #include "moe_internal.h" #include "moe_routing.cuh" #include "moe_scale_inputs.cuh" @@ -22,15 +21,14 @@ namespace monomoe { /** - * @brief Top-K MoE kernel — split-phase WGMMA path for BS <= 8. + * @brief Top-K MoE kernel — split-phase TMA+WGMMA path for BS <= 8. * * Design doc: docs/design_docs/monomoe_kernel.md. The five-phase pipeline - * (routing+prefetch / quantize / up-proj / down-proj / writeback) and the two - * grid syncs between them are described in §1; the barriers in §2. Phase + * (routing+prefetch / quantize / up-proj / down-proj / writeback). Phase * markers below tie each block of code to that table. */ template -__device__ void moe_kernel_topk_BS8( +__device__ void moe_kernel_topk_impl( const A_element* __restrict__ activations_in, std::uint32_t batch_size, const __nv_bfloat16* __restrict__ router_logits, const W_element* __restrict__ expert_weights_up, const S_element* __restrict__ expert_scales_up, @@ -39,18 +37,21 @@ __device__ void moe_kernel_topk_BS8( uint32_t top_k, ScoringFunc scoring_func, bool renormalize, MoEGemmSpec* __restrict__ spec, MoE_SHM* __restrict__ shmem, CUtensorMap const& up_weights_desc, CUtensorMap const& activations_desc, - CUtensorMap const& down_weights_desc, CUtensorMap const& down_activations_desc, - uint32_t* __restrict__ grid_counters, uint32_t& grid_phase, - uint32_t* __restrict__ expert_counters, uint32_t& expert_phase, - uint32_t* __restrict__ colstripe_counters, uint32_t& colstripe_phase) { - static_assert(Dims::BS <= 8); - static_assert(use_wgmma_v, "BS8 path requires the WGMMA configuration (use_wgmma)."); - static_assert(use_tma_v, "BS8 path requires USE_TMA"); + CUtensorMap const& down_weights_desc, CUtensorMap const& down_activations_desc) { + static_assert(Dims::BS <= 8, + "moe_kernel_topk_impl supports BS<=8 (token_count > 8 is " + "rejected by the host dispatcher)."); + static_assert(use_wgmma::value, + "TMA+WGMMA path requires the WGMMA configuration (use_wgmma)."); + static_assert(use_tma::value, "TMA+WGMMA path requires USE_TMA"); using CoreDims = MoECoreDims; - // Zero-init `down_partial_out[BS][HIDDEN]` that Phase 4 atomicAdds into. - // All blocks zero a chunk in parallel; the Site-#2 expert_barrier is the - // cross-block visibility fence before any Phase-4 atomicAdd fires. + // Zero the Phase-4 accumulator (all blocks cooperate). No cross-block + // sync guards this against Phase-4 atomicAdds from fast blocks; the + // margin is structural — every block runs the full routing + quantize + + // up-projection pipeline (tens of µs) before its first Phase-4 + // atomicAdd, while this zero-fill retires within the first ~µs of the + // launch. { const uint32_t partial_n = Dims::BS * Dims::HIDDEN_STATES; for (uint32_t i = threadIdx.x + blockIdx.x * blockDim.x; i < partial_n; @@ -59,100 +60,60 @@ __device__ void moe_kernel_topk_BS8( } } - // ── Phase 1: routing (topK) + routing-window BF16 prefetch ───────────── - // Phase 1 runs routing (topK / prepare_moe_topk) which writes - // shmem->experts and shmem->topk_ids_flat that later phases depend on. - // - // In parallel with routing, the prefetch warps issue the routing- - // window TMA: a single 16-issue load that pulls the full per-block - // BF16 input tile (`BS × HIDDEN_STATES`) into `bf16_in_full`. - // Completion is signalled on the single mbarrier `bar_rwin` - // (`arrival_count = 1`, `tx_bytes = BS * K_BLOCKS_TOTAL * - // K_STEP_WGMMA * sizeof(A_element)`). Phase 2 then quantizes the - // full tile into `fp8_act_full`, which the up-projection K-loop - // reads directly — no per-K-step bf16 TMA, no `bar_a`. - // - // Correctness requirements: - // * mbarriers must be initialized before any `arrive_expect_tx`. - // The init and the arm run on the same launcher thread, so - // program order guarantees local visibility. The - // `fence_mbarrier_init_release_cluster()` below (and the - // block-wide `__syncthreads()` at the end of Phase 2) publishes - // the init to every consumer warp before it waits on - // `bar_rwin` / `bar_w[*]`. + // ── mbarrier init + sentinel-handoff launch parity ─────────────────── + // Inits run unconditionally (cheap SHM writes) so the barrier state is + // well-defined before any warp reaches its first try_wait. auto* u_tma = &shmem->tiny_wgmma_tma; if (is_tma_launcher_thread()) { - // mbarrier inits are kept regardless of the profile flags: they are - // cheap SHM writes and make the SHM state well-defined even when - // SKIP_PREFETCH elides every arrive/TMA below. The K-loop waits - // inside the up-proj helper are themselves gated on SKIP_PREFETCH, - // so a consumer will never block on an uninitialized parity. - mbarrier_init(&u_tma->bar_w[0], 1u); - mbarrier_init(&u_tma->bar_w[1], 1u); -#ifdef MONO_PROFILE_BARW_4DEEP - // 2-deep up-proj weight pipeline: slots 2 and 3 hold lookahead - // tiles `(s+2) & 3` issued at iter `s`. Initializing them in - // the prologue (rather than re-initializing in the up-proj - // helper) reuses the existing fence_mbarrier_init_release_cluster - // sequence already covering bar_w[0..1]. The down-proj phase - // doesn't use slots 2 and 3 — they're left untouched at the - // down-proj re-init and stay armed-or-idle accordingly. - mbarrier_init(&u_tma->bar_w[2], 1u); - mbarrier_init(&u_tma->bar_w[3], 1u); -#endif - // Phase-1 routing-window mbarrier. Single mbarrier with - // arrival_count = 1 and tx_bytes = BS * K_BLOCKS_TOTAL * - // K_STEP_WGMMA * sizeof(A_element) (= 32 KB for Qwen3.5). Armed by - // the TMA launcher thread at the start of Phase 1; waited on by - // every warp in [1, 12) at the start of Phase 2 before reading - // bf16_in_full. Init shares the same launcher-thread / fence - // discipline as bar_w so consumers never block on an - // uninitialized parity. +#pragma unroll + for (uint32_t i = 0; i < MoECoreDims::UP_W_SLOTS; ++i) { + mbarrier_init(&u_tma->bar_w[i], 1u); + } mbarrier_init(&u_tma->bar_rwin, 1u); fence_mbarrier_init_release_cluster(); } - // Block-wide barrier publishes the mbarrier inits to every warp - // before any warp issues a `try_wait.parity` against them. Without - // this sync, warp 9 (a non-launcher prefetch warp) can race past - // the launcher's `mbarrier_init(&bar_rwin, 1u)` and hit the Phase-2 - // wait loop while `bar_rwin` is still in an undefined state, which - // compute-sanitizer flags as `Unknown Error` at the - // `SYNCS.PHASECHK.TRANS64.TRYWAIT` instruction (mbarrier state - // corruption). `bar_w[*]` was previously protected by the calc-warp - // path's early `topK_BS8` cost; `bar_rwin` is the only mbarrier - // waited on by EVERY warp 1..11 with no intervening prior work, so - // the discipline must be made explicit here. - // - // `fence_mbarrier_init_release_cluster()` alone is not sufficient: - // it pairs with a matching acquire on the consuming side, but - // `mbarrier.try_wait.parity` is not an acquire of the init; it - // assumes the init has already been published. The `__syncthreads()` - // is what publishes the launcher-thread-only init writes to all - // warps. + if (threadIdx.x == 0) { + // Per-block private launch counter → scale-buffer parity for the + // sentinel Phase-3→4 handoff. No cross-block sync needed: each block + // increments only its own word, once per launch, so all blocks agree. + const uint32_t flip = spec->launch_flip[blockIdx.x]; + shmem->scale_parity = flip & 1u; + spec->launch_flip[blockIdx.x] = flip + 1u; + } + // Publish the launcher-thread inits to every warp before any + // try_wait.parity. fence_mbarrier_init alone is not sufficient: it pairs + // with a matching acquire, but try_wait.parity is not an acquire of the + // init — without this sync a prefetch warp can hit the Phase-2 bar_rwin + // wait while the barrier is still uninitialized (mbarrier state + // corruption under compute-sanitizer). Also publishes scale_parity. __syncthreads(); - // ── Phase 1 — Routing-window concurrent dispatch. - // - // Re-organized as an if-elif-else over warp identity: - // * warp ∈ [8, 12) (prefetch warps): - // - TMA launcher thread (warp 8, lane 0) arms `bar_rwin` once - // with `tx_bytes = BS * K_BLOCKS_TOTAL * K_STEP_WGMMA * - // sizeof(A_element)` (= 32 KB for Qwen3.5) and issues - // K_BLOCKS_TOTAL `cp.async.bulk.tensor.2d` instructions - // covering the full per-block BF16 input tile via - // `moe_load_full_bf16_input`. The matching wait - // lives in the Phase-2 dispatch. - // - Other prefetch lanes do nothing in Phase 1. - // * warp ∈ [0, 8) (calc warps): unchanged `topK_BS8` + - // `sync_calc_threads<>()` (256-thread `bar.sync 15`). - // `prepare_moe_topk_BS8` runs in Phase 2 on warp 0 alongside - // `routing_phase_quantize` on warps 1..11. + + // Zero-refill the OTHER parity's handoff state for the NEXT launch + // (sentinel reset, off the critical path — nobody reads those words + // this launch; kernel completion publishes them before the next launch + // starts). The host-side torch.zeros allocation establishes the same + // invariant before the first launch. + { + constexpr uint32_t SCALE_N = + MoEGemmSpec::TEMP_ROWS * MoEGemmSpec::TEMP_ACT_SCALE_COLS; + const uint32_t next_parity = shmem->scale_parity ^ 1u; + float* next_buf = moe_act_scale_buf(spec, next_parity); + for (uint32_t i = threadIdx.x + blockIdx.x * blockDim.x; i < SCALE_N; + i += blockDim.x * gridDim.x) { + reinterpret_cast(next_buf)[i] = 0u; // +0.0f sentinel + } + // Phase-4→5 readiness counters for the next launch (site #3 flags). + if (threadIdx.x < MoEGemmSpec::DOWN_GRID && blockIdx.x == 0) { + spec->down_ready[next_parity][threadIdx.x] = 0u; + } + } + + // ── Phase 1: routing ∥ routing-window BF16 prefetch ─────────────────── const unsigned warp_id = get_any_warp(); if (warp_id >= CoreDims::CALC_WARP_COUNT) { - // Prefetch warps + TMA launcher thread (warp ∈ [8, 12)). + // Prefetch warps: the launcher arms bar_rwin once for the whole tile + // and issues the K_BLOCKS_TOTAL bulk loads; other lanes idle. if (is_tma_launcher_thread()) { - // Single mbarrier arm covers all K_BLOCKS_TOTAL bulk loads. - // The helper itself does not arm — see the doc comment on - // `moe_load_full_bf16_input` for the caller contract. constexpr std::uint32_t RWIN_TX_BYTES = Dims::BS * MoE_SHM::TinyDataWGMMA_TMA::K_BLOCKS_TOTAL * CoreDims::K_STEP_WGMMA * static_cast(sizeof(A_element)); @@ -160,43 +121,21 @@ __device__ void moe_kernel_topk_BS8( /*tx_bytes=*/RWIN_TX_BYTES); moe_load_full_bf16_input(activations_desc, u_tma->bf16_in_full, &u_tma->bar_rwin); } - // Other prefetch lanes (warp 8 lanes 1..31, warps 9..11) do - // nothing in Phase 1. Phase 2 re-engages them as - // BF16→FP8 quantization workers. } else { - // Calc warps (warp ∈ [0, 8)). `topK_BS8` and `prepare_moe_topk_BS8` - // build `shmem->expert_count` / `shmem->experts[e].id`, which drive - // the downstream per-expert loop bounds. - topK_BS8(top_k, scoring_func, renormalize, router_logits, batch_size, shmem); + // Calc warps run routing: shmem->expert_count / experts[] drive + // downstream loop bounds and must always be valid. + topK(top_k, scoring_func, renormalize, router_logits, batch_size, shmem); sync_calc_threads(); - // `prepare_moe_topk_BS8` is no longer called from the calc-warp - // branch — it now runs in the Phase-2 dispatch below on warp 0 - // only, alongside `routing_phase_quantize` on warps 1..11. } - // ── Phase 2 — Prepare-phase concurrent dispatch. - // - // Warp dispatch over the 12 warps in the block: - // * warp 0: runs `prepare_moe_topk_BS8` (builds expert ids, - // `sorted_slot`, `expert_count`, `expert_slot_start[]`). Does - // NOT wait on `bar_rwin` because warp 0 does not read - // `bf16_in_full`. - // * warps 1..11: wait on `bar_rwin` (paired with the Phase-1 - // 16-issue TMA load armed in 4.1) and then run - // `routing_phase_quantize`, which calls - // `moe_streaming_quantize_k128` once per (token, k_block) pair - // across the 11 warps in stride-11 partition. - // - // The trailing `__syncthreads()` is the SINGLE block-wide sync - // that ends Phase 2: it publishes BOTH warp 0's routing - // metadata writes AND warps 1..11's `fp8_act_full` / `act_scale` - // writes to all warps before Phase 3 begins. No additional - // intra-Phase-2 sync between warp 0 and warps 1..11 is required — - // they touch disjoint SHM (warp 0 writes - // `experts[]`/`sorted_slot[]`/...; warps 1..11 write - // `fp8_act_full`/`act_scale`). + // ── Phase 2: prepare (warp 0) ∥ quantize (warps 1..11) ──────────────── + // Warp 0 builds the routing tables and does not read bf16_in_full, so it + // skips the bar_rwin wait. Warps 1..11 wait for the Phase-1 load, then + // quantize bf16 → fp8_act_full + act_scale. The two sides touch + // disjoint SHM; the single trailing __syncthreads() publishes both to + // all warps before Phase 3. if (warp_id == 0) { - prepare_moe_topk_BS8(batch_size, top_k, shmem, spec); + prepare_moe_topk(batch_size, top_k, shmem); } else { uint32_t parity_rwin = 0; while (!mbarrier_try_wait_parity(&u_tma->bar_rwin, parity_rwin)) { @@ -206,79 +145,82 @@ __device__ void moe_kernel_topk_BS8( } __syncthreads(); - // ── Up-projection group mapping (docs/design_docs/monomoe_kernel.md §6) ──────────────────────── - // UP_GRID blocks cover one expert's 2*N rows; UP_GROUPS expert groups run - // in parallel. For this shape: UP_GRID=8, UP_GROUPS=16. + // ── Phase 3: up-projection — expert groups in parallel ──────────────── + // Group g (blocks [g*UP_GRID, (g+1)*UP_GRID)) iterates experts starting + // at index g, stepping by UP_GROUPS. Groups write disjoint temp_fp8 + // rows (each routed (tok, expert) pair has its own sorted_slot row). constexpr std::uint32_t UP_GRID = 2 * Dims::N / CoreDims::W_UP_TILE_EFFECTIVE; constexpr std::uint32_t UP_GROUPS = Dims::KernelConfig::GRID_SIZE / UP_GRID; static_assert(Dims::KernelConfig::GRID_SIZE % UP_GRID == 0, "GRID_SIZE must be a multiple of UP_GRID."); - // UP_GROUPS has no correctness upper bound (blocks whose expert isn't in a - // token's top-K just skip the write) — higher only means wasted WGMMAs. static_assert(UP_GROUPS <= Dims::NUM_EXPERTS, "UP_GROUPS cannot exceed the total number of experts."); const std::uint32_t up_group = blockIdx.x / UP_GRID; const std::uint32_t up_block_idx = blockIdx.x % UP_GRID; const bool in_up = (up_group < UP_GROUPS); - // No __syncthreads() before Phase 3: the Phase-2 trailing sync already - // published `fp8_act_full` / barrier init / `expert_count`, and the - // up_group/up_block_idx math is pure register work. The up-proj helper - // primes its own weight tile (pre-loop `bar_w[0]` arm + first TMA). - - // ── Phase 3: Up-projection — expert groups in parallel (docs/design_docs/monomoe_kernel.md §1) - // Group `g` iterates experts from index `g` stepping by UP_GROUPS, writing - // disjoint `temp_fp8` slabs (no write conflict). TMA+WGMMA dispatch is - // unconditional (asserted at function top). if (in_up && up_group < shmem->expert_count) { - moe_up_projection_BS8_allexperts_wgmma_tma( - activations_in, expert_weights_up, expert_scales_up, top_k, batch_size, spec, shmem, - up_weights_desc, activations_desc, up_block_idx, - /*expert_start=*/up_group, - /*expert_stride=*/UP_GROUPS); + // Single-atom interleaved up-projection (UP_COL_HALVES == 1): one + // 128-row A-tile packs 64 gate + 64 up rows in the gate/up pair layout. + static_assert(CoreDims::UP_COL_HALVES == 1u, + "this shape uses the interleaved (UCH==1) up-projection."); + moe_up_projection_allexperts_wgmma_tma(activations_in, expert_weights_up, + expert_scales_up, top_k, batch_size, spec, shmem, + up_weights_desc, activations_desc, up_block_idx, + /*expert_start=*/up_group, + /*expert_stride=*/UP_GROUPS); } - // ── Site #2 — Expert-local barrier, Phase 3→4 (docs/design_docs/monomoe_kernel.md §2) ───────── - // DOWN_GROUPS == UP_GROUPS aligns the producer set (8 blocks that wrote - // expert group `g`'s temp_fp8 rows) with the consumer set, so an - // expert_barrier keyed on `up_group` is sufficient (vs a full grid sync). - // `in_up` is always true here but gated defensively for future configs. - if (in_up) { - monomoe::expert_barrier(expert_counters, - /*expert_id=*/up_group, - /*arrival_count=*/UP_GRID, - /*seed_blockidx=*/up_group * UP_GRID, expert_phase); - } + // ── Site #2: Phase 3 → Phase 4 handoff — SENTINEL, NO BARRIER ───────── + // + // Replaced by data-path readiness: each `temp_act_scale` cell is + // release-published by its producing warp AFTER the covering fp8 + // payload segment (moe_publish_act_scale), and the down-projection + // polls exactly the cells it consumes until they turn non-NaN before + // reading/TMA-loading the payload (see the act-scale loader and the + // inter-expert lookahead poll in moe_down_projection.cu). + // + // This gives per-expert granularity — a down-block starts an expert as + // soon as THAT expert's rows are published, instead of waiting for its + // whole up-group — and covers the coupled and decoupled carves + // uniformly (consumers wait on data, so producer set != consumer set + // needs no special protocol). Barrier-counter state is no longer + // involved in this handoff, which also removes the decoupled + // consume-wait stale-marker hazard. - // ── Phase 4 (WGMMA): dual-WG streaming down-projection ── - // (docs/design_docs/monomoe_kernel.md §1,§6) - // Blocks partition into DOWN_GROUPS expert groups × DOWN_GRID col-blocks, - // each owning DOWN_COL_TILE output cols. Every contributing block - // atomicAdds its partial into the single-buffer `down_partial_out` (zeroed - // at kernel entry); Phase 5 reads each cell once. Dispatch unconditional. - moe_down_projection_BS8_allexperts_wgmma_tma(expert_weights_down, expert_scales_down, top_k, - batch_size, spec, shmem, down_weights_desc, - down_activations_desc); + // ── Phase 4: down-projection ────────────────────────────────────────── + moe_down_projection_allexperts_wgmma_tma(expert_weights_down, expert_scales_down, top_k, + batch_size, spec, shmem, down_weights_desc, + down_activations_desc); - // ── Site #3 — Col-stripe-local barrier, Phase 4→5 (docs/design_docs/monomoe_kernel.md §2) ───── - // Phase 5 reader for col stripe `b` is `blockIdx.x == b`; its producer set - // is the DOWN_GROUPS blocks with `blockIdx.x % DOWN_GRID == b`, which is - // exactly the colstripe_barrier arrival set (and `b` is its own seed). - // Every block calls it to publish its Phase-4 atomicAdd. + // ── Site #3: Phase 4 → Phase 5 handoff — FLAGS, NO BARRIER ──────────── + // Phase 5 on block b reads down_partial_out cells at col stripe b, whose + // producers are the DOWN_GROUPS blocks with blockIdx.x % DOWN_GRID == b. + // + // down_partial_out is atomicAdd-accumulated, so readiness cannot live + // in the data itself; instead every block publishes its Phase-4 adds + // by bumping its stripe's parity-selected arrival counter (release + // fence + add), and ONLY the stripe's Phase-5 writer polls it up to + // DOWN_GROUPS. The other blocks publish and run to kernel exit — no + // grid-wide mutual spin. Counter reset is the launch-parity + // double-buffer refilled in the prologue (same discipline as the + // site-#2 scale sentinel). { const uint32_t col_stripe_id = blockIdx.x % MoECoreDims::DOWN_GRID; - monomoe::colstripe_barrier(colstripe_counters, - /*col_stripe=*/col_stripe_id, - /*arrival_count=*/MoECoreDims::DOWN_GROUPS, - /*seed_blockidx=*/col_stripe_id, colstripe_phase); + // All threads' Phase-4 atomicAdds are issued before this sync; the + // fence releases them at device scope before the arrival is visible. + __syncthreads(); + if (threadIdx.x == 0) { + __threadfence(); + atomicAdd(&spec->down_ready[shmem->scale_parity][col_stripe_id], 1u); + } } - // ── Phase 5 (WGMMA): bf16 cast + writeback (docs/design_docs/monomoe_kernel.md §1) ───────────── - // Each Phase-5 block reads its own DOWN_COL_TILE cols × BS tokens of fp32 - // sums (already reduced by the Phase-4 atomicAdds) and casts to bf16 — a - // streaming load+cast+store, no cross-group reduction. Only the first - // DOWN_GRID blocks write (gate on `down_group == 0`); the rest would map to - // duplicate cols via `blockIdx.x % DOWN_GRID`. + // ── Phase 5: fp32 → bf16 cast + writeback ───────────────────────────── + // Each cell of down_partial_out already holds the full sum (Phase-4 + // atomicAdds); the first DOWN_GRID blocks stream-cast their own col + // stripe. Every element of the M-row output is `=`-written, so no + // output pre-zero pass exists anywhere. constexpr std::uint32_t DOWN_GRID_LOCAL = CoreDims::DOWN_GRID; constexpr std::uint32_t DOWN_COL_TILE_LOCAL = CoreDims::DOWN_COL_TILE; const std::uint32_t down_group_r = blockIdx.x / DOWN_GRID_LOCAL; @@ -286,11 +228,18 @@ __device__ void moe_kernel_topk_BS8( const std::uint32_t base_col_r = down_block_idx_r * DOWN_COL_TILE_LOCAL; if (down_group_r == 0) { - // Phase 5 with atomicAdd writeback: read the SINGLE fp32 cell at - // `partial[tok][col]` (already the sum across all 16 contributing - // blocks via Phase-4 atomicAdds) and cast to bf16. No DOWN_GROUPS - // dimension to reduce over — this is just a streaming - // load + cast + store. + // Readiness wait: this block is the single Phase-5 writer for col + // stripe `down_block_idx_r` (== blockIdx.x here). One thread polls + // the stripe's arrival counter, acquires, and the __syncthreads + // broadcasts the observation to the whole block. + if (threadIdx.x == 0) { + uint32_t* ctr = &spec->down_ready[shmem->scale_parity][down_block_idx_r]; + while (atomicAdd(ctr, 0u) < MoECoreDims::DOWN_GROUPS) { + } + __threadfence(); + } + __syncthreads(); + for (std::uint32_t flat = threadIdx.x; flat < batch_size * DOWN_COL_TILE_LOCAL; flat += blockDim.x) { const std::uint32_t tok = flat / DOWN_COL_TILE_LOCAL; @@ -300,35 +249,23 @@ __device__ void moe_kernel_topk_BS8( activations_out[tok * Dims::HIDDEN_STATES + col] = (R_element)v; } - // Zero out activations_out[tok] for tok in [batch_size, Dims::BS) - // for this block's DOWN_COL_TILE col stripe. - for (std::uint32_t flat = threadIdx.x; flat < (Dims::BS - batch_size) * DOWN_COL_TILE_LOCAL; - flat += blockDim.x) { - const std::uint32_t tok = batch_size + flat / DOWN_COL_TILE_LOCAL; - const std::uint32_t col_in_block = flat % DOWN_COL_TILE_LOCAL; - const std::uint32_t col = base_col_r + col_in_block; - activations_out[tok * Dims::HIDDEN_STATES + col] = (R_element)0.0f; - } + // No padding-row writes: activations_out is an M-row tensor and rows + // [batch_size, Dims::BS) do not exist (writing them was an + // out-of-bounds store for M < 8; no consumer ever read them). } } /** - * @brief Top-K MoE kernel with configurable scoring and renormalization. + * @brief Kernel entry point. Dispatches to moe_kernel_topk_impl. * - * Dispatches to moe_kernel_topk_BS8 (BS <= 8). + * The TMA descriptors are built host-side (moe_wrapper.cu) and passed as + * `__grid_constant__` parameters. * - * `up_weights_desc` and `activations_desc` are the host-built TMA - * descriptors consumed by `moe_up_projection_BS8_allexperts_wgmma_tma` when - * `use_tma_v` is true. For non-TMA variants the torch-binding - * wrapper passes zero-initialized `CUtensorMap` values and the descriptors - * are never read. The `__grid_constant__` qualifier - * places them in constant memory coherent with all threads without SMEM - * cost. + * `__launch_bounds__(BLOCK_SIZE, 1)` is the compile-time half of the + * one-block-per-SM co-residency invariant the software barriers rely on + * (every participating block must be scheduled from launch); the host + * launcher checks the runtime half (GRID_SIZE <= SM count). */ -// `__launch_bounds__(BLOCK_SIZE, 1)` pins one block per SM — the compile-time -// half of the co-residency invariant the barrier spin depends on -// (docs/design_docs/monomoe_kernel.md §3); the launcher enforces -// `GRID_SIZE <= SM_count` at runtime. template __global__ __launch_bounds__(Dims::KernelConfig::BLOCK_SIZE, 1) void moe_kernel_topk( const A_element* __restrict__ activations_in, std::uint32_t token_count, @@ -341,22 +278,12 @@ __global__ __launch_bounds__(Dims::KernelConfig::BLOCK_SIZE, 1) void moe_kernel_ __grid_constant__ CUtensorMap const activations_desc, __grid_constant__ CUtensorMap const down_weights_desc, __grid_constant__ CUtensorMap const down_activations_desc) { - // Compile-time preconditions on `Dims` (fire at first instantiation): - // TMA requires WGMMA (no scalar TMA path), and the SHM footprint must fit - // the H100 opt-in 228 KB per-block budget. The third assert is the same - // budget specialized to BS8 TMA+WGMMA, where DOWN_COL_TILE=256 doubles the - // per-slot down-proj weight tile — kept pointed so a layout regression - // names that cause. - static_assert(!use_tma_v || use_wgmma_v, + static_assert(!use_tma::value || use_wgmma::value, "USE_TMA requires USE_WGMMA; no TMA support for the scalar " "path."); - static_assert(!use_tma_v || sizeof(MoE_SHM) <= 228 * 1024, + static_assert(!use_tma::value || sizeof(MoE_SHM) <= 228 * 1024, "MoE_SHM exceeds the 228 KB per-block SHM budget " "for TMA variants."); - static_assert(!(use_tma_v && Dims::BS <= 8) || sizeof(MoE_SHM) <= 228 * 1024, - "Exceeds 228 KB opt-in SHM budget for BS8 TMA+WGMMA after " - "Phase 2a layout alignment (DOWN_COL_TILE = 256 doubles " - "the per-block down-proj weight tile)."); assert(MoECoreDims::THREADS_PER_WARP == 32); assert(blockDim.x == Dims::KernelConfig::BLOCK_SIZE); @@ -375,28 +302,13 @@ __global__ __launch_bounds__(Dims::KernelConfig::BLOCK_SIZE, 1) void moe_kernel_ extern __shared__ char shmem_buffer[]; MoE_SHM* shmem = reinterpret_cast*>(shmem_buffer); - // Barrier counter-region pointers (into the scratchpad tail; see - // docs/design_docs/monomoe_kernel.md §4) and per-region phase counters - // (block-local registers, init 0, bumped by each barrier call; §2). - uint32_t* grid_counters = spec->grid_barrier.slot; - uint32_t* expert_counters = &spec->partial_barrier.expert_slot[0][0]; - uint32_t* colstripe_counters = &spec->partial_barrier.colstripe_slot[0][0]; - uint32_t grid_phase = 0; - uint32_t expert_phase = 0; - uint32_t colstripe_phase = 0; - constexpr uint32_t GRID_SIZE_STATIC = Dims::KernelConfig::GRID_SIZE; - - // No top-of-kernel output zero-out: Phase 5 `=`-writes every element of - // activations_out (reduced sum for [0, batch_size), zeros for the rest), so - // a pre-zero would be dead work. + // Cross-block ordering is entirely flag/sentinel-based (sites #2 and + // #3 inside moe_kernel_topk_impl); no software barrier counters remain. - static_assert(Dims::BS <= 8, "Only BS <= 8 is supported."); - moe_kernel_topk_BS8(activations_in, token_count, router_logits, expert_weights_up, - expert_scales_up, expert_weights_down, expert_scales_down, - activations_out, top_k, scoring_func, renormalize, spec, shmem, - up_weights_desc, activations_desc, down_weights_desc, - down_activations_desc, grid_counters, grid_phase, expert_counters, - expert_phase, colstripe_counters, colstripe_phase); + moe_kernel_topk_impl( + activations_in, token_count, router_logits, expert_weights_up, expert_scales_up, + expert_weights_down, expert_scales_down, activations_out, top_k, scoring_func, renormalize, + spec, shmem, up_weights_desc, activations_desc, down_weights_desc, down_activations_desc); } } // namespace monomoe diff --git a/csrc/fused_moe/monomoe/src/moe_down_projection.cuh b/csrc/fused_moe/monomoe/src/moe_down_projection.cuh index de17b7dfa01..1db2ce22b32 100644 --- a/csrc/fused_moe/monomoe/src/moe_down_projection.cuh +++ b/csrc/fused_moe/monomoe/src/moe_down_projection.cuh @@ -15,59 +15,28 @@ #include "moe_tma.h" #include "ptx_utils.h" -// Phase 4 down-projection — `moe_down_projection_BS8_..._tma` -// (docs/design_docs/monomoe_kernel.md §1/§6) -// streams fp8 weight/activation tiles via TMA into double-buffered SHM, runs the -// dual-warpgroup WGMMA K-loop with per-128-K block-FP8 scale-apply, overlaps -// expert transitions via inter-expert lookahead, then atomicAdds each block's -// fp32 partial into `spec->down_partial_out` for Phase 5 to cast. Per-function -// and per-line specifics are documented inline below. - namespace monomoe { /** - * @brief Per-expert activation-scale loader (down-projection, TMA path). - * - * Loads ALL `T_TILE × (Dims::N / 64)` per-token activation scales for - * the current expert into `a_down_scale[col_block][tok]`. Called ONCE - * per expert at the top of the per-expert loop, NOT per K-step. This - * is the hoisted-out-of-K-loop variant: the K-loop's WGMMA scale-apply - * indexes `a_down_scale[s * K_SUBSTEPS_DOWN * 2 + 2 * kk + half][tok]` - * directly, removing the per-K-step cp.async + pipe drain that the - * older variant required. + * @brief Per-expert activation-scale loader (down-projection). * - * Rank-indexing invariant: - * `a_down_scale[col_block][rank]` must match the scale for the token - * whose fp8 payload sits at `a_down_wgmma[slot][?][rank][kc][ki]`. - * That fp8 payload is loaded by the bulk-per-expert TMA from GM rows - * `[expert_slot_start[id], expert_slot_start[id] + routed_count)` - * of `spec->temp_fp8`. Those same rows were written by the Phase-3 - * up-proj epilogue at `dest_row = sorted_slot[pair] = - * expert_slot_start[id] + rank`, alongside - * `temp_act_scale[dest_row][...]` at the same row, so reading scales - * from row `expert_slot_start[id] + rank` guarantees byte-level - * alignment between the fp8 payload and its per-token scale. + * Loads ALL T_TILE × (N / DOWN_ACT_BLOCK_SIZE) per-token activation scales + * for the current expert into `a_down_scale[block][tok]`, once per expert + * (the K-loop's scale-apply then indexes SHM directly — no per-K-step + * reload). * - * Thread mapping: - * - Gated to prefetch warp `RUN_PW` (one of 0..3 = warps 8..11). - * - Within that warp, lanes 0..(T_TILE * (N/64) - 1) each load one - * scale. For Qwen3.5 (T_TILE=8, N/64=8): 64 lanes — but we only - * have 32 in a warp, so each lane does TWO loads via a stride-32 - * loop. Tiny work either way (≤256 B per expert). + * Rank-indexing invariant: `a_down_scale[block][rank]` must match the token + * whose fp8 payload the bulk activation TMA fetches from temp_fp8 row + * `expert_slot_start[id] + rank` — the same row the up-proj epilogue wrote + * via sorted_slot, alongside temp_act_scale at that row. Reading scales + * from that row guarantees payload/scale alignment. * - * @tparam Dims MoE dims. - * @tparam ScaleTok Must be T_TILE (8). - * @tparam ScaleHalves Must be Dims::N / 64. - * @tparam RunPw Prefetch-warp gate (0..3). Use 0 for warp 8, - * 1 for warp 9, etc. - * @param spec Global scratchpad (reads `temp_act_scale`). - * @param shmem SHM struct (reads `expert_routed_count`, - * `expert_slot_start`). - * @param id Current expert id. - * @param dest_scale SHM `a_down_scale[N/64][T_TILE]`. + * GM temp_act_scale is [row][block]; SHM a_down_scale is [block][tok] + * (bank-conflict-free reads in the WGMMA scale-apply) — this loop + * transposes on the fly. * - * @note Prefetch-warp only. Caller MUST ensure a `__syncthreads()` - * before the K-loop reads `a_down_scale`. + * Runs on prefetch warp `RunPw` only; the caller must __syncthreads() + * before the K-loop reads a_down_scale. */ template __device__ inline void moe_load_down_wgmma_act_scale_per_expert( @@ -76,122 +45,121 @@ __device__ inline void moe_load_down_wgmma_act_scale_per_expert( using CoreDims = MoECoreDims; static_assert(ScaleTok == CoreDims::T_TILE, "down-proj activation scale tile must have T_TILE=8 tokens"); - static_assert(ScaleHalves == Dims::N / 64u, - "down-proj activation scale tile must have N/64 halves " - "per token (one per per-64-col up-block, full reduction " - "dim)"); + static_assert(ScaleHalves == Dims::N / CoreDims::DOWN_ACT_BLOCK_SIZE, + "down-proj activation scale tile must have one block per " + "up-block across the full reduction dim"); - constexpr unsigned ACT_BLOCK = 64; // per-64-col up-block - constexpr unsigned SCALE_COLS = Dims::N / ACT_BLOCK; // = ScaleHalves + constexpr unsigned SCALE_COLS = Dims::N / CoreDims::DOWN_ACT_BLOCK_SIZE; const unsigned thread = get_thread(); - const unsigned pw = get_prefetch_warp(); // 0..3 + const unsigned pw = get_prefetch_warp(); if (pw != RunPw) return; - // Cache routed_count / expert_start once per thread (cheap broadcast). const auto* tma_shm = &shmem->tiny_wgmma_tma; const uint32_t routed_count = static_cast(tma_shm->expert_routed_count[id]); const uint32_t expert_start = static_cast(tma_shm->expert_slot_start[id]); - // Strided loop over the (slot_row, half) plane. Total entries = - // T_TILE * SCALE_COLS = 8 * 8 = 64; one warp's 32 lanes - // do 2 loads each (stride 32). GM `temp_act_scale` is `[row][half]` - // (row-major, written by the up-proj epilogue) but SHM - // `a_down_scale` is `[half][row]` (chosen for bank-conflict-free - // reads in the down-proj WGMMA scale-apply, see comment on the SHM - // declaration in `MoE_SHM::TinyDataWGMMA_TMA`). This loop - // transposes on the fly. + // Sentinel handoff (replaces the site-#2 barrier): the up-proj epilogue + // release-publishes each scale AFTER its fp8 payload segment, so + // polling a cell until it turns non-zero is the readiness wait for + // exactly the payload this expert consumes. Device-scope atomic reads + // (ld.acquire.gpu on SM90) bypass the non-coherent L1. + uint32_t* scale_bits = reinterpret_cast( + moe_act_scale_buf(const_cast*>(spec), shmem->scale_parity)); + constexpr unsigned TOTAL = (unsigned)(ScaleTok * ScaleHalves); for (unsigned i = thread; i < TOTAL; i += 32u) { - const unsigned slot_row = i / SCALE_COLS; // 0..T_TILE-1 - const unsigned half = i % SCALE_COLS; // 0..ScaleHalves-1 + const unsigned slot_row = i / SCALE_COLS; + const unsigned half = i % SCALE_COLS; if (slot_row < routed_count) { const uint32_t source_row = expert_start + slot_row; - dest_scale[half][slot_row] = spec->temp_act_scale[source_row * SCALE_COLS + half]; + uint32_t* cell = scale_bits + source_row * SCALE_COLS + half; + uint32_t bits = atomicAdd(cell, 0u); + while (moe_scale_is_sentinel(bits)) { + bits = atomicAdd(cell, 0u); + } + dest_scale[half][slot_row] = __uint_as_float(bits); } else { - // Unused rank — see preamble in the BS8 down-proj kernel for - // why the value doesn't matter. Set to 0 for cleanliness. + // Unused rank — never consumed (the rank-filtered accumulate skips + // it); zeroed for cleanliness. dest_scale[half][slot_row] = 0.f; } } + + // Acquire for the payload behind the observed flags, then join the + // warp: this loader runs on the TMA launcher's warp, so after the + // syncwarp the launcher's activation-TMA issue (later in program + // order) is gated on EVERY lane's polls, not just its own. + __threadfence(); + __syncwarp(); } /** - * @brief streaming-pipeline WGMMA down-projection weight-scale tile loader. - * - * Loads one K-step's worth of the down-projection's fp32 weight scales - * into a SHM slot — one scale per (warpgroup, col-block) pair. There - * are 2 warpgroups (WG0 covers weight rows `[base_col..base_col+63]`, - * WG1 covers rows `[base_col+64..base_col+127]`) and `W_DOWN_SCALE_COLS` - * col-blocks along the K = Dims::N dimension. (For block-wise quant, - * `W_DOWN_SCALE_COLS == Dims::DOWN_SCALE_COLS == N/128`; for per-channel, - * it is a 1-wide placeholder and these bytes are never consumed.) + * @brief Single-thread readiness wait for one expert's published scales. * - * The down-proj weight matrix is `[NUM_EXPERTS, HIDDEN_STATES, N]`, so - * the 128 output cols that this down-block owns map to 128 weight rows - * `[base_col, base_col + 128)`. Because `base_col` is a multiple of - * 128, WG0's 64 weight rows and WG1's 64 weight rows always fall within - * the SAME 128-row scale-block (so `row_block_wg0 == row_block_wg1`), - * but we still compute and store both independently for generality. + * Sentinel-handoff companion for the inter-expert LOOKAHEAD activation + * TMA: the launcher issues the NEXT expert's K=0 activation tile while + * the current expert is still computing, i.e. BEFORE the next expert's + * loader poll runs — so the launcher must confirm the next expert's + * payload is published first. Sweep-polls all (row, half) cells of the + * expert (independent reads pipeline within a sweep; re-sweeps until no + * sentinel remains), then acquires. * - * Scale tensor layout (block-wise): - * `expert_scales_down[NUM_EXPERTS][DOWN_SCALE_ROWS][DOWN_SCALE_COLS]` fp32, - * where `DOWN_SCALE_ROWS = HIDDEN_STATES / 128` - * and `DOWN_SCALE_COLS = N / 128`. - * - * SHM layout written: - * `dest[wg][col_block]` for `wg in [0, 2)`, `col_block in [0, - * W_DOWN_SCALE_COLS)`. - * - * Thread distribution: the first prefetch warp loads all - * `2 * W_DOWN_SCALE_COLS` scalars synchronously. - * For W_DOWN_SCALE_COLS=4, this is just 8 fp32 values — well under a warp. - * No async copy is used; the synchronous SHM stores complete as soon - * as the warp retires them. + * Runs on ONE thread (the TMA launcher). Weight TMAs need no such gate + * (weights are static); issue them before this wait to keep DRAM busy. + */ +template +__device__ inline void moe_wait_expert_scales_published(const MoEGemmSpec* __restrict__ spec, + const MoE_SHM* __restrict__ shmem, + std::uint32_t expert_start, + std::uint32_t routed_count) { + constexpr uint32_t SCALE_COLS = Dims::N / MoECoreDims::DOWN_ACT_BLOCK_SIZE; + uint32_t* base = reinterpret_cast( + moe_act_scale_buf(const_cast*>(spec), shmem->scale_parity)); + bool pending = true; + while (pending) { + pending = false; + for (uint32_t r = 0; r < routed_count; ++r) { + for (uint32_t h = 0; h < SCALE_COLS; ++h) { + uint32_t* cell = base + (expert_start + r) * SCALE_COLS + h; + if (moe_scale_is_sentinel(atomicAdd(cell, 0u))) { + pending = true; + } + } + } + } + __threadfence(); +} + +/** + * @brief Per-expert weight-scale loader (down-projection). * - * @tparam Dims MoE dims. - * @tparam DestRows Must be 2 (WG0, WG1). - * @tparam DestCols Must be `W_DOWN_SCALE_COLS` (= N/128 for - * block-wise). - * @param expert_scales_down GM pointer to the full scale tensor. - * @param id Expert index. - * @param base_col First output col of this block's M stripe - * (multiple of 128). - * @param dest SHM slot `[2 row-blocks][W_DOWN_SCALE_COLS]` - * fp32. + * Loads the expert's fp32 weight scales for one 128-row M-atom into + * `dest[wg][col_block]` — one scale per (warpgroup, col-block along N). + * WG0 covers weight rows [base_col, +64), WG1 rows [base_col+64, +64); + * for a 128-aligned base_col both fall in the same 128-row scale block, + * but each is computed independently for generality. * - * @note Prefetch-warp only. Unlike the fp8 tile loaders, this function - * uses synchronous SHM stores (no `pipe`) because the payload is - * tiny (≤ 32 bytes for Qwen3.5-35B) and fits comfortably in a - * single warp-sized burst. + * Runs on prefetch warp 1 (warp 9) so it issues in parallel with the + * activation-scale loader on warp 8. Payload is tiny (≤ 32 B for the + * E256_N512_K2048 shape) — plain synchronous SHM stores. */ template __device__ inline void moe_load_down_wgmma_weight_scale_tile( const S_element* __restrict__ expert_scales_down, std::uint32_t id, std::uint32_t base_col, S_element (&dest)[DestRows][DestCols]) { - using CoreDims = MoECoreDims; static_assert(DestRows == 2, "down-proj weight-scale tile must have 2 row-blocks (WG0, WG1)"); - constexpr uint32_t COLS = DestCols; // W_DOWN_SCALE_COLS = N/128 (block-wise) + constexpr uint32_t COLS = DestCols; const unsigned thread = get_thread(); - const unsigned pw = get_prefetch_warp(); // 0..3 - - // WG0 covers weight rows [base_col .. base_col + 63] → row-block - // (base_col ) / 128 WG1 covers weight rows [base_col+64 .. base_col + - // 127] → row-block (base_col + 64 ) / 128 - // - // - // Run on prefetch warp 1 (= block warp 9). The matching activation - // scale loader (`moe_load_down_wgmma_act_scale_per_expert`) runs on - // prefetch warp 0 (= block warp 8) — both at the top of the - // per-expert loop — so the two scale loads issue in parallel on - // independent warps instead of serializing on warp 8 alone. + const unsigned pw = get_prefetch_warp(); + if (pw == 1 && thread < DestRows * COLS) { - const uint32_t wg = thread / COLS; // 0..1 - const uint32_t cb = thread % COLS; // col-block index in [0, COLS) + const uint32_t wg = thread / COLS; + const uint32_t cb = thread % COLS; const uint32_t weight_row = base_col + (wg == 0 ? 0u : 64u); const uint32_t rb = weight_row / 128; dest[wg][cb] = expert_scales_down[id * Dims::DOWN_SCALE_ROWS * Dims::DOWN_SCALE_COLS + @@ -199,86 +167,64 @@ __device__ inline void moe_load_down_wgmma_weight_scale_tile( } } -} // namespace monomoe - -namespace monomoe { - -/////////////////////////////////////////////////////////////////////////////// -// -// moe_down_projection_BS8_allexperts_wgmma_tma -// -// TMA + WGMMA down-projection for BS <= 8. Both the fp8 expert-weight -// tile and the fp8 intermediate-activation tile are loaded via -// `cp.async.bulk.tensor.2d` with `CU_TENSOR_MAP_SWIZZLE_128B`, issued by -// a single TMA launcher thread (warp 8, lane 0). Completion of each -// tile is signalled via SHM mbarriers (`bar_w[2]`, `bar_a[2]` reused -// from Phase 3); consumer warps wait via `mbarrier.try_wait.parity`. -// -// Descriptors are built host-side in the torch binding wrapper and -// passed to the top-level kernel as `__grid_constant__ CUtensorMap -// const` parameters. At this device-side helper boundary they appear -// as `CUtensorMap const&` — the `__grid_constant__` qualifier only -// applies at the kernel-function boundary. -// +/** + * @brief TMA + WGMMA down-projection for BS <= 8. + * + * See docs/design_docs/monomoe_kernel.md "Phase 4 — down-projection". Both the fp8 weight tile and + * the fp8 intermediate-activation tile are loaded via bulk TMA (SWZ128), + * issued by the TMA launcher thread with completion on bar_w / bar_a + * (2-slot double buffers, re-initialized in this function's prologue). + * Each block accumulates its DOWN_COL_TILE output cols across its expert + * group's experts and atomicAdds the result into + * `spec->down_partial_out[BS][HIDDEN_STATES]`. + */ template -__device__ inline void moe_down_projection_BS8_allexperts_wgmma_tma( +__device__ inline void moe_down_projection_allexperts_wgmma_tma( const W_element* __restrict__ expert_weights_down, const S_element* __restrict__ expert_scales_down, std::uint32_t top_k, std::uint32_t batch_size, MoEGemmSpec* __restrict__ spec, MoE_SHM* __restrict__ shmem, CUtensorMap const& down_weights_desc, CUtensorMap const& down_activations_desc) { - static_assert(Dims::BS <= 8, "moe_down_projection_BS8_allexperts_wgmma_tma is BS<=8 only"); + static_assert(Dims::BS <= 8, "moe_down_projection_allexperts_wgmma_tma supports BS<=8."); using CoreDims = MoECoreDims; - // `expert_weights_down` is retained on the parameter list for signature - // parity with the `cp.async` reference but is not dereferenced on the - // TMA path — all weight GM reads go through `down_weights_desc`. + // All weight GM reads go through the TMA descriptor; top_k's rank scan + // was replaced by the routing-recorded down_rank table. Both stay on + // the signature for parity with the up-proj helpers. (void)expert_weights_down; + (void)top_k; - // ── Compile-time constants ──────────────────────────────────────────── - constexpr std::uint32_t K_TILE_W = CoreDims::K_TILE_WGMMA; // 32 - constexpr std::uint32_t K_STEP_DOWN = CoreDims::K_STEP_DOWN; // 128 or 256 - // K_STEP_WGMMA is the inner SWZ128 atom K-width (always 128). Each - // outer K-step packs K_SUBSTEPS_DOWN = K_STEP_DOWN / K_STEP_WGMMA - // 128-K sub-blocks; the WGMMA loop chains 4 m64n8k32 instructions - // per sub-block (lo+hi pair around the 128-K block-wise scale - // boundary). - constexpr std::uint32_t K_STEP_WGMMA = CoreDims::K_STEP_WGMMA; // 128 - constexpr std::uint32_t K_SUBSTEPS_DOWN = CoreDims::K_SUBSTEPS_DOWN; // 1/2 + constexpr std::uint32_t K_TILE_W = CoreDims::K_TILE_WGMMA; // 32 + constexpr std::uint32_t K_STEP_DOWN = CoreDims::K_STEP_DOWN; + constexpr std::uint32_t K_STEP_WGMMA = CoreDims::K_STEP_WGMMA; // 128 + constexpr std::uint32_t K_SUBSTEPS_DOWN = CoreDims::K_SUBSTEPS_DOWN; constexpr std::uint32_t WGMMAS_PER_SUBSTEP = K_STEP_WGMMA / K_TILE_W; // 4 - constexpr std::uint32_t K_TILES_DOWN = Dims::N / K_STEP_DOWN; // N/K - constexpr std::uint32_t DOWN_COL_TILE = CoreDims::DOWN_COL_TILE; // 128 or 256 - constexpr std::uint32_t DOWN_GRID = CoreDims::DOWN_GRID; // 16 or 8 - constexpr std::uint32_t DOWN_GROUPS = CoreDims::DOWN_GROUPS; // 8 or 16 - // Phase-2a layout alignment: one block owns `DOWN_COL_TILE` output - // cols. The two WGs (64 output cols each per WGMMA pass) together - // cover 128 cols per pass, so we need `HALVES = DOWN_COL_TILE / 128` - // sequential passes per K-step: - // * Pre Phase 2a (DOWN_COL_TILE=128): HALVES=1, pre-alignment 128-col - // behaviour. Weight tile in SHM is 128×128. - // * Post Phase 2a (DOWN_COL_TILE=256, BS8 TMA+WGMMA only): HALVES=2, - // weight tile in SHM is 256×128. Pass 0 covers output rows - // [base_col+0..base_col+127], pass 1 covers [+128..+255]. - constexpr std::uint32_t DOWN_COL_HALVES = DOWN_COL_TILE / 128u; // 1 or 2 + constexpr std::uint32_t K_TILES_DOWN = Dims::N / K_STEP_DOWN; + constexpr std::uint32_t DOWN_COL_TILE = CoreDims::DOWN_COL_TILE; + constexpr std::uint32_t DOWN_GRID = CoreDims::DOWN_GRID; + constexpr std::uint32_t DOWN_GROUPS = CoreDims::DOWN_GROUPS; + // The two WGs cover 128 output cols per WGMMA pass, so a block runs + // DOWN_COL_HALVES sequential passes per K-step to cover its + // DOWN_COL_TILE cols. + constexpr std::uint32_t DOWN_COL_HALVES = DOWN_COL_TILE / 128u; static_assert(DOWN_COL_TILE % 128u == 0, "DOWN_COL_TILE must be a multiple of 128 for the TMA+WGMMA " "down-projection (the weight tile is laid out as 128-row " "SWZ128 atoms on the M axis)."); - static_assert(DOWN_COL_HALVES <= 2u, - "DOWN_COL_TILE > 256 not supported by the Phase-2a " - "two-halves WGMMA structure."); - // Per-K-step weight TMA transfer size. Each 128×128 fp8 atom is - // 16384 B; an outer K-step issues - // `DOWN_COL_HALVES * K_SUBSTEPS_DOWN` - // such atoms total — `DOWN_COL_HALVES` along the M axis × the - // `K_SUBSTEPS_DOWN` 128-K sub-blocks that make up one outer step — - // stacking them along the M axis as contiguous 128-row SWZ128 atoms. + static_assert(DOWN_COL_HALVES <= 4u, + "DOWN_COL_TILE > 512 not supported by the WGMMA down-proj " + "M-axis structure."); + // Per-K-step TMA transfer sizes: one 128×128 fp8 weight atom is 16 KB, + // issued DOWN_COL_HALVES × K_SUBSTEPS_DOWN times per step; one + // activation atom is 1024 B (8 tok × 128 K), issued K_SUBSTEPS_DOWN + // times. Each bar is armed once with the total. constexpr std::uint32_t DOWN_W_TX_BYTES_PER_HALF = 16384u; constexpr std::uint32_t DOWN_W_TX_BYTES_TOTAL = - DOWN_W_TX_BYTES_PER_HALF * DOWN_COL_HALVES * K_SUBSTEPS_DOWN; // 16384 * halves * substeps - // Per-K-step activation TMA transfer size. Each 1024-B SWZ128 atom - // covers one 128-K sub-block; an outer K-step issues - // `K_SUBSTEPS_DOWN` such atoms back-to-back along the K axis. - constexpr std::uint32_t DOWN_A_TX_BYTES_TOTAL = 1024u * K_SUBSTEPS_DOWN; + DOWN_W_TX_BYTES_PER_HALF * DOWN_COL_HALVES * K_SUBSTEPS_DOWN; + // Activation atom bytes scale with T_TILE (8 tok × 128 K = 1024 B on + // the BS8 path). + constexpr std::uint32_t DOWN_A_TX_BYTES_TOTAL = + CoreDims::T_TILE * MoE_SHM::TinyDataWGMMA_TMA::FP8_ACT_NUM_CHUNKS * + MoE_SHM::TinyDataWGMMA_TMA::FP8_ACT_K_CHUNK * K_SUBSTEPS_DOWN; constexpr std::uint32_t W_DOWN_SCALE_COLS = MoE_SHM::TinyDataWGMMA_TMA::W_DOWN_SCALE_COLS; static_assert(Dims::N % K_STEP_DOWN == 0, "Dims::N must be a multiple of K_STEP_DOWN"); @@ -286,133 +232,76 @@ __device__ inline void moe_down_projection_BS8_allexperts_wgmma_tma( "K_STEP_DOWN must be a multiple of K_STEP_WGMMA (=128, the " "SWZ128 atom K-width)"); - // A descriptor strides for the 128×128 fp8 weight tile under - // SWIZZLE_128B. The TMA hardware applies the 8-row × 128-byte - // core-matrix XOR swizzle at write time, so each 1024-B atom holds - // one 8-row M-block. CUTLASS Major::K B128 layout: - // LBO = 16 B (one K-core-matrix within the 1024-B atom) - // SBO = 1024 B (next M-block atom) - // swizzle_mode = 1 - // The Python pre-interleave is NOT applied — the raw `[E, K, N]` - // row-major fp8 weight tensor is fed to the TMA, and the swizzle - // hardware produces the canonical layout in SHM. + // A operand (weights): SWZ128 canonical Major::K layout produced by the + // TMA from the RAW row-major [E, K, N] tensor (no pre-interleave). constexpr std::uint64_t A_LBO = 16ULL; constexpr std::uint64_t A_SBO = 1024ULL; constexpr std::uint32_t A_SWIZZLE = 1u; - // B descriptor strides for the 8-token × 128-K fp8 activation tile - // under SWIZZLE_128B (token-major Major::K B128 canonical layout). - // The TMA hardware applies the 8-row × 128-byte XOR at write time: - // logical byte(tok, kc, ki) = tok * 128 + kc * 16 + ki - // SHM byte = logical byte XOR swizzle(tok bits) - // CUTLASS strides for this layout: - // LBO = 16 B (stride between 16-B K-chunks along K inside a row) - // SBO = 128 B (stride between 8-row atoms; unused here, N=8 → 1 atom) - // swizzle = 1 (SWZ128) + // B operand (activations): a single 8-token × 128-K SWZ128 atom. + // BS8 (m64n8k32) has a single atom so SBO is unused; the historical + // 128 B value is preserved to keep BS8 SASS byte-identical. constexpr std::uint64_t B_LBO = 16ULL; constexpr std::uint64_t B_SBO = 128ULL; constexpr std::uint32_t B_SWIZZLE = 1u; - // ── Warp / lane identity ────────────────────────────────────────────── const unsigned thread_in_block = threadIdx.x; - const unsigned warp = thread_in_block / 32; // 0..11 - const unsigned lane = thread_in_block & 31; // 0..31 + const unsigned warp = thread_in_block / 32; + const unsigned lane = thread_in_block & 31; const bool is_wg1 = (warp >= 4 && warp < 8); const bool is_calc = (warp < 8); - const unsigned warp_in_wg = warp & 3; // 0..3 within each WG + const unsigned warp_in_wg = warp & 3; const unsigned my_wg = is_wg1 ? 1u : 0u; - // TMA path uses the `tiny_wgmma_tma` union variant (byte-identical to - // `tiny_wgmma` plus 32 B of mbarriers + the reorg tables at the tail). auto* shm = &shmem->tiny_wgmma_tma; - // ── Grid-to-(expert-group, output-col-tile) mapping ─────────────────── + // Grid-to-(expert-group, output-col-tile) mapping. const std::uint32_t down_group = blockIdx.x / DOWN_GRID; const std::uint32_t down_block_idx = blockIdx.x % DOWN_GRID; const std::uint32_t base_col = down_block_idx * DOWN_COL_TILE; - // ── Per-thread fp32 accumulators ────────────────────────────────────── - // One m64n8k32 WGMMA holds 4 fp32 accumulators per thread (d0/d1/d2/d3). - // The down-projection's inner K chain stacks 4 WGMMAs per K-step into a - // "lo" chunk (K[0..63], 2 WGMMAs) and "hi" chunk (K[64..127], 2 WGMMAs). - // Phase-2a generalizes this to `DOWN_COL_HALVES` parallel halves along - // the M axis, so we hold `4 * HALVES` final accumulators per thread: - // * chunk_d_lo[h][0..3] / chunk_d_hi[h][0..3] — per-half per-K-chunk - // scratch, reset each - // K-step. - // * final_d[h][0..3] — per-half per-expert - // K-loop accumulator - // (scaled by ws·as). + // Per-thread accumulators: per M-half, the 4-WGMMA K-chain splits each + // 128-K substep into a "lo" chunk (K[0..63]) and "hi" chunk (K[64..127]) + // so the two 64-K activation-scale halves can be applied separately. float chunk_d_lo[DOWN_COL_HALVES][4] = {{0.f}}; float chunk_d_hi[DOWN_COL_HALVES][4] = {{0.f}}; float final_d[DOWN_COL_HALVES][4] = {{0.f}}; - // ── Zero out_accum + Phase-4 mbarrier (re-)initialization ──────────── - // - // Two independent SHM publishes happen here, merged behind a single - // block-wide sync: - // - // (1) Zero per-block SHM `out_accum[BS][DOWN_COL_TILE]`. `out_accum` - // is not read until the per-expert accumulate loop below, which - // follows several additional `__syncthreads()` (priming drain + - // per-K-iter syncs). A single trailing sync here is sufficient. - // - // (2) Re-initialize the 4 TMA mbarriers. The Phase-3→4 - // `grid.sync()` guarantees the barriers are idle at entry; we - // reset them to `arrival_count = 1` on the launcher thread and - // publish with `fence.mbarrier_init.release.cluster`. They are - // not armed or waited on until inside the expert loop, strictly - // after this sync. - // - // Both targets (`out_accum`, `bar_w/bar_a`) are disjoint SHM regions - // so the two operations race-freely run in parallel; only one sync is - // needed to publish both. - // - // The `out_accum` zero-fill is unconditional — its cost is negligible - // (1 KB per block with 384 threads) and keeping it well-defined - // simplifies reasoning under either profile flag. The mbarrier inits - // are also unconditional: they cost only 4 SHM stores + 1 fence and - // leave the barriers in a known-idle state. The K-loop - // waits/arms are themselves gated on SKIP_PREFETCH, so uninit'd - // barriers are never a concern. + // ── Prologue: zero out_accum + re-init the Phase-4 mbarriers ────────── + // The site-#2 barrier guarantees the barriers are idle at entry. The + // two targets are disjoint SHM, so one trailing sync publishes both + // (issued at the top of the first expert iteration below). for (unsigned idx = thread_in_block; idx < Dims::BS * DOWN_COL_TILE; idx += blockDim.x) { const unsigned tok = idx / DOWN_COL_TILE; const unsigned col = idx % DOWN_COL_TILE; shm->out_accum[tok][col] = 0.f; } + constexpr std::uint32_t DOWN_PIPE_DEPTH = CoreDims::DOWN_PIPE_DEPTH; if (is_tma_launcher_thread()) { - mbarrier_init(&shm->bar_w[0], 1u); - mbarrier_init(&shm->bar_w[1], 1u); - mbarrier_init(&shm->bar_a[0], 1u); - mbarrier_init(&shm->bar_a[1], 1u); +#pragma unroll + for (std::uint32_t i = 0; i < DOWN_PIPE_DEPTH; ++i) { + mbarrier_init(&shm->bar_w[i], 1u); + mbarrier_init(&shm->bar_a[i], 1u); + } fence_mbarrier_init_release_cluster(); } __syncthreads(); const std::uint32_t expert_count = shmem->expert_count; - // Per-slot mbarrier parity state. Hoisted OUT of the expert loop so - // it stays continuously synced with the bar_{w,a}[slot] hardware - // phase across expert transitions. Resetting to 0 every expert is - // only correct when each slot is visited an even number of times per - // expert (so the bar returns to phase 0); for K_STEP_DOWN=256 with - // K_TILES_DOWN=2 each slot is visited exactly once per expert and - // ends at phase 1, so a blind reset would deadlock the next - // expert's `try_wait_parity(0)` call. Keeping this state continuous - // works for ANY K_TILES_DOWN, and adds zero cost. - std::uint32_t parity_w[2] = {0u, 0u}; - std::uint32_t parity_a[2] = {0u, 0u}; - - // ── Per-expert loop (expert_start = down_group, stride = DOWN_GROUPS) ─ + // Parity state is hoisted OUT of the expert loop: for K_TILES_DOWN == + // DOWN_PIPE_DEPTH each slot is visited once per expert and ends at + // phase 1, so a blind per-expert reset to 0 would deadlock the next + // expert's wait. Keeping it continuous works for any K_TILES_DOWN. + std::uint32_t parity_w[DOWN_PIPE_DEPTH] = {}; + std::uint32_t parity_a[DOWN_PIPE_DEPTH] = {}; + + // ── Per-expert loop (start = down_group, stride = DOWN_GROUPS) ──────── for (std::uint32_t e = down_group; e < expert_count; e += DOWN_GROUPS) { const std::uint32_t id = shmem->experts[e].id; - // Per-expert (expert, token) reorganization state. These - // values are populated by `prepare_moe_topk_BS8` in Phase 1/2 and - // drive the bulk activation TMA's outer coordinate and row count. const std::uint32_t routed_count = static_cast(shm->expert_routed_count[id]); const std::uint32_t expert_start = static_cast(shm->expert_slot_start[id]); - // Reset per-expert `final_d` accumulator. #pragma unroll for (std::uint32_t h = 0; h < DOWN_COL_HALVES; ++h) { #pragma unroll @@ -421,229 +310,127 @@ __device__ inline void moe_down_projection_BS8_allexperts_wgmma_tma( } } - // ── Load weight scales + per-expert activation scales (parallel) ─── - // Both scale tensors are fixed across K-steps for this expert, so - // we load them once per expert at the top of the per-expert loop. - // - // Weight scales: warp 9 (RunPw=1, see helper for rationale). - // Loaded via plain SHM stores from the GM pointer; each `h` call - // covers a 128-row M-block × full K (= W_DOWN_SCALE_COLS=N/128 - // col-blocks). - // - // Activation scales: warp 8 (RunPw=0). Loaded as a per-expert - // tile of `T_TILE × (N/64)` fp32 (= 256 B for Qwen3.5). Hoisted - // out of the K-loop so the WGMMA scale-apply reads the full set - // from SHM with `a_down_scale[tok][s * K_SUBSTEPS_DOWN * 2 + 2 * - // kk + half]` indexing — no per-K-step reload. - // - // Both loaders run inside `if (is_prefetch_warp())`; their - // `RunPw` template arg routes the actual stores onto the correct - // single warp, so warps 8 and 9 issue in parallel on independent - // SM sub-schedulers. + // Load weight scales (warp 9) + per-expert activation scales (warp 8) + // in parallel; both are fixed across the expert's K-steps. if (is_prefetch_warp()) { #pragma unroll for (std::uint32_t h = 0; h < DOWN_COL_HALVES; ++h) { moe_load_down_wgmma_weight_scale_tile(expert_scales_down, id, base_col + h * 128u, shm->w_down_scale[h]); } - moe_load_down_wgmma_act_scale_per_expert(spec, shmem, id, shm->a_down_scale); } - // ── Priming: prefetch slot 0 (w + a + a_scale for K-step 0) ──────── - // - // First-iteration priming only. For e > down_group, the previous - // expert's last-K-iteration in-loop launcher already issued the - // INTER-EXPERT LOOKAHEAD TMAs into slot 0 (see the launcher's - // `else if (e + DOWN_GROUPS < expert_count)` branch below), so - // skip the weight + activation TMA arm/issue here — only the - // weight scales (cheap cp.async, no bar) and the activation - // scales (also cp.async, separate `pipe`) need fresh loads per - // expert. + // ── Priming: K-step 0 weight + activation TMAs ──────────────────── + // First expert only — for later experts the previous expert's + // last-K-step launcher already issued the inter-expert lookahead into + // slot 0 (see the launcher branch in the K-loop). // - // The fp8 weight and activation tiles land via - // `cp.async.bulk.tensor.2d` issued by the launcher thread, with - // completion signalled on `bar_w[0]` / `bar_a[0]`. The activation - // scale tile loads via cp.async through `pipe`. + // The weight descriptor's row box is pinned to 128 host-side (the TMA + // boxDim cap is 256 and DOWN_COL_TILE=384 exceeds it), so one 128-row + // TMA is issued per (kk-substep, h-half) atom, landing at SHM row + // (kk*DOWN_COL_HALVES + h)*128. All atoms retire into one bar_w arm. const bool need_first_expert_prime = (e == down_group); if (need_first_expert_prime && is_tma_launcher_thread()) { - // Weight tile for K-step 0: arm bar_w[0] with the TOTAL tx_bytes - // and issue ONE TMA per 128-K substep covering the full - // DOWN_COL_TILE M-rows. The descriptor's boxDim row dimension - // is set to DOWN_COL_TILE host-side (see - // `create_down_weight_tma_desc(... row_box=DOWN_COL_TILE)`), so - // each TMA delivers `DOWN_COL_TILE * 128` bytes at once - // (16 KB for DOWN_COL_TILE=128, 32 KB for DOWN_COL_TILE=256). - // The two 128-row sub-atoms inside a 256-row delivery still - // observe the SWZ128 byte layout, so the consumer-side WGMMA A - // descriptor (which addresses one 128-row sub-atom per WGMMA - // call) is unchanged. - // - // Per-K-substep destination row offset into `w_down_wgmma[slot]`: - // kk-th substep starts at row `kk * DOWN_COL_TILE`. - // All atoms retire into the same bar_w[0], so a single - // `mbarrier.try_wait.parity` on the compute side drains them all. - mbarrier_arrive_expect_tx(&shm->bar_w[0], - /*tx_bytes=*/DOWN_W_TX_BYTES_TOTAL); + // 2-deep: prime K-step 0 only (the in-loop launcher covers s+1). + // 4-deep: prime K-steps 0 AND 1 into ring slots 0,1 — the in-loop + // launcher then arms slot (s+2)&3 each iter, so it fills slots 2,3 + // at s=0,1 and cross-stitches the NEXT expert into slots 0,1 at the + // last two iters. + constexpr std::uint32_t PRIME_STEPS = (DOWN_PIPE_DEPTH == 4u) ? 2u : 1u; #pragma unroll - for (std::uint32_t kk = 0; kk < K_SUBSTEPS_DOWN; ++kk) { - W_element* dest_base = &shm->w_down_wgmma[0][kk * DOWN_COL_TILE][0]; - tma_load_down_wgmma_tile(down_weights_desc, /*expert_id=*/id, - /*K=*/Dims::HIDDEN_STATES, - /*base_col=*/base_col, - /*k_start=*/kk * K_STEP_WGMMA, - /*dest_smem_ptr=*/(void*)dest_base, - /*bar_smem_ptr=*/&shm->bar_w[0]); - } - - // Activation tile for K-step 0: only issue when routed_count > 0. - // One TMA per 128-K sub-block (each delivers a 1024-B SWZ128 - // atom into `a_down_wgmma[slot][kk]`). All atoms retire into - // `bar_a[0]`; the launcher arms it once with the total tx_bytes. - if (routed_count > 0u) { - mbarrier_arrive_expect_tx(&shm->bar_a[0], - /*tx_bytes=*/DOWN_A_TX_BYTES_TOTAL); + for (std::uint32_t ps = 0; ps < PRIME_STEPS; ++ps) { + const std::uint32_t prime_k = ps * K_STEP_DOWN; + mbarrier_arrive_expect_tx(&shm->bar_w[ps], + /*tx_bytes=*/DOWN_W_TX_BYTES_TOTAL); #pragma unroll for (std::uint32_t kk = 0; kk < K_SUBSTEPS_DOWN; ++kk) { - tma_load_down_wgmma_activation_bulk(down_activations_desc, - /*k_start=*/kk * K_STEP_WGMMA, - /*expert_slot_start=*/expert_start, - /*dest_smem_ptr=*/&shm->a_down_wgmma[0][kk][0][0][0], - /*bar_smem_ptr=*/&shm->bar_a[0]); +#pragma unroll + for (std::uint32_t h = 0; h < DOWN_COL_HALVES; ++h) { + W_element* dest_base = &shm->w_down_wgmma[ps][(kk * DOWN_COL_HALVES + h) * 128u][0]; + tma_load_down_wgmma_tile(down_weights_desc, /*expert_id=*/id, + /*K=*/Dims::HIDDEN_STATES, + /*base_col=*/base_col + h * 128u, + /*k_start=*/prime_k + kk * K_STEP_WGMMA, + /*dest_smem_ptr=*/(void*)dest_base, + /*bar_smem_ptr=*/&shm->bar_w[ps]); + } + } + + // Activation tile — only when tokens route to this expert. With + // routed_count == 0 nothing is armed; the WGMMA computes on + // garbage that the rank-filtered accumulate never reads (fp8 e4m3 + // has no NaN encoding, so garbage can't fault). + if (routed_count > 0u) { + mbarrier_arrive_expect_tx(&shm->bar_a[ps], + /*tx_bytes=*/DOWN_A_TX_BYTES_TOTAL); +#pragma unroll + for (std::uint32_t kk = 0; kk < K_SUBSTEPS_DOWN; ++kk) { + tma_load_down_wgmma_activation_bulk( + down_activations_desc, + /*k_start=*/prime_k + kk * K_STEP_WGMMA, + /*expert_slot_start=*/expert_start, + /*dest_smem_ptr=*/&shm->a_down_wgmma[ps][kk][0][0][0], + /*bar_smem_ptr=*/&shm->bar_a[ps]); + } } } } - // Activation-slot tail (rows [routed_count, T_TILE)) is left - // uninitialized. WGMMAs for ranks ≥ routed_count produce - // garbage in calc-thread accumulators that map to `down_out` - // columns the rank-filtered accumulate never reads: - // if (rank_u8 != 0xFFu) out_accum[tok][col] += down_out[col][rank_u8]; - // `rank_for_tok[tok]` only emits ranks in [0, routed_count) (or - // sentinel 0xFF), so the garbage columns are written but never - // read. fp8 e4m3 has no NaN encoding, so the WGMMA can't trip - // an exception on garbage input. - - // Activation scales for this expert were already loaded above - // (top-of-expert per-expert loader on warp 8). No per-K-step - // scale load is needed: the WGMMA scale-apply indexes the - // already-resident `a_down_scale[tok][global_half]` directly. - - // Publish the prologue's `out_accum` zero-fill + mbarrier inits and - // the top-of-expert weight + activation scale tiles across the - // block before the WGMMA consumers wait on bar_w[0] / bar_a[0]. + + // Publish the prologue zero-fill + mbarrier inits and this expert's + // scale tiles before the WGMMA consumers wait on the barriers. __syncthreads(); // ── Main K-loop ───────────────────────────────────────────────────── - // - // Both WEIGHT and ACTIVATION tiles are loaded via TMA (mbarrier - // wait). Activation scales for the WHOLE expert are pre-loaded - // at the top of the per-expert loop (see - // `moe_load_down_wgmma_act_scale_per_expert` above), so the - // K-loop's WGMMA scale-apply just indexes the already-resident - // `a_down_scale[tok][global_half]` directly — no per-K-step - // scale fetch. - // - // PIPELINED ACCUMULATE: at iter s=0 of every expert AFTER the - // first one, prefetch warps run the PREVIOUS expert's - // `out_accum += down_out[col][rank]` accumulate concurrently with - // calc warps' WGMMA + the launcher's intra-expert prefetch. This - // hides the per-expert epilogue accumulate behind useful WGMMA - // work (~1 µs/expert at BS=8) and uses the prefetch warps that - // were otherwise idle (TMA issue is serial on lane 0; the rest of - // warps 9..11 had nothing to do). Hazards: - // * `down_out` is single-buffered. It's written by expert e's - // end-of-K-loop epilogue and read by expert e+1's iter-0 - // deferred accumulate; the writeback `__syncthreads()` and - // the priming-block `__syncthreads()` (both at the start of - // each expert) make the data visible to iter 0. The next - // write to `down_out` (at end of expert e+1's K-loop) is - // ordered after the iter-0 sync drain, so the previous - // expert's accumulate is guaranteed to have completed. - // * `rank_for_tok` follows the same lifetime as `down_out` - // (computed at end of expert e, read at iter 0 of expert e+1). - // * The LAST expert's accumulate is performed AFTER the expert - // loop (one final pass before the GM writeback). + // Per step: calc warps wait bar_w/bar_a and run the WGMMA chain; the + // launcher concurrently prefetches step s+1 (or the next expert's + // step 0 at the last step); prefetch warps run the PREVIOUS expert's + // deferred accumulate, sliced across the first K_TILES_DOWN - 1 steps. const bool has_prev_expert = (e != down_group); + const std::uint32_t prev_id = has_prev_expert ? shmem->experts[e - DOWN_GROUPS].id : 0u; for (std::uint32_t s = 0; s < K_TILES_DOWN; ++s) { - const std::uint32_t read_slot = s & 1; + const std::uint32_t read_slot = s & (DOWN_PIPE_DEPTH - 1u); - // ── COMPUTE half: WGMMA + scale-apply || TMA prefetch step s+1 ── if (is_calc) { - // Wait for this step's weight tile to be fully in SHM. The - // launcher pre-armed bar_w[read_slot] with tx=16384 before - // issuing the 128x128 weight TMA (priming for s=0, previous - // compute-half for s>0). while (!mbarrier_try_wait_parity(&shm->bar_w[read_slot], parity_w[read_slot])) { } parity_w[read_slot] ^= 1; - // Wait for this step's activation tile if any tokens route to - // this expert. When routed_count == 0 the launcher did not - // arm bar_a[read_slot] and did not issue a TMA; the WGMMA - // reads garbage from the un-initialized SHM slot, but every - // thread's accumulator maps to a rank that the - // rank-filtered accumulate never reads (see safety argument - // at the priming block). No wait needed. if (routed_count > 0u) { while (!mbarrier_try_wait_parity(&shm->bar_a[read_slot], parity_a[read_slot])) { } parity_a[read_slot] ^= 1; } - // A descriptor bases per WG per (kk-substep, h-half). The - // weight tile is laid out as `K_SUBSTEPS_DOWN * DOWN_COL_HALVES` - // contiguous 128-row M-slabs (substep 0 occupies rows - // [0..DOWN_COL_TILE-1], substep 1 occupies rows - // [DOWN_COL_TILE..2*DOWN_COL_TILE-1], …). Within each slab, - // half 0 spans the first `128 * DOWN_COL_HALVES / 2` … see the - // priming-block comment for the row-offset formula. WG0 owns - // rows [0..63] of each (kk, h) atom and WG1 owns rows [64..127]. const void* a_slot_base = (const void*)&shm->w_down_wgmma[read_slot][0][0]; const std::uint32_t wg_offset_bytes = is_wg1 ? 8192u : 0u; - // Bytes between consecutive 128×128 atoms (K_STEP_WGMMA-K-wide, - // 128-rows-tall) in `w_down_wgmma`; identical to a single TMA - // payload size. constexpr std::uint32_t W_ATOM_BYTES = DOWN_W_TX_BYTES_PER_HALF; - // Per-WGMMA K-advancement: - // A: 2 * A_LBO = 32 B inside the 1024-B A atom. - // B: 2 * B_LBO = 32 B inside the 1024-B B atom (next 2 - // K-chunks of each token row). constexpr std::uint32_t A_K_STRIDE = 2u * A_LBO; constexpr std::uint32_t B_K_STRIDE = 2u * B_LBO; const void* b_slot_base = (const void*)&shm->a_down_wgmma[read_slot][0][0][0][0]; - // Bytes between consecutive 8 tok × 128 K SWZ128 activation - // atoms (one per K-substep) in `a_down_wgmma[slot]`. - constexpr std::uint32_t B_SUBSTEP_BYTES = 1024u; - - // Per-(kk, h) WGMMA passes. Each pass runs the same - // 4-chained-m64n8k32 structure as the legacy K_STEP_DOWN=128 - // kernel and accumulates into `chunk_d_lo[h]` / `chunk_d_hi[h]`, - // then applies the (ws, as) scales at the K=128 boundary and - // folds into `final_d[h]`. Per-expert outer accumulator - // semantics are unchanged — the substep merely adds another - // inner level that itself runs 4 chained WGMMAs + scale apply. + // Bytes per K-substep activation atom: T_TILE rows × 128 B/row + // (1024 B at BS<=8, 2048 B at BS=16). + constexpr std::uint32_t B_SUBSTEP_BYTES = CoreDims::T_TILE * 128u; + #pragma unroll for (std::uint32_t kk = 0; kk < K_SUBSTEPS_DOWN; ++kk) { - // A new `wgmma.fence` is required at the start of every - // group of dependent WGMMAs (one fence ↔ one - // commit-group/wait-group pair below). + // One fence per commit/wait pair; hoisting it out of the kk loop + // would merge the substeps into one WGMMA supergroup without the + // intermediate scale-apply ordering — incorrect. wgmma_fence(); - // Per-substep activation base: kk-th 1024-B SWZ128 atom. const void* b_kk_base = (const void*)((const char*)b_slot_base + kk * B_SUBSTEP_BYTES); #pragma unroll for (std::uint32_t h = 0; h < DOWN_COL_HALVES; ++h) { - // Weight-tile atom row offset for (kk, h): - // row_off = (kk * DOWN_COL_HALVES + h) * 128. - // SHM byte offset = row_off * 128 (since each row is the - // full 128-K SWZ128 line) = (kk * HALVES + h) * 16384. const std::uint32_t atom_off_bytes = (kk * DOWN_COL_HALVES + h) * W_ATOM_BYTES; const void* a_base = (const void*)((const char*)a_slot_base + atom_off_bytes + wg_offset_bytes); - // 4 chained WGMMAs into chunk_d_lo[h] (K[0..63], j = 0, 1). + // 2 chained WGMMAs into the lo chunk (K[0..63])... #pragma unroll for (std::uint32_t j = 0; j < 2; ++j) { const void* a_ptr = (const void*)((const char*)a_base + j * A_K_STRIDE); @@ -654,7 +441,7 @@ __device__ inline void moe_down_projection_BS8_allexperts_wgmma_tma( chunk_d_lo[h][2], chunk_d_lo[h][3]); } - // 4 chained WGMMAs into chunk_d_hi[h] (K[64..127], j = 2, 3). + // ...and 2 into the hi chunk (K[64..127]). #pragma unroll for (std::uint32_t j = 2; j < WGMMAS_PER_SUBSTEP; ++j) { const void* a_ptr = (const void*)((const char*)a_base + j * A_K_STRIDE); @@ -669,37 +456,23 @@ __device__ inline void moe_down_projection_BS8_allexperts_wgmma_tma( wgmma_commit_group(); wgmma_wait_group<0>(); - // ── Scale-apply at the K=128 boundary (per-substep, per-half) ─ - // Each (kk, h) uses its own weight-scale entry - // `w_down_scale[h][my_wg][ws_col]` (ws_col = global 128-K - // index along Dims::N) and its own per-token activation - // scale halves indexed at the (s, kk)-derived global 64-K - // half offset in the per-expert `a_down_scale[tok][...]`. + // ── Scale-apply at the K=128 boundary (per substep, per half) ─ + // The lo/hi chunks map to the activation block covering their + // global-K start; for DOWN_ACT_BLOCK_SIZE=64 hi = lo + 1, for + // 128 lo and hi share a block. const std::uint32_t tok_02 = (lane % 4) * 2; const std::uint32_t tok_13 = (lane % 4) * 2 + 1; - // Activation scales are now hoisted to a per-expert - // single-buffer `a_down_scale[global_half][tok]`. The global - // 64-K half index for outer step `s`, substep `kk`, half - // `half ∈ {0, 1}` is `s * K_SUBSTEPS_DOWN * 2 + kk * 2 + - // half` (= `s * (K_STEP_DOWN/64) + 2*kk + half`). - // - // Layout note: the legacy `[tok][global_half]` layout caused - // a 2-way bank conflict on these LDS sites because the row - // stride along `tok` was 32 B = 8 banks and lane groups - // {0,4} mapped to the same bank. The transpose to - // `[global_half][tok]` (matching `MoE_SHM::act_scale`) puts - // every (tok_02 ∈ {0,2,4,6}) lookup on a distinct bank - // within one 32-B row → conflict-free. - const std::uint32_t base_half = s * K_SUBSTEPS_DOWN * 2u + 2u * kk; - const float as_lo_02 = shm->a_down_scale[base_half + 0u][tok_02]; - const float as_hi_02 = shm->a_down_scale[base_half + 1u][tok_02]; - const float as_lo_13 = shm->a_down_scale[base_half + 0u][tok_13]; - const float as_hi_13 = shm->a_down_scale[base_half + 1u][tok_13]; - - // Global 128-K block index along Dims::N for this (s, kk): - // global_kblock = (s * K_STEP_DOWN + kk * K_STEP_WGMMA) / 128 - // = s * K_SUBSTEPS_DOWN + kk + constexpr std::uint32_t ACT_BLK = CoreDims::DOWN_ACT_BLOCK_SIZE; + const std::uint32_t global_k = (s * K_SUBSTEPS_DOWN + kk) * 128u; + const std::uint32_t block_lo = global_k / ACT_BLK; + const std::uint32_t block_hi = (global_k + 64u) / ACT_BLK; + const float as_lo_02 = shm->a_down_scale[block_lo][tok_02]; + const float as_hi_02 = shm->a_down_scale[block_hi][tok_02]; + const float as_lo_13 = shm->a_down_scale[block_lo][tok_13]; + const float as_hi_13 = shm->a_down_scale[block_hi][tok_13]; + + // Global 128-K block index along Dims::N for (s, kk). const std::uint32_t ws_col = (W_DOWN_SCALE_COLS > 1) ? (s * K_SUBSTEPS_DOWN + kk) : 0u; #pragma unroll @@ -715,57 +488,141 @@ __device__ inline void moe_down_projection_BS8_allexperts_wgmma_tma( } // end kk substep loop } - // Launcher runs IN PARALLEL with the WGMMA above. Two cases: - // - // (a) `s + 1 < K_TILES_DOWN` — intra-expert prefetch: arms the - // OTHER slot for the current expert's next K-step. - // (b) `s + 1 == K_TILES_DOWN` AND there is a next expert in - // this block's group — INTER-EXPERT LOOKAHEAD: arms the - // slot that's about to be freed (slot 0 for K_TILES_DOWN - // even, see static_assert below) and issues the next - // expert's K=0 weight + activation TMAs into it. This - // keeps DRAM busy during the current expert's writeback / - // accumulate phase, eliminating the GPU-quiet "blue gap" - // at expert transitions in the NCU timeline. - // - // The next-expert priming block at the top of the expert loop - // detects `e > down_group` and skips its TMA arm/issue when the - // lookahead has already armed bar_{w,a}[0] — only the (cheap) - // weight + activation scale cp.async loads still run. + // Launcher (in parallel with the WGMMAs above): + // (a) s+1 < K_TILES_DOWN — intra-expert prefetch of the next + // K-step into the other slot; + // (b) last step + next expert exists — INTER-EXPERT LOOKAHEAD: + // prefetch the next expert's K=0 tiles into the slot about to + // be freed, keeping DRAM busy through the writeback/accumulate + // phase. With K_TILES_DOWN even that slot is index 0 — the + // slot the next expert's s=0 wait reads, with parity already + // aligned via the hoisted parity state. static_assert(K_TILES_DOWN % 2u == 0u, - "Inter-expert lookahead requires K_TILES_DOWN to be " - "even so the freshly-freed slot at s=K_TILES_DOWN-1 " - "(== (s+1)&1 == 0) is the same slot the next expert's " - "s=0 wait reads. All currently instantiated Dims " - "variants satisfy this (Qwen3.5 N=512 with K_STEP_DOWN " - "in {128, 256} → K_TILES_DOWN in {4, 2}). If this " - "fires for a future shape, either disable the " - "lookahead branch or introduce a per-expert slot " - "offset."); + "Inter-expert lookahead requires K_TILES_DOWN to be even " + "so the slot freed at the last step is the slot the next " + "expert's s=0 wait reads. If this fires for a new shape, " + "either disable the lookahead branch or introduce a " + "per-expert slot offset."); if (is_tma_launcher_thread()) { - if (s + 1 < K_TILES_DOWN) { + if constexpr (DOWN_PIPE_DEPTH == 4u) { + // ── 4-deep rolling ring, arm distance 2 ───────────────────── + // At iter s arm ring slot (s+2)&3 for the tile its consumer + // reads 2 iters later, giving each weight TMA two compute + // windows to land. Two source cases: + // (A) intra-expert: s+2 < K_TILES_DOWN → CURRENT expert's + // tile s+2 at k=(s+2)*K_STEP_DOWN. + // (B) cross-expert: s+2 >= K_TILES_DOWN → NEXT expert's + // tile s+2-K_TILES_DOWN (0..1) into slot (s+2)&3, which + // equals the tile index (K_TILES_DOWN % 4 == 0 — + // asserted in MoECoreDims), i.e. exactly the slot the + // next expert's early waits read. + // (Arm distance 3 — stitching a THIRD next-expert tile across + // the boundary — was measured 2026-07-15 after the boundary- + // shrink change and was flat on BS16 and ~5% slower on the + // BS8 tunable path; the shrunken boundary no longer needs the + // extra byte coverage, and the deeper stitch adds launcher + // overhead. Keep distance 2.) + const std::uint32_t la_tile = s + 2u; + const std::uint32_t la_slot = la_tile & 3u; + if (la_tile < K_TILES_DOWN) { + // (A) intra-expert tile s+2 of the CURRENT expert. + const std::uint32_t nk = la_tile * K_STEP_DOWN; + mbarrier_arrive_expect_tx(&shm->bar_w[la_slot], + /*tx_bytes=*/DOWN_W_TX_BYTES_TOTAL); +#pragma unroll + for (std::uint32_t kk = 0; kk < K_SUBSTEPS_DOWN; ++kk) { +#pragma unroll + for (std::uint32_t h = 0; h < DOWN_COL_HALVES; ++h) { + W_element* dest_base = + &shm->w_down_wgmma[la_slot][(kk * DOWN_COL_HALVES + h) * 128u][0]; + tma_load_down_wgmma_tile(down_weights_desc, /*expert_id=*/id, + /*K=*/Dims::HIDDEN_STATES, + /*base_col=*/base_col + h * 128u, + /*k_start=*/nk + kk * K_STEP_WGMMA, + /*dest_smem_ptr=*/(void*)dest_base, + /*bar_smem_ptr=*/&shm->bar_w[la_slot]); + } + } + if (routed_count > 0u) { + mbarrier_arrive_expect_tx(&shm->bar_a[la_slot], + /*tx_bytes=*/DOWN_A_TX_BYTES_TOTAL); +#pragma unroll + for (std::uint32_t kk = 0; kk < K_SUBSTEPS_DOWN; ++kk) { + tma_load_down_wgmma_activation_bulk(down_activations_desc, + /*k_start=*/nk + kk * K_STEP_WGMMA, + /*expert_slot_start=*/expert_start, + /*dest_smem_ptr=*/ + &shm->a_down_wgmma[la_slot][kk][0][0][0], + /*bar_smem_ptr=*/&shm->bar_a[la_slot]); + } + } + } else if (e + DOWN_GROUPS < expert_count) { + // (B) cross-expert stitch: NEXT expert's tile 0 or 1. + const std::uint32_t next_e = e + DOWN_GROUPS; + const std::uint32_t next_id = shmem->experts[next_e].id; + const std::uint32_t next_routed_count = + static_cast(shm->expert_routed_count[next_id]); + const std::uint32_t next_expert_start = + static_cast(shm->expert_slot_start[next_id]); + const std::uint32_t next_tile = la_tile - K_TILES_DOWN; // 0..1 + const std::uint32_t nk = next_tile * K_STEP_DOWN; + mbarrier_arrive_expect_tx(&shm->bar_w[la_slot], + /*tx_bytes=*/DOWN_W_TX_BYTES_TOTAL); +#pragma unroll + for (std::uint32_t kk = 0; kk < K_SUBSTEPS_DOWN; ++kk) { +#pragma unroll + for (std::uint32_t h = 0; h < DOWN_COL_HALVES; ++h) { + W_element* dest_base = + &shm->w_down_wgmma[la_slot][(kk * DOWN_COL_HALVES + h) * 128u][0]; + tma_load_down_wgmma_tile(down_weights_desc, /*expert_id=*/next_id, + /*K=*/Dims::HIDDEN_STATES, + /*base_col=*/base_col + h * 128u, + /*k_start=*/nk + kk * K_STEP_WGMMA, + /*dest_smem_ptr=*/(void*)dest_base, + /*bar_smem_ptr=*/&shm->bar_w[la_slot]); + } + } + // Sentinel-gate + issue the next expert's activation tiles + // here. After the first successful poll (case B) the case-C + // poll returns immediately — the sentinel is monotone within + // a launch. + if (next_routed_count > 0u) { + moe_wait_expert_scales_published(spec, shmem, next_expert_start, + next_routed_count); + mbarrier_arrive_expect_tx(&shm->bar_a[la_slot], + /*tx_bytes=*/DOWN_A_TX_BYTES_TOTAL); +#pragma unroll + for (std::uint32_t kk = 0; kk < K_SUBSTEPS_DOWN; ++kk) { + tma_load_down_wgmma_activation_bulk(down_activations_desc, + /*k_start=*/nk + kk * K_STEP_WGMMA, + /*expert_slot_start=*/next_expert_start, + /*dest_smem_ptr=*/ + &shm->a_down_wgmma[la_slot][kk][0][0][0], + /*bar_smem_ptr=*/&shm->bar_a[la_slot]); + } + } + } + } else if (s + 1 < K_TILES_DOWN) { const std::uint32_t next_slot = (s + 1) & 1; const std::uint32_t next_k_start = (s + 1) * K_STEP_DOWN; - // Next weight tile — ONE TMA per 128-K substep (covers the - // full DOWN_COL_TILE M-rows), same structure as the priming - // block. Single bar_w arm with the TOTAL tx_bytes drains - // every atom in one wait on the compute side. mbarrier_arrive_expect_tx(&shm->bar_w[next_slot], /*tx_bytes=*/DOWN_W_TX_BYTES_TOTAL); #pragma unroll for (std::uint32_t kk = 0; kk < K_SUBSTEPS_DOWN; ++kk) { - W_element* dest_base = &shm->w_down_wgmma[next_slot][kk * DOWN_COL_TILE][0]; - tma_load_down_wgmma_tile(down_weights_desc, /*expert_id=*/id, - /*K=*/Dims::HIDDEN_STATES, - /*base_col=*/base_col, - /*k_start=*/next_k_start + kk * K_STEP_WGMMA, - /*dest_smem_ptr=*/(void*)dest_base, - /*bar_smem_ptr=*/&shm->bar_w[next_slot]); +#pragma unroll + for (std::uint32_t h = 0; h < DOWN_COL_HALVES; ++h) { + W_element* dest_base = + &shm->w_down_wgmma[next_slot][(kk * DOWN_COL_HALVES + h) * 128u][0]; + tma_load_down_wgmma_tile(down_weights_desc, /*expert_id=*/id, + /*K=*/Dims::HIDDEN_STATES, + /*base_col=*/base_col + h * 128u, + /*k_start=*/next_k_start + kk * K_STEP_WGMMA, + /*dest_smem_ptr=*/(void*)dest_base, + /*bar_smem_ptr=*/&shm->bar_w[next_slot]); + } } - // Next activation tile — only if any tokens route to this - // expert. K_SUBSTEPS_DOWN back-to-back 1024-B atoms. if (routed_count > 0u) { mbarrier_arrive_expect_tx(&shm->bar_a[next_slot], /*tx_bytes=*/DOWN_A_TX_BYTES_TOTAL); @@ -779,38 +636,40 @@ __device__ inline void moe_down_projection_BS8_allexperts_wgmma_tma( /*bar_smem_ptr=*/&shm->bar_a[next_slot]); } } - } else if (e + DOWN_GROUPS < expert_count) { - // ── INTER-EXPERT LOOKAHEAD ──────────────────────────────── - // - // Prefetch the NEXT expert's K=0 weight + activation tiles - // into the slot that's about to be freed. With - // K_TILES_DOWN even, that slot is index 0 — same slot the - // next expert's `read_slot = s & 1` lookup picks at s=0, - // so the next expert's K-loop starts on data already in - // SHM with the parity bookkeeping already aligned via the - // hoisted `parity_w[]` / `parity_a[]` state. + } else if (s + 1 >= K_TILES_DOWN && e + DOWN_GROUPS < expert_count) { const std::uint32_t lookahead_slot = (s + 1) & 1; // == 0 const std::uint32_t next_e = e + DOWN_GROUPS; const std::uint32_t next_id = shmem->experts[next_e].id; - const std::uint32_t next_routed_count = - static_cast(shm->expert_routed_count[next_id]); - const std::uint32_t next_expert_start = - static_cast(shm->expert_slot_start[next_id]); mbarrier_arrive_expect_tx(&shm->bar_w[lookahead_slot], /*tx_bytes=*/DOWN_W_TX_BYTES_TOTAL); #pragma unroll for (std::uint32_t kk = 0; kk < K_SUBSTEPS_DOWN; ++kk) { - W_element* dest_base = &shm->w_down_wgmma[lookahead_slot][kk * DOWN_COL_TILE][0]; - tma_load_down_wgmma_tile(down_weights_desc, /*expert_id=*/next_id, - /*K=*/Dims::HIDDEN_STATES, - /*base_col=*/base_col, - /*k_start=*/kk * K_STEP_WGMMA, - /*dest_smem_ptr=*/(void*)dest_base, - /*bar_smem_ptr=*/&shm->bar_w[lookahead_slot]); +#pragma unroll + for (std::uint32_t h = 0; h < DOWN_COL_HALVES; ++h) { + W_element* dest_base = + &shm->w_down_wgmma[lookahead_slot][(kk * DOWN_COL_HALVES + h) * 128u][0]; + tma_load_down_wgmma_tile(down_weights_desc, /*expert_id=*/next_id, + /*K=*/Dims::HIDDEN_STATES, + /*base_col=*/base_col + h * 128u, + /*k_start=*/kk * K_STEP_WGMMA, + /*dest_smem_ptr=*/(void*)dest_base, + /*bar_smem_ptr=*/&shm->bar_w[lookahead_slot]); + } } + // Sentinel-gate + issue the next expert's activation tile here. + // The next expert's fp8 payload may still be in flight from its + // up-group — confirm publication before the activation TMA reads + // it. (Weight TMAs above are static data and issue without the + // gate.) + const std::uint32_t next_routed_count = + static_cast(shm->expert_routed_count[next_id]); + const std::uint32_t next_expert_start = + static_cast(shm->expert_slot_start[next_id]); if (next_routed_count > 0u) { + moe_wait_expert_scales_published(spec, shmem, next_expert_start, + next_routed_count); mbarrier_arrive_expect_tx(&shm->bar_a[lookahead_slot], /*tx_bytes=*/DOWN_A_TX_BYTES_TOTAL); #pragma unroll @@ -825,62 +684,40 @@ __device__ inline void moe_down_projection_BS8_allexperts_wgmma_tma( } } } - // Activation-slot tail is left uninitialized; - // Activation scales are loaded once per expert (top of expert - // loop) — no per-K-step scale reload. Prefetch warps still - // run the PREVIOUS expert's deferred accumulate at iter 0 of - // every expert AFTER the first concurrently with calc warps' - // iter-0 WGMMA (see the K-loop block comment above for the - // lifetime/hazard argument). + + // ── Deferred accumulate of the PREVIOUS expert (prefetch warps) ── + // + // out_accum[tok][col] += down_out[col][rank] for the previous + // expert, sliced into K_TILES_DOWN - 1 disjoint (tok, col) ranges — + // one per K-step — so on many-K-step shapes the accumulate hides + // behind each step's WGMMA window instead of spilling past a single + // one. The LAST step carries no accumulate: its trailing + // __syncthreads() then cleanly separates the final down_out READ + // from this expert's epilogue WRITE of the same buffer (and keeps + // PF SHM traffic off the inter-expert lookahead step). + // + // Safety: down_out is stable across the whole K-loop (written only + // by the previous expert's epilogue, published by the expert-top + // sync); down_rank is routing-recorded and immutable in Phase 4; + // slices are disjoint so += never double-adds. if (is_prefetch_warp()) { - // Deferred accumulate of the PREVIOUS expert. Runs on prefetch - // warps only (warps 8..11, 128 threads), iterating over the - // (tok, col) plane. Calc warps run their WGMMAs in parallel. - // - // Distribute-across-K-steps (generic): the whole - // `batch_size * DOWN_COL_TILE` (tok, col) plane is split into - // `DEFER_ITERS_DOWN = K_TILES_DOWN - 1` contiguous flat-index - // chunks, one processed per K-loop iteration s in - // [0, DEFER_ITERS_DOWN). The LAST iteration (s == K_TILES_DOWN-1) - // is left free — it carries the launcher's inter-expert lookahead - // TMA (the `else if (e + DOWN_GROUPS < expert_count)` branch - // above). For the shipped Qwen3.5 shape K_TILES_DOWN=2, so - // DEFER_ITERS_DOWN=1 and this is byte-identical to the previous - // `s == 0` burst; for any other K_STEP_DOWN (e.g. 128 → - // K_TILES_DOWN=4) the epilogue spreads over the first - // K_TILES_DOWN-1 iterations instead of concentrating all of it - // into one, dropping the per-iteration `out_accum`/`down_out` - // SHM-traffic peak and overlapping each chunk with calc-warp - // WGMMA. - // - // Reads: - // * `shm->partial_result.down_out` — written by the - // previous expert's end-of-K-loop writeback, published by - // the expert-loop top __syncthreads. Overwritten only at - // THIS expert's end-of-K-loop (after all K_TILES_DOWN iters), - // so reads at iters [0, K_TILES_DOWN-1) all precede it. - // * `shm->rank_for_tok` — computed at the end of the - // previous expert (after its writeback, before the - // trailing __syncthreads), same lifetime as `down_out`. - // Writes: - // * `shm->out_accum[tok][col]` — `+=` only, no contention - // with calc warps (they don't touch out_accum during the - // K-loop). Each (tok, col) cell is independent, so - // splitting a token's columns across iterations is safe. - constexpr unsigned DEFER_ITERS_DOWN = K_TILES_DOWN - 1u; - if (has_prev_expert && s < DEFER_ITERS_DOWN) { + constexpr unsigned NUM_ACC_STEPS = (K_TILES_DOWN > 1u) ? (K_TILES_DOWN - 1u) : 1u; + if (has_prev_expert && s < NUM_ACC_STEPS) { + const unsigned acc_slice = s; const unsigned thread_in_pf = thread_in_block - CoreDims::CALC_WARP_COUNT * CoreDims::THREADS_PER_WARP; constexpr unsigned PF_THREADS = CoreDims::PREFETCH_WARP_COUNT * CoreDims::THREADS_PER_WARP; + const uint8_t* prev_rank = shm->down_rank[prev_id]; + // Slice s covers [floor(s*total/N), floor((s+1)*total/N)): + // adjacent, disjoint, covers [0, total) for any runtime total. const unsigned total = batch_size * DOWN_COL_TILE; - const unsigned flat_lo = s * total / DEFER_ITERS_DOWN; - const unsigned flat_hi = (s + 1u) * total / DEFER_ITERS_DOWN; - for (unsigned tok_col = flat_lo + thread_in_pf; tok_col < flat_hi; - tok_col += PF_THREADS) { + const unsigned start = (acc_slice * total) / NUM_ACC_STEPS; + const unsigned end = ((acc_slice + 1u) * total) / NUM_ACC_STEPS; + for (unsigned tok_col = start + thread_in_pf; tok_col < end; tok_col += PF_THREADS) { const unsigned tok = tok_col / DOWN_COL_TILE; const unsigned col = tok_col % DOWN_COL_TILE; - const uint8_t rank_u8 = shm->rank_for_tok[tok]; + const uint8_t rank_u8 = prev_rank[tok]; if (rank_u8 != 0xFFu) { shm->out_accum[tok][col] += shm->partial_result.down_out[col][rank_u8]; } @@ -888,22 +725,13 @@ __device__ inline void moe_down_projection_BS8_allexperts_wgmma_tma( } } - // Align all warps before the next iteration's WGMMA reads the - // new slot. Activation scales were hoisted out of the K-loop - // (see top-of-expert per-expert loader), so no pipe drain is - // needed here — only the cross-warp `__syncthreads()`. + // Align all warps before the next step's WGMMA reads the new slot. __syncthreads(); } // end K-loop - // ── End-of-expert: write final_d → partial_result.down_out[DCT][8] ─ - // - // Each half `h` contributes to output cols - // `[base_col + h*128, base_col + h*128 + 127]`, which map to - // `down_out` rows `[h*128 + wg_row_offset + warp_in_wg*16 + lane/4]` - // (row_base) / `[row_base + 8]` for the d0..d3 halves. - // - // WG1 adds +64 to the row offset within its 128-row half because - // WG1 owns output cols [h*128+64 .. h*128+127] within that half. + // ── End-of-expert: final_d → down_out[DOWN_COL_TILE][8] ───────────── + // Half h covers output cols [base_col + h*128, +128); within a half, + // WG1 owns the upper 64 cols. if (is_calc) { const std::uint32_t wg_row_offset = is_wg1 ? 64u : 0u; const std::uint32_t col_base = (lane % 4) * 2; @@ -917,64 +745,29 @@ __device__ inline void moe_down_projection_BS8_allexperts_wgmma_tma( } } - // ── Stage rank_for_tok for the current expert ──────────────────── - // - // Derive each token's intra-expert slot rank from the routing-time - // inverse map `expert_tok_krank[id][tok]` (built once in - // `prepare_moe_topk_BS8`) instead of re-scanning `topk_ids_flat` - // per expert. A valid `k` gives the global slot - // `sorted_slot[tok*top_k + k]`; subtract `expert_start` for the - // intra-expert rank the accumulate loop indexes. Sentinel 0xFF - // means the token does not route through this expert. - // - // Still staged into the per-expert `[BS]` `rank_for_tok` array - // (rather than read straight from the routing table in the inner - // loop) because the (tok, col) accumulate reads it once per column - // per token — a hot `[BS]`-sized row keeps that a broadcast. - // - // 8 threads (one per token) fill it in parallel; the accumulate - // that consumes both `down_out` and `rank_for_tok` is DEFERRED to - // the next expert's prefetch-warp body (see the K-loop block - // comment above). For the LAST expert in a group, an - // unconditional accumulate runs after the expert loop. - if (thread_in_block < batch_size) { - const unsigned tok = thread_in_block; - uint8_t rank_val = 0xFFu; - const uint8_t k = shm->expert_tok_krank[id * Dims::BS + tok]; - if (k != 0xFFu) { - const std::uint32_t pair = tok * top_k + k; - rank_val = - static_cast(static_cast(shm->sorted_slot[pair]) - expert_start); - } - shm->rank_for_tok[tok] = rank_val; - } + // Publishes this expert's down_out to the next expert's deferred + // accumulate (staged path); also orders this expert's out_accum RMWs + // before the next expert's (different threads can target the same + // (tok, col) across experts). __syncthreads(); } // end expert loop // ── Final accumulate for the LAST expert in this block's group ──────── - // - // The pipelined deferred accumulate inside the K-loop covers experts - // [down_group, down_group + DOWN_GROUPS, …, expert_count - DOWN_GROUPS). - // The LAST expert visited (`e_last = down_group + ((expert_count - - // 1 - down_group) / DOWN_GROUPS) * DOWN_GROUPS`) has nothing to - // defer to, so we run one final accumulate here. All warps - // participate (now that the K-loop is done, the prefetch warps are - // free to help). - // - // The expert-loop's trailing __syncthreads() already published this - // block's `down_out` and `rank_for_tok`. No additional sync - // required before reading them. - // - // For blocks whose group has zero experts (expert_count <= - // down_group), `e_started` stays false and the accumulate is - // skipped — `down_out` was never written for this block. + // The deferred accumulate covers all but the last visited expert; drain + // it here with all warps (the K-loop is done, PF warps are free). The + // expert loop's trailing sync already published down_out. Blocks whose + // group had zero experts skip (down_out was never written). if (expert_count > down_group) { + const std::uint32_t e_last = + down_group + ((expert_count - 1u - down_group) / DOWN_GROUPS) * DOWN_GROUPS; + const std::uint32_t last_id = shmem->experts[e_last].id; + const uint8_t* last_rank = shm->down_rank[last_id]; for (unsigned tok_col = thread_in_block; tok_col < batch_size * DOWN_COL_TILE; tok_col += blockDim.x) { const unsigned tok = tok_col / DOWN_COL_TILE; const unsigned col = tok_col % DOWN_COL_TILE; - const uint8_t rank_u8 = shm->rank_for_tok[tok]; + const uint8_t rank_u8 = last_rank[tok]; if (rank_u8 != 0xFFu) { shm->out_accum[tok][col] += shm->partial_result.down_out[col][rank_u8]; } @@ -982,15 +775,10 @@ __device__ inline void moe_down_projection_BS8_allexperts_wgmma_tma( } __syncthreads(); - // ── After all experts in this group: atomicAdd out_accum → GM partial ─ - // Phase 5 then reads each cell ONCE and casts to bf16 — no 16-way - // sum. The colstripe barrier still gates Phase 5 since all 16 - // contributing blocks must finish their atomicAdds first. - // The buffer is zero-initialized at kernel entry (see - // `moe_kernel_topk` prologue), and the up-proj-completion barrier - // publishes that zero across all blocks before any Phase 4 - // atomicAdd fires. - float* gm_partial = spec->down_partial_out; // single-buffer view + // ── atomicAdd out_accum into the global single-buffer accumulator ───── + // Phase 5 reads each cell once (no cross-group reduction); the + // col-stripe barrier gates it on all contributing blocks finishing. + float* gm_partial = spec->down_partial_out; for (unsigned idx = thread_in_block; idx < batch_size * DOWN_COL_TILE; idx += blockDim.x) { const unsigned tok = idx / DOWN_COL_TILE; const unsigned col = idx % DOWN_COL_TILE; diff --git a/csrc/fused_moe/monomoe/src/moe_grid_barrier.h b/csrc/fused_moe/monomoe/src/moe_grid_barrier.h deleted file mode 100644 index 487f49b52c5..00000000000 --- a/csrc/fused_moe/monomoe/src/moe_grid_barrier.h +++ /dev/null @@ -1,179 +0,0 @@ -#pragma once -#ifndef MOE_GRID_BARRIER_H -#define MOE_GRID_BARRIER_H - -#ifndef INSIDE_MONOMOE_IMPLEMENTATION -#error Do not include this file directly. -#endif - -#include - -// Software grid / partial barriers for the MonoMoe kernel. -// -// Full protocol (seed + high-bit, ping-pong slots, fence discipline, -// self-maintaining reset) and the per-site arrival-set recipe live in -// docs/design_docs/monomoe_kernel.md §2. Deadlock-freedom rests on the co-residency invariant -// (docs/design_docs/monomoe_kernel.md §3). Comments here only flag the per-step intent. - -namespace monomoe { - -/** - * @brief Software grid-wide barrier (all `GRID_SIZE_STATIC` blocks), - * cooperative-groups-equivalent happens-before with a standard - * launch. Protocol: docs/design_docs/monomoe_kernel.md §2. - * - * @tparam GRID_SIZE_STATIC Compile-time block count - * (`Dims::KernelConfig::GRID_SIZE`); folds the - * seed value and degenerate gate. - * @param counters Two-slot ping-pong Counter_Pair (e.g. - * `&spec->grid_barrier.slot[0]`). Host - * zero-inits on first use; self-maintaining - * thereafter (docs/design_docs/monomoe_kernel.md §4). - * @param phase In/out phase counter; active slot is - * `phase & 1`. Init to 0 at kernel entry. - */ -template -__device__ __forceinline__ void grid_barrier(uint32_t* __restrict__ counters, uint32_t& phase) { - // Degenerate single-block grid: nothing to order; still bump phase. - if constexpr (GRID_SIZE_STATIC == 1) { - ++phase; - return; - } - - // Slot holds 0x80000000u (bit 31 set) once all N blocks contribute; - // partial counts stay in [SEED, 0x7FFFFFFFu]. N <= 132 ⇒ no wrap. - constexpr uint32_t SEED = 0x80000000u - (GRID_SIZE_STATIC - 1u); - - const uint32_t slot = phase & 1u; - uint32_t* c = counters + slot; - - __syncthreads(); // step 1: publish pre-barrier block writes - - if (threadIdx.x == 0) { - __threadfence(); // step 2: release pre-barrier global writes - - if (blockIdx.x == 0) { - // step 3: seed. Mask strips the previous call's leftover high-bit - // marker, folding back only real early arrivals (docs/design_docs/monomoe_kernel.md §2). - const uint32_t prior = atomicExch(c, SEED); - const uint32_t to_fold = prior & 0x7FFFFFFFu; - if (to_fold != 0u) { - atomicAdd(c, to_fold); - } - } else { - atomicAdd(c, 1u); // non-seed blocks arrive once - } - } - - // step 4: thread 0 alone spins; atomicAdd(c, 0u) is an uncached - // device-scope read (== ld.acquire.gpu on SM90). Others wait at the - // step-6 sync. Happens-before chain: docs/design_docs/monomoe_kernel.md §2. - if (threadIdx.x == 0) { - while ((atomicAdd(c, 0u) & 0x80000000u) == 0u) { - } - } - - __threadfence(); // step 5: post-barrier accesses happen-after bit-31 - __syncthreads(); // step 6: re-gather block, release non-spinners - ++phase; // step 7: next call targets the other slot -} - -/** - * @brief Software sub-grid (partial) barrier over a caller-specified - * arrival set. Underlies `expert_barrier` (site #2) and - * `colstripe_barrier` (site #3). Protocol, caller contract, and - * per-site seed/arrival recipe: docs/design_docs/monomoe_kernel.md §2. - * - * Identical to `grid_barrier` except the slot is per-id - * (`counter_region + id*2 + (phase&1)`) and the seed block / - * arrival_count are runtime args. `arrival_count` is runtime (not a - * template param) so the primitive isn't instantiated per site; every - * call site passes a compile-time constant so `SEED` and the degenerate - * gate still fold. - * - * @param counter_region Base of this region's Counter_Pair array - * (`expert_slot`/`colstripe_slot`). Host - * zero-inits on first use (docs/design_docs/monomoe_kernel.md §4). - * @param id Barrier id (expert group or col stripe). - * @param arrival_count Blocks arriving for this `id` - * (`UP_GRID` or `DOWN_GROUPS`). - * @param seed_thread_blockidx `blockIdx.x` of the seed block (lowest - * in the arrival set). - * @param phase In/out phase counter for this - * (region, id-at-call-site); active slot - * `phase & 1`. Init to 0 at kernel entry. - */ -__device__ __forceinline__ void partial_barrier(uint32_t* __restrict__ counter_region, uint32_t id, - uint32_t arrival_count, - uint32_t seed_thread_blockidx, uint32_t& phase) { - // Degenerate single-block arrival set: nothing to order; still bump - // phase. Folds away since arrival_count is constant per call site. - if (arrival_count == 1u) { - ++phase; - return; - } - - // Slot holds 0x80000000u once all arrival_count blocks contribute. - const uint32_t SEED = 0x80000000u - (arrival_count - 1u); - - // Per-id Counter_Pair; `id * 2` stride matches the [N_IDS][2] layout - // in `MoEGemmSpec::partial_barrier`. - const uint32_t slot = phase & 1u; - uint32_t* c = counter_region + id * 2u + slot; - - __syncthreads(); // step 1: publish pre-barrier block writes - - if (threadIdx.x == 0) { - __threadfence(); // step 2: release pre-barrier global writes - - if (blockIdx.x == seed_thread_blockidx) { - // step 3: seed (mask strips leftover high-bit marker; docs/design_docs/monomoe_kernel.md §2) - const uint32_t prior = atomicExch(c, SEED); - const uint32_t to_fold = prior & 0x7FFFFFFFu; - if (to_fold != 0u) { - atomicAdd(c, to_fold); - } - } else { - atomicAdd(c, 1u); // non-seed members arrive once - } - } - - // step 4: thread 0 alone spins on an uncached device-scope read. - if (threadIdx.x == 0) { - while ((atomicAdd(c, 0u) & 0x80000000u) == 0u) { - } - } - - __threadfence(); // step 5: post-barrier accesses happen-after bit-31 - __syncthreads(); // step 6: re-gather block, release non-spinners - ++phase; // step 7: next call targets the other slot -} - -/** - * @brief Phase 3→4 expert-local barrier (site #2). Thin `__forceinline__` - * alias for `partial_barrier` (zero runtime cost). Recipe: - * `id = up_group`, `arrival_count = UP_GRID`, - * `seed_blockidx = up_group * UP_GRID` (docs/design_docs/monomoe_kernel.md §2). - */ -__device__ __forceinline__ void expert_barrier(uint32_t* __restrict__ expert_counters, - uint32_t expert_id, uint32_t arrival_count, - uint32_t seed_thread_blockidx, uint32_t& phase) { - partial_barrier(expert_counters, expert_id, arrival_count, seed_thread_blockidx, phase); -} - -/** - * @brief Phase 4→5 col-stripe-local barrier (site #3). Thin - * `__forceinline__` alias for `partial_barrier` (zero runtime - * cost). Recipe: `id = blockIdx.x % DOWN_GRID`, - * `arrival_count = DOWN_GROUPS`, `seed_blockidx = id` (the - * Phase-5 writer is its own seed; docs/design_docs/monomoe_kernel.md §2). - */ -__device__ __forceinline__ void colstripe_barrier(uint32_t* __restrict__ colstripe_counters, - uint32_t col_stripe, uint32_t arrival_count, - uint32_t seed_thread_blockidx, uint32_t& phase) { - partial_barrier(colstripe_counters, col_stripe, arrival_count, seed_thread_blockidx, phase); -} - -} // namespace monomoe - -#endif // MOE_GRID_BARRIER_H diff --git a/csrc/fused_moe/monomoe/src/moe_interface.h b/csrc/fused_moe/monomoe/src/moe_interface.h index 9e063135db0..ee501092d8a 100644 --- a/csrc/fused_moe/monomoe/src/moe_interface.h +++ b/csrc/fused_moe/monomoe/src/moe_interface.h @@ -34,22 +34,18 @@ struct MoEDimensions { struct KernelConfig { static constexpr std::uint32_t GRID_SIZE = (2 * N) / 16; static constexpr std::uint32_t BLOCK_SIZE = 384; - // Defaults for the generic (non-WGMMA) path. Concrete shape variants - // (e.g. Dims_BS8_..._WGMMA_TMA) override these. K_STEP_* default to 128 - // (the SWZ128 atom K-width). - static constexpr bool USE_WGMMA = false; - static constexpr bool USE_TMA = false; - static constexpr std::uint32_t K_STEP_DOWN = 128; - static constexpr std::uint32_t K_STEP_UP = 128; }; }; -// The single BS8 shape variant: TMA + WGMMA, SWIZZLE_128B on both weight -// sides. Phase 3 (up-proj) uses the Hopper wgmma.mma_async fp8 path with a -// v1 dual-warpgroup K=128 streaming pipeline. Group geometry (UP_GRID, -// UP_GROUPS, DOWN_GRID, DOWN_GROUPS) and the TMA caller contracts live in -// docs/design_docs/monomoe_kernel.md §5/§6; per-tensor specifics are in the moe_tma.h factory docs. -struct Dims_BS8_E256_Qwen3_5_35B_BlockFP8_WGMMA_TMA { +// ── Single fixed-shape Dims (E=256, N=512, K=2048 block-wise FP8) ───────── +// The kernel is hard-specialized to one shape and one token cap (BS8: M <= 8). +// The KernelConfig knobs below are the shipped default (formerly config 0); +// the omitted DOWN_COL_TILE / UP_COL_HALVES / UP_W_SLOTS / DOWN_PIPE_DEPTH are +// derived by the SFINAE detectors in moe_internal.h (UP_COL_HALVES resolves to +// 1 for this coupled shape, DOWN_PIPE_DEPTH to 2), so this struct is +// byte-identical to the pre-reduction default kernel. Grid = 128 <= H200's +// 132 SMs (the co-residency invariant). +struct Dims_BS8_E256_N512_K2048_BlockFP8_WGMMA_TMA { static constexpr uint32_t HIDDEN_STATES = 2048; static constexpr uint32_t K = 2048; static constexpr uint32_t N = 512; @@ -84,6 +80,7 @@ struct Dims_BS8_E256_Qwen3_5_35B_BlockFP8_WGMMA_TMA { // cost of doubling the per-slot bf16/fp8 activation tile and the // per-slot weight tile in SHM (see the K-step note in moe_internal.h). static constexpr std::uint32_t K_STEP_UP = 256; + static constexpr bool USE_PAIR_LAYOUT = true; }; }; @@ -99,12 +96,25 @@ using AQ_element = __nv_fp8_e4m3; // activations after quantization using S_element = float; // scaling factors using R_element = __nv_bfloat16; // MoE output +/** + * @brief Returns the maximum amount of shared memory necessary to run + * moe_kernel_topk() + */ +constexpr size_t get_moe_max_shmem_size(); + +/** + * @brief Returns the maximum amount of global scratchpad memory to run + * moe_kernel_topk() + */ +constexpr size_t get_moe_max_scratchpad_size(); + /** * @brief W8A8 MoE kernel with configurable top-K routing, scoring function, * and renormalization. * - * Designed for Qwen3.5-30B-A3B FP8 (softmax scoring, top_k=8, 256 experts). - * Also supports block-wise (128×128) FP8 quantization for Qwen3.5-35B. + * Supports block-wise (128×128) FP8 quantization for the fixed + * E256_N512_K2048 shape (softmax scoring, top_k up to 8, 256 experts). See + * docs/design_docs/monomoe_kernel.md for the architecture. * * @param [in] activations_in Input activations. Shape: [M, K] * @param [in] token_count Number of active tokens diff --git a/csrc/fused_moe/monomoe/src/moe_internal.h b/csrc/fused_moe/monomoe/src/moe_internal.h index 1ff0228f5d8..f2511772329 100644 --- a/csrc/fused_moe/monomoe/src/moe_internal.h +++ b/csrc/fused_moe/monomoe/src/moe_internal.h @@ -9,122 +9,226 @@ #include "moe_interface.h" -// Full 32-lane warp mask for the `*_sync` warp intrinsics. Previously -// supplied by the vLLM tree's `cuda_utils.h`; defined here so the monomoe -// sources are self-contained under FlashInfer's JIT build. -#ifndef FULL_MASK -#define FULL_MASK 0xffffffffu -#endif - -// ── Default pipeline variants ─────────────────────────────────────────────── -// Two scheduling optimizations are enabled by default. Both are pure -// pipeline / data-movement reschedules — they do not change the kernel's -// numerical result (verified bit-identical against the non-variant path), -// only how work overlaps: -// -// MONO_PROFILE_BARW_4DEEP : up-proj weight TMA pipeline is 2-deep -// (4 mbarrier slots, lookahead `(s+2)&3`) -// instead of single-deep, hiding more of -// the cross-/intra-expert weight TMA -// latency behind compute. -// MONO_PROFILE_DEFER_UP_EPILOGUE: the up-proj SiLU+fp8-quant writeback is -// deferred onto the prefetch warps during -// the next expert's first K-loop iters, -// overlapping it with calc-warp WGMMA. -// -// Define MONO_PROFILE_NO_BARW_4DEEP / MONO_PROFILE_NO_DEFER_UP_EPILOGUE (e.g. -// via an nvcc -D flag) to fall back to the simpler single-deep / inline- -// epilogue paths, which are kept compiled-out below for A/B comparison. -#if !defined(MONO_PROFILE_BARW_4DEEP) && !defined(MONO_PROFILE_NO_BARW_4DEEP) -#define MONO_PROFILE_BARW_4DEEP -#endif -#if !defined(MONO_PROFILE_DEFER_UP_EPILOGUE) && !defined(MONO_PROFILE_NO_DEFER_UP_EPILOGUE) -#define MONO_PROFILE_DEFER_UP_EPILOGUE -#endif - namespace monomoe { -using T_element = float; //< Type of fp32 accumulators (partial results, out_accum) -using OpaqueElement = std::uint32_t; //< Auxiliary 32-bit type used to generate - // better assembly code in loads +using T_element = float; //< fp32 accumulators (partial results, out_accum) /** - * @brief Offsets into the @c token_indexes field - * - * This is an offset array. To find all the tokens that belong to expert @c id : - * - * for (int i = first_token; i < last_token; i++) { - * int token_index = token_indexes[i]; - * } + * @brief One active expert. Filled by prepare_moe_topk in ascending + * expert-id order; only the first `expert_count` entries are valid. */ struct ExpertRef { - std::uint16_t first_token; - std::uint16_t last_token; std::uint32_t id; }; -// ── KernelConfig accessors ─────────────────────────────────────────────── -// `KernelConfig` always carries USE_WGMMA / USE_TMA / K_STEP_DOWN / K_STEP_UP: -// the generic `MoEDimensions` provides defaults (false / false / 128 / 128) -// and concrete shape variants override them, so these are plain reads. -// -// K_STEP_{UP,DOWN} must be a multiple of 128 (the SWZ128 atom K-width) and a -// divisor of the reduction dim (HIDDEN_STATES / N respectively). Bumping a -// K-step to 256 halves the outer K-iteration count (amortizing launch / bar / -// sync overhead over more compute) at the cost of a larger per-slot SHM tile. +// ── KernelConfig opt-in detection ─────────────────────────────────────────── +// The tunable knobs are optional members of `Dims::KernelConfig`; each +// `xxx::value` helper reads the member when present and falls back to +// the historical default otherwise. See docs/design_docs/monomoe_kernel.md "Tunable configs". + +template +struct use_wgmma { + template + static constexpr auto test(int) -> decltype(D::KernelConfig::USE_WGMMA, bool()) { + return D::KernelConfig::USE_WGMMA; + } + template + static constexpr bool test(...) { + return false; + } + static constexpr bool value = test(0); +}; + +template +struct use_tma { + template + static constexpr auto test(int) -> decltype(D::KernelConfig::USE_TMA, bool()) { + return D::KernelConfig::USE_TMA; + } + template + static constexpr bool test(...) { + return false; + } + static constexpr bool value = test(0); +}; + +// Gate/up pair layout for the up-projection epilogue. Set by all shipped +// BS8 shapes; enables the register-resident combine + deferred writeback. +template +struct use_pair_layout { + template + static constexpr auto test(int) -> decltype(D::KernelConfig::USE_PAIR_LAYOUT, bool()) { + return D::KernelConfig::USE_PAIR_LAYOUT; + } + template + static constexpr bool test(...) { + return false; + } + static constexpr bool value = test(0); +}; + +// K_STEP_DOWN: K-width per outer down-proj K-step. Multiple of 128 (the +// SWZ128 atom width); must divide Dims::N. Larger steps amortize launcher +// and barrier-wait overhead over more compute at the cost of larger +// `w_down_wgmma` / `a_down_wgmma` slots. +template +struct down_k_step { + private: + template + static constexpr auto test(int) -> decltype((std::uint32_t)D::KernelConfig::K_STEP_DOWN) { + return (std::uint32_t)D::KernelConfig::K_STEP_DOWN; + } + template + static constexpr std::uint32_t test(...) { + return 128u; + } + + public: + static constexpr std::uint32_t value = test(0); +}; + +// DOWN_PIPE_DEPTH: down-proj weight/activation TMA ring depth (tunable via +// the config table's DPD column). Optional on the Dims tag; defaults to 2 +// (the classic double buffer — SHM layout and SASS byte-identical for every +// Dims that doesn't declare it). 4 +// selects the rolling ring: at iter s the launcher arms slot (s+2)&3, so a +// weight tile has two compute windows to land and the fetch stream runs +// through the per-expert epilogue/sync bubble. Must be a power of two so +// `s & (DOWN_PIPE_DEPTH - 1)` folds to a mask. template -inline constexpr bool use_wgmma_v = Dims::KernelConfig::USE_WGMMA; +struct down_pipe_depth { + private: + template + static constexpr auto test(int) -> decltype((std::uint32_t)D::KernelConfig::DOWN_PIPE_DEPTH) { + return (std::uint32_t)D::KernelConfig::DOWN_PIPE_DEPTH; + } + template + static constexpr std::uint32_t test(...) { + return 2u; + } + + public: + static constexpr std::uint32_t value = test(0); +}; + +// K_STEP_UP: K-width per outer up-proj K-step. Multiple of 128; must divide +// Dims::HIDDEN_STATES. Scales are still applied at every 128-K boundary +// (the block-wise FP8 quantization granularity). template -inline constexpr bool use_tma_v = Dims::KernelConfig::USE_TMA; +struct up_k_step { + private: + template + static constexpr auto test(int) -> decltype((std::uint32_t)D::KernelConfig::K_STEP_UP) { + return (std::uint32_t)D::KernelConfig::K_STEP_UP; + } + template + static constexpr std::uint32_t test(...) { + return 128u; + } + + public: + static constexpr std::uint32_t value = test(0); +}; + +// DOWN_COL_TILE: output cols owned per down-block. Multiple of 128; must +// divide HIDDEN_STATES. template -inline constexpr std::uint32_t down_k_step_v = Dims::KernelConfig::K_STEP_DOWN; +struct down_col_tile { + private: + template + static constexpr auto test(int) -> decltype((std::uint32_t)D::KernelConfig::DOWN_COL_TILE) { + return (std::uint32_t)D::KernelConfig::DOWN_COL_TILE; + } + template + static constexpr std::uint32_t test(...) { + return (use_tma::value && Dims::BS <= 8) ? 256u : 128u; + } + + public: + static constexpr std::uint32_t value = test(0); +}; + +// UP_W_SLOTS: number of physical bar_w / w_wgmma slots in the up-proj +// weight-TMA lookahead pipeline. The prefetch distance is derived: +// UP_ARM_DISTANCE = max(1, SLOTS - 2), which keeps a slot's re-arm strictly +// after its previous consumer wait (SLOTS >= ARM + 2). Default is the +// historical per-shape depth: 4 for single-atom shapes (UP_COL_HALVES == 1), +// 2 for two-atom shapes. +template +struct up_w_slots { + private: + template + static constexpr auto test(int) -> decltype((std::uint32_t)D::KernelConfig::UP_W_SLOTS) { + return (std::uint32_t)D::KernelConfig::UP_W_SLOTS; + } + template + static constexpr std::uint32_t test(...) { + return (((2u * D::N * down_col_tile::value) / (128u * D::HIDDEN_STATES) >= 2u)) ? 2u : 4u; + } + + public: + static constexpr std::uint32_t value = test(0); +}; + +// UP_COL_HALVES: stacked 128-row WGMMA M-atoms per up-block (1 or 2). +// +// When ABSENT, derived from the coupling identity that pins +// UP_GROUPS == DOWN_GROUPS (so the site-#2 expert barrier's producer set +// equals its consumer set): +// UP_COL_HALVES = (2*N * DOWN_COL_TILE) / (128 * HIDDEN_STATES), min 1. +// +// When PRESENT, taken verbatim and the up/down grids are DECOUPLED +// (UP_GROUPS need not equal DOWN_GROUPS); the sentinel Phase-3→4 handoff +// covers this case natively (consumers poll the published scales they +// read, so producer set != consumer set needs no special protocol). template -inline constexpr std::uint32_t up_k_step_v = Dims::KernelConfig::K_STEP_UP; +struct up_col_halves { + private: + template + static constexpr auto test(int) -> decltype((std::uint32_t)D::KernelConfig::UP_COL_HALVES) { + return (std::uint32_t)D::KernelConfig::UP_COL_HALVES; + } + template + static constexpr std::uint32_t test(...) { + return ((2u * D::N * down_col_tile::value) / (128u * D::HIDDEN_STATES) > 0u) + ? (2u * D::N * down_col_tile::value) / (128u * D::HIDDEN_STATES) + : 1u; + } + + public: + static constexpr std::uint32_t value = test(0); +}; /** - * @brief Scratchpad memory for use within the MonoMoe kernel. - * - * Place in global memory. + * @brief Global-memory scratchpad for the monokernel. * + * LAYOUT INVARIANT: the host-side TMA wrapper computes the device pointer to + * `temp_fp8` as `scratchpad_base + TEMP_FP8_OFFSET`, and the Python debug + * readers in test_monokernel_accuracy.py assume the head field order + * (activations, temp_fp8, temp_act_scale, down_partial_out). Never insert + * fields before `down_partial_out`; new fields go at the tail. */ template struct MoEGemmSpec { static constexpr uint32_t SPEC_MAX_TOPK = 8; - // Virtual batch size: each token may be routed to up to SPEC_MAX_TOPK - // experts, so the sorted temp buffer must hold BS * SPEC_MAX_TOPK rows. BS <= - // 8 now also uses BS * SPEC_MAX_TOPK rows because the split-phase design - // writes one row per (token, expert) pair into spec->temp_bf16. + // Virtual batch size: up to SPEC_MAX_TOPK routed rows per token, plus 8 + // rows of guard padding. static constexpr uint32_t TEMP_ROWS = Dims::BS * SPEC_MAX_TOPK + 8; + // The down-activation TMA descriptor's outer extent excludes the guard + // padding — the up-proj epilogue only writes rows [0, BS * SPEC_MAX_TOPK). static constexpr uint32_t TEMP_ROWS_TMA = Dims::BS * SPEC_MAX_TOPK; - AQ_element activations[Dims::BS][Dims::HIDDEN_STATES]; //< Quantized activations - - // Kept for struct layout stability — removing it would shift - // TEMP_FP8_OFFSET and break the down-activation TMA descriptor. - A_element temp_bf16[TEMP_ROWS * Dims::N]; + AQ_element activations[Dims::BS][Dims::HIDDEN_STATES]; - // ── WGMMA-path-only up-proj → down-proj scratchpad ─────────────────── - // Used when `use_wgmma_v == true`. The up-projection - // epilogue fuses per-64-col fp8 quantization into the SiLU writeback - // and stores the fp8 activations plus per-(virtual-row, up-block) - // fp32 scales into these buffers; the WGMMA down-projection consumes - // them directly (no bf16→fp8 re-quantization pass). - // - // Layouts: - // temp_fp8 [TEMP_ROWS][N] fp8 - // temp_act_scale [TEMP_ROWS][N / 64] fp32 - // one scale per (virtual_row, up_block_idx) - // - // For Qwen3.5-35B (BS=8, top_k=8, N=512): TEMP_ROWS = 72 - // temp_fp8 = 72 × 512 × 1 B = 36.0 KB - // temp_act_scale = 72 × 8 × 4 B = 2.25 KB - // - // These are separate from temp_bf16 (kept for the scalar path) so - // non-WGMMA builds are byte-identical. - static constexpr uint32_t DOWN_ACT_BLOCK_SIZE = 64; + // Phase 3 → Phase 4 handoff: fp8 SiLU output in expert-sorted rows (each + // expert's routed tokens occupy a contiguous slab — see sorted_slot), with + // one fp32 scale per (row, up-block) where an up-block covers + // DOWN_ACT_BLOCK_SIZE = UP_COL_HALVES * 64 intermediate features. + static constexpr uint32_t UP_COL_HALVES_LOCAL = up_col_halves::value; + static constexpr uint32_t DOWN_ACT_BLOCK_SIZE = (UP_COL_HALVES_LOCAL * 128u) / 2u; static_assert(Dims::N % DOWN_ACT_BLOCK_SIZE == 0, - "Dims::N must be a multiple of 64 for the WGMMA down-proj " - "per-64-col activation quantization scheme"); + "Dims::N must be a multiple of DOWN_ACT_BLOCK_SIZE for the " + "WGMMA down-proj per-block activation quantization scheme"); static_assert(Dims::HIDDEN_STATES % 128 == 0, "Dims::HIDDEN_STATES must be a multiple of 128 for the " "WGMMA down-proj 128-cols-per-block grid layout"); @@ -132,57 +236,121 @@ struct MoEGemmSpec { AQ_element temp_fp8[TEMP_ROWS * Dims::N]; float temp_act_scale[TEMP_ROWS * TEMP_ACT_SCALE_COLS]; - // Byte offset of `temp_fp8`, so the host can address it from the - // scratchpad base without reading the layout at runtime (docs/design_docs/monomoe_kernel.md §4). + // Byte offset of `temp_fp8`, exposed so the host TMA wrapper can address + // it without reading the struct layout at runtime. static constexpr size_t TEMP_FP8_OFFSET = offsetof(MoEGemmSpec, temp_fp8); - // Down-projection group layout (docs/design_docs/monomoe_kernel.md §6): DOWN_COL_TILE=256, - // DOWN_GRID=8, DOWN_GROUPS=16 for the BS8 TMA path. `DOWN_GROUPS == - // UP_GROUPS` is the prerequisite for the Site-#2 Expert_Barrier; the value - // is mirrored in MoECoreDims with a cross-checking static_assert. - static constexpr uint32_t DOWN_COL_TILE = (use_tma_v && Dims::BS <= 8) ? 256u : 128u; + // Mirrors of the MoECoreDims values (MoECoreDims is defined later in this + // file; static_asserts there cross-check the two). + static constexpr uint32_t DOWN_COL_TILE = down_col_tile::value; static constexpr uint32_t DOWN_GRID = Dims::HIDDEN_STATES / DOWN_COL_TILE; static constexpr uint32_t DOWN_GROUPS = DOWN_GRID == 0 ? 1 : Dims::KernelConfig::GRID_SIZE / DOWN_GRID; - // Single-buffer fp32 accumulator for the down-projection (docs/design_docs/monomoe_kernel.md §1). - // [BS][HIDDEN_STATES] = 64 KB for Qwen3.5. fp32 (not bf16) so the 16-way - // Phase-4 atomicAdd keeps precision; Phase 5 casts each cell once. Zeroed - // at kernel entry, fenced by the Site-#2/#3 barriers. + + // Phase-4 accumulator: every contributing block atomicAdds its fp32 + // partial sum here; Phase 5 reads each cell once and casts to bf16. + // Zeroed at kernel entry; the site-#2 barrier publishes the zero before + // any Phase-4 atomicAdd. fp32 so the multi-block atomicAdd preserves + // precision. float down_partial_out[Dims::BS * Dims::HIDDEN_STATES]; - // Per-token block-wise activation quantization scales. - // Block size = 128 along K dimension → K/128 scales per token. - // act_scale[tok][blk] = max(|x_tok[blk*128..(blk+1)*128-1]|) / 448 - static constexpr uint32_t ACT_BLOCK_SIZE = 128; - static constexpr uint32_t ACT_SCALE_BLOCKS = - (Dims::HIDDEN_STATES + ACT_BLOCK_SIZE - 1) / ACT_BLOCK_SIZE; - float act_scale[Dims::BS][ACT_SCALE_BLOCKS]; - - // Software barrier counters (docs/design_docs/monomoe_kernel.md §2), at the TAIL of the struct so - // TEMP_FP8_OFFSET is unaffected (docs/design_docs/monomoe_kernel.md §4). Counter_Pairs are - // ping-pong slots: `grid_barrier.slot[2]` (all blocks), - // `expert_slot[id][2]` (one per expert group, arrival UP_GRID), - // `colstripe_slot[id][2]` (one per col stripe, arrival DOWN_GROUPS). - // ~2 KB total — negligible. Uses the local `DOWN_GRID` (not - // `MoECoreDims::DOWN_GRID`, which is an incomplete forward ref here); - // the two match via a MoECoreDims static_assert. - struct { - uint32_t slot[2]; - } grid_barrier; - struct { - uint32_t expert_slot[Dims::NUM_EXPERTS][2]; - uint32_t colstripe_slot[DOWN_GRID][2]; - } partial_barrier; + // ── Sentinel-based Phase 3 → 4 handoff state (tail fields) ──────────── + // + // The site-#2 barrier is replaced by data-path readiness (see the + // site-#2 note in moe.cu and the up/down projection publish/poll + // sites): a `temp_act_scale` cell doubles as the readiness + // flag for its fp8 payload segment, with bit pattern 0x00000000 (+0.0f) + // as the "not yet published" sentinel. Published scales are clamped to + // >= FLT_MIN (positive normal) at the publish site, so 0.0 is never a + // valid value — even under flush-to-zero. Using 0.0 (not NaN) means + // the host-side `torch.zeros` scratchpad allocation establishes the + // sentinel invariant for EVERY scratchpad (one per layer) with no + // per-scratchpad host init. + // + // Reset discipline (double buffer + async reset): consumers must never + // observe a LEFTOVER scale from the previous launch, so the scale + // buffer ping-pongs per launch. Launch parity comes from + // `launch_flip[blockIdx.x]` — a per-block PRIVATE persistent counter + // each block increments exactly once per launch (no cross-block + // synchronization needed; all blocks agree because all count the same + // launches). Each launch writes/polls the parity-selected buffer and + // zero-refills the OTHER buffer for the next launch, off the critical + // path. + // + // `temp_act_scale_alt` lives at the TAIL (not next to `temp_act_scale`) + // to preserve the head-field layout invariant documented above. + float temp_act_scale_alt[TEMP_ROWS * TEMP_ACT_SCALE_COLS]; + uint32_t launch_flip[Dims::KernelConfig::GRID_SIZE]; + + // ── Phase 4 → 5 readiness flags (replaces the site-#3 barrier) ──────── + // + // `down_partial_out` is atomicAdd-accumulated, so its readiness cannot + // be encoded in the data (a partial sum looks like a complete one). + // Instead each contributing block bumps its col-stripe's arrival + // counter (fence + atomicAdd) after its Phase-4 adds; the stripe's + // single Phase-5 writer polls until the count reaches DOWN_GROUPS. + // Only the 8 Phase-5 writers ever wait — the other blocks publish and + // exit (the old colstripe_barrier made all 128 blocks spin). + // + // Same double-buffer parity reset as the scale sentinel: launch parity + // selects the active row; the prologue zero-refills the OTHER row for + // the next launch. torch.zeros allocation covers the first launch. + uint32_t down_ready[2][DOWN_GRID]; + + static constexpr size_t TEMP_ACT_SCALE_OFFSET = offsetof(MoEGemmSpec, temp_act_scale); + static constexpr size_t TEMP_ACT_SCALE_ALT_OFFSET = + offsetof(MoEGemmSpec, temp_act_scale_alt); + static constexpr size_t TEMP_ACT_SCALE_BYTES = sizeof(float) * TEMP_ROWS * TEMP_ACT_SCALE_COLS; }; -// Upper bound on the supported dimensions, used by the `static_assert` -// bounds-checks in `get_moe_shmem_size()`. -using Dims_Max = MoEDimensions<1024, 1024, 5120, 256>; +// ── Sentinel handoff helpers (Phase 3 → 4) ──────────────────────────────── + +// "Not yet published" test. The sentinel is exactly +0.0f (bit pattern +// 0x00000000); published scales are clamped to >= FLT_MIN so no valid +// publication can produce it. (-0.0f cannot occur either: the buffer is +// only ever zero-filled or published-to.) +__device__ __forceinline__ bool moe_scale_is_sentinel(uint32_t bits) { return bits == 0u; } + +// Parity-selected scale buffer for the CURRENT launch. +template +__device__ __forceinline__ float* moe_act_scale_buf(MoEGemmSpec* __restrict__ spec, + uint32_t parity) { + return parity ? spec->temp_act_scale_alt : spec->temp_act_scale; +} + +/** + * @brief Publish one (row, up-block) activation scale as payload + flag. + * + * Caller contract: every lane of the calling warp has already issued its + * fp8 payload stores for this (row, up-block) segment, and the call is + * warp-uniform. `__syncwarp()` joins the lanes, the fence releases the + * payload at device scope, and the `atomicExch` makes the flag store + * morally strong so a consumer's device-scope poll that observes a + * non-sentinel value is guaranteed to also observe the payload. + * + * The published value is clamped to >= FLT_MIN so a subnormal scale can + * never flush to 0.0 (the sentinel) and hang a consumer; a scale that + * tiny dequantizes to ~0 either way, so the clamp is numerically inert. + */ +template +__device__ __forceinline__ void moe_publish_act_scale(MoEGemmSpec* __restrict__ spec, + uint32_t parity, uint32_t row, + uint32_t up_block, float scale, + unsigned lane) { + __syncwarp(); + if (lane == 0) { + __threadfence(); + constexpr uint32_t SCALE_COLS = MoEGemmSpec::TEMP_ACT_SCALE_COLS; + atomicExch(&moe_act_scale_buf(spec, parity)[row * SCALE_COLS + up_block], + fmaxf(scale, __FLT_MIN__)); + } +} + +// Maximum supported dimensions. Sizes only the max-SHM / max-scratchpad +// bookkeeping (`get_moe_max_*`); never launched. +using Dims_Max = MoEDimensions<1024, 1024, 6144, 512>; -// ── Block-wise quantization detection (forward declaration) ────────────── -// These helpers are used in the MoE_SHM layout below and defined with full -// SFINAE semantics further down. Here we just need the compile-time bool, -// so we duplicate the minimal detection inline. +// Block-wise quantization detection for the SHM scale-tile sizing below. template struct shm_is_block_wise { template @@ -221,733 +389,335 @@ struct shm_down_scale_cols { static constexpr uint32_t value = Dims::DOWN_SCALE_COLS; }; -// ── WGMMA opt-in detection ─────────────────────────────────────────────── -// `Dims::KernelConfig::USE_WGMMA` is optional; default to false for all -// existing Dims variants so the current mma.sync path stays in use. -// Only the new Dims_BS8_..._WGMMA variant sets USE_WGMMA=true. -// -// NOTE: The primary definition lives near the top of this file (before -// `MoEGemmSpec`) so `MoEGemmSpec` can use `use_wgmma_v` -// to select the variant-dependent `DOWN_COL_TILE` for Phase 2a. The -// block comment below documents the same detection scheme for readers -// who land on the later usage sites first. - -// ── TMA opt-in detection ──────────────────────────────────────────────── -// `Dims::KernelConfig::USE_TMA` is optional; default to false for all -// existing Dims variants so the current cp.async WGMMA path stays in use. -// Only the new Dims_BS8_..._WGMMA_TMA variant sets USE_TMA=true. -// -// NOTE: The primary definition lives near the top of this file (before -// `MoEGemmSpec`) — see the comment on `use_wgmma` above. - /** - * @brief contains various constants used within the MonoMoe kernel. + * @brief Derived compile-time constants of the monokernel. */ template struct MoECoreDims { using MoEDims = Dims; - // GPU configuration. static constexpr std::uint32_t THREADS_PER_WARP = 32; static constexpr std::uint32_t TOTAL_WARP_COUNT = Dims::KernelConfig::BLOCK_SIZE / THREADS_PER_WARP; static constexpr std::uint32_t CALC_WARP_COUNT = 8; static constexpr std::uint32_t PREFETCH_WARP_COUNT = TOTAL_WARP_COUNT - CALC_WARP_COUNT; - // MMA 1 matrix tile dimensions. - static constexpr std::uint32_t A_TILE = 8; + // Legacy scalar-path row tile; only feeds W_UP_TILE_EFFECTIVE for + // non-WGMMA Dims (Dims_Max bookkeeping). static constexpr std::uint32_t W_UP_TILE = 16; - static constexpr std::uint32_t K_TILE = 32; - // ── WGMMA-only tile dimensions (v1 dual-WG K=128 streaming) ────────── - // Used by the WGMMA up-proj path (Phase 2-3 when USE_WGMMA=true). - // - // Layout of the 128-row weight tile per block: - // rows [0 .. 31] : WG0 gate rows [base .. base+31] - // rows [32 .. 63] : WG0 up rows [base+N .. base+N+31] - // rows [64 .. 95] : WG1 gate rows [base+32 .. base+63] - // rows [96 .. 127] : WG1 up rows [base+N+32 .. base+N+63] - // - // Per K-step each WG issues 4 chained wgmma.mma_async.m64n8k32, which - // together consume K=128. The weight tile is single-buffered; bf16 input - // and fp8 activation tiles are double-buffered. The streaming pipeline - // alternates between even half-stages (WGMMA + bf16 prefetch) and odd - // half-stages (quantize + weight prefetch). - // - // W_UP_TILE_WGMMA = 128 — M dim of the block's weight tile - // (64 rows per WG × 2 WGs) - // W_UP_COLS_WGMMA = 64 — output columns per block per K-step - // (W_UP_TILE_WGMMA / 2) - // K_TILE_WGMMA = 32 — K width of one m64n8k32 instruction - // (hardware-fixed for fp8) - // K_STEP_WGMMA = 128 — K consumed per outer K-step (=4 × K_TILE_WGMMA) - // K_TILES_WGMMA = K/K_STEP_WGMMA — outer K iterations per expert - // WGMMAS_PER_STEP = 4 — WGMMAs chained per WG per K-step - // UP_GRID_WGMMA = 2*N / W_UP_TILE_WGMMA — blocks per expert + // ── WGMMA tile geometry ─────────────────────────────────────────────── + // One 128-row weight tile per block per K-step, split across two + // warpgroups (WG0 rows [0..63], WG1 rows [64..127]). Each WG chains + // WGMMAS_PER_STEP m64n8k32 WGMMAs per 128-K substep. static constexpr std::uint32_t W_UP_TILE_WGMMA = 128; - static constexpr std::uint32_t W_UP_COLS_WGMMA = W_UP_TILE_WGMMA / 2; - static constexpr std::uint32_t K_TILE_WGMMA = 32; - static constexpr std::uint32_t K_STEP_WGMMA = 128; + static constexpr std::uint32_t K_TILE_WGMMA = 32; // K per fp8 WGMMA + static constexpr std::uint32_t K_STEP_WGMMA = 128; // SWZ128 atom K-width static constexpr std::uint32_t WGMMAS_PER_STEP = K_STEP_WGMMA / K_TILE_WGMMA; // 4 - static constexpr std::uint32_t K_TILES_WGMMA = Dims::HIDDEN_STATES / K_STEP_WGMMA; - static constexpr std::uint32_t UP_GRID_WGMMA = 2 * Dims::N / W_UP_TILE_WGMMA; static_assert(K_STEP_WGMMA % K_TILE_WGMMA == 0, "K_STEP_WGMMA must be a multiple of K_TILE_WGMMA"); - static_assert(!use_wgmma_v || Dims::HIDDEN_STATES % K_STEP_WGMMA == 0, + static_assert(!use_wgmma::value || Dims::HIDDEN_STATES % K_STEP_WGMMA == 0, "HIDDEN_STATES must be a multiple of 128 for the WGMMA path " "(one K-step consumes K=128)"); - static_assert(!use_wgmma_v || (2 * Dims::N) % W_UP_TILE_WGMMA == 0, + static_assert(!use_wgmma::value || (2 * Dims::N) % W_UP_TILE_WGMMA == 0, "2*N must be a multiple of 128 for the WGMMA path " "(one block produces 128 output rows per K-step)"); - // ── Down-proj outer K-step (Dims::KernelConfig::K_STEP_DOWN tunable) ─ - // K_STEP_DOWN is the K-width consumed per OUTER K-step of the down- - // projection K-loop; it's a multiple of K_STEP_WGMMA = 128 (the - // SWZ128 atom K-width). Defaults to 128 (= K_STEP_WGMMA) for full - // backward compatibility; setting `KernelConfig::K_STEP_DOWN = 256` - // doubles per-iter compute / data movement, halving the iter count. - // - // Each outer K-step runs `K_SUBSTEPS_DOWN = K_STEP_DOWN / K_STEP_WGMMA` - // inner 128-K sub-blocks; scales are applied at every 128-K boundary - // (matching the block-wise quantization granularity). - static constexpr std::uint32_t K_STEP_DOWN = down_k_step_v; + // ── Down-proj outer K-step (K_STEP_DOWN tunable) ────────────────────── + static constexpr std::uint32_t K_STEP_DOWN = down_k_step::value; static constexpr std::uint32_t K_SUBSTEPS_DOWN = K_STEP_DOWN / K_STEP_WGMMA; static_assert(K_STEP_DOWN >= K_STEP_WGMMA && K_STEP_DOWN % K_STEP_WGMMA == 0, "K_STEP_DOWN must be a positive multiple of K_STEP_WGMMA " "(=128, the SWZ128 atom K-width)."); - static_assert(!use_wgmma_v || Dims::N % K_STEP_DOWN == 0, + static_assert(!use_wgmma::value || Dims::N % K_STEP_DOWN == 0, "Dims::N must be a multiple of K_STEP_DOWN for the WGMMA " - "down-projection (one outer K-step consumes K_STEP_DOWN " - "K-elements)."); - - // ── Up-proj outer K-step (Dims::KernelConfig::K_STEP_UP tunable) ──── - // K_STEP_UP is the K-width consumed per OUTER K-step of the up- - // projection K-loop; multiple of K_STEP_WGMMA = 128 (the SWZ128 atom - // K-width and the per-128-K block-wise FP8 scale boundary). - // Defaults to 128 (= K_STEP_WGMMA) for full backward compatibility; - // setting `KernelConfig::K_STEP_UP = 256` halves the K-loop iter - // count and doubles per-iter QUANT/COMPUTE work. - // - // Each outer K-step runs `K_SUBSTEPS_UP = K_STEP_UP / K_STEP_WGMMA` - // inner 128-K sub-blocks; the QUANT half quantizes one 128-K bf16 - // input chunk per substep, and the COMPUTE half runs 4 chained - // m64n8k32 WGMMAs + scale-apply per substep. - static constexpr std::uint32_t K_STEP_UP = up_k_step_v; + "down-projection."); + + // ── Down-proj TMA pipeline depth (DOWN_PIPE_DEPTH tunable) ──────────── + // 2 = classic double buffer (default); 4 = rolling ring with 2 K-steps + // of lookahead (arm slot (s+2)&3 at iter s). See the down_pipe_depth + // detector for the opt-in mechanics. + static constexpr std::uint32_t DOWN_PIPE_DEPTH = down_pipe_depth::value; + static_assert(DOWN_PIPE_DEPTH == 2u || DOWN_PIPE_DEPTH == 4u, + "DOWN_PIPE_DEPTH must be 2 (double buffer) or 4 (rolling " + "ring); other depths have no launcher implementation."); + static_assert(DOWN_PIPE_DEPTH == 2u || (Dims::N / K_STEP_DOWN) % DOWN_PIPE_DEPTH == 0u, + "DOWN_PIPE_DEPTH == 4 requires K_TILES_DOWN (= N / " + "K_STEP_DOWN) to be a multiple of 4 so the cross-expert " + "stitch at iters K_TILES-2 / K_TILES-1 lands the next " + "expert's tiles 0,1 on ring slots 0,1."); + + // ── Up-proj outer K-step (K_STEP_UP tunable) ────────────────────────── + static constexpr std::uint32_t K_STEP_UP = up_k_step::value; static constexpr std::uint32_t K_SUBSTEPS_UP = K_STEP_UP / K_STEP_WGMMA; static_assert(K_STEP_UP >= K_STEP_WGMMA && K_STEP_UP % K_STEP_WGMMA == 0, "K_STEP_UP must be a positive multiple of K_STEP_WGMMA " "(=128, the SWZ128 atom K-width)."); - static_assert(!use_wgmma_v || Dims::HIDDEN_STATES % K_STEP_UP == 0, + static_assert(!use_wgmma::value || Dims::HIDDEN_STATES % K_STEP_UP == 0, "Dims::HIDDEN_STATES must be a multiple of K_STEP_UP for " - "the WGMMA up-projection (one outer K-step consumes " - "K_STEP_UP K-elements of the reduction dim)."); - // Up-proj outer K-loop iteration count (replaces K_TILES_WGMMA in - // call sites that should follow the K_STEP_UP setting). + "the WGMMA up-projection."); static constexpr std::uint32_t K_TILES_UP = Dims::HIDDEN_STATES / K_STEP_UP; - // Effective M (row-tile) size of one block's up-proj work — 64 for the - // WGMMA path, 16 for the scalar path. Used to compute UP_GRID = 2*N/M. + // ── Up-proj weight-TMA lookahead (UP_W_SLOTS tunable) ───────────────── + // The launcher arms slot (s + UP_ARM_DISTANCE) % UP_W_SLOTS for logical + // outer-K iter s + A; the consumer waits slot s % UP_W_SLOTS. See the + // `up_w_slots` detector for the arm-distance derivation. + static constexpr std::uint32_t UP_W_SLOTS = up_w_slots::value; + static constexpr std::uint32_t UP_ARM_DISTANCE = (UP_W_SLOTS > 2u) ? (UP_W_SLOTS - 2u) : 1u; + static_assert(!use_wgmma::value || UP_W_SLOTS >= 2u, + "UP_W_SLOTS must be >= 2 (the up-proj weight pipeline needs " + "at least a ping-pong double buffer)."); + static_assert(!use_wgmma::value || (UP_W_SLOTS & (UP_W_SLOTS - 1u)) == 0u, + "UP_W_SLOTS must be a power of two so the slot index can use " + "a cheap `s & (UP_W_SLOTS-1)` mask."); + static_assert(!use_wgmma::value || K_TILES_UP % UP_W_SLOTS == 0, + "K_TILES_UP must be a multiple of UP_W_SLOTS so the " + "cross-expert weight-TMA stitch lands the next expert's " + "iters [0, UP_ARM_DISTANCE) on slots [0, UP_ARM_DISTANCE), " + "keeping per-slot arm/wait parity balanced across experts."); + static_assert(!use_wgmma::value || K_TILES_UP >= UP_W_SLOTS, + "K_TILES_UP must be >= UP_W_SLOTS so the pre-loop can prime " + "UP_ARM_DISTANCE slots without wrapping past the K-loop."); + + // ── Up-proj col-halves (M-axis 128-row atoms per block) ─────────────── + // 1 = interleaved single-TMA layout; 2 = raw two-TMA layout (also the + // decoupled up/down-grid shapes). See the `up_col_halves` detector. + static constexpr std::uint32_t UP_COL_HALVES = up_col_halves::value; + static_assert(!use_wgmma::value || UP_COL_HALVES <= 2u, + "UP_COL_HALVES > 2 not supported by the up-proj M-axis " + "WGMMA loop (post_silu_scratch is sized for 2 atoms)."); + + // Activation-quantization block size along N: one up-block owns + // UP_COL_HALVES * 64 gate features (each atom packs 64 gate + 64 up rows). + static constexpr std::uint32_t DOWN_ACT_BLOCK_SIZE = UP_COL_HALVES * 64u; + static constexpr std::uint32_t DOWN_ACT_HALVES = Dims::N / DOWN_ACT_BLOCK_SIZE; + + // Effective M (row-tile) size of one block's up-proj work; drives + // UP_GRID = 2*N / W_UP_TILE_EFFECTIVE. static constexpr std::uint32_t W_UP_TILE_EFFECTIVE = - use_wgmma_v ? W_UP_TILE_WGMMA : W_UP_TILE; - - // ── WGMMA down-projection grid layout ──────────────────────────────── - // Each down-block owns DOWN_COL_TILE output cols within - // Dims::HIDDEN_STATES, so DOWN_GRID = HIDDEN_STATES / DOWN_COL_TILE - // blocks cover one expert's full output. The remaining grid blocks - // process DIFFERENT expert groups in parallel: DOWN_GROUPS = - // GRID_SIZE / DOWN_GRID expert groups each accumulate the - // contribution of their assigned experts via fp32 atomicAdd into - // the single-buffer `spec->down_partial_out[BS][HIDDEN_STATES]`. - // Phase 5 reads each cell once and casts to bf16 (no cross-group - // reduction). - // - // BS8 TMA+WGMMA (Phase 2a layout alignment): DOWN_COL_TILE = 256. - // DOWN_GRID = 2048 / 256 = 8 blocks per expert - // DOWN_GROUPS = 128 / 8 = 16 expert groups (== UP_GROUPS) - // This alignment makes the 8 blocks `[g*8, g*8+7]` form both - // `up_group = g` and `down_group = g` for the same expert set, so - // the producer-set of site #2 (Phase 3 → Phase 4) becomes identical - // to its consumer-set, enabling the Expert_Barrier in Phase 2b. - // - // The variant-dependent value MUST match - // `MoEGemmSpec::DOWN_COL_TILE`; the static_assert further down - // cross-checks their derived DOWN_GROUPS. - static constexpr std::uint32_t DOWN_COL_TILE = (use_tma_v && Dims::BS <= 8) ? 256u : 128u; + use_wgmma::value ? (UP_COL_HALVES * W_UP_TILE_WGMMA) : W_UP_TILE; + + // ── Down-projection grid layout ─────────────────────────────────────── + // DOWN_GRID blocks cover one expert's HIDDEN_STATES output cols; + // DOWN_GROUPS expert groups run in parallel, each atomicAdding into the + // single-buffer `spec->down_partial_out`. + static constexpr std::uint32_t DOWN_COL_TILE = down_col_tile::value; static constexpr std::uint32_t DOWN_GRID = Dims::HIDDEN_STATES / DOWN_COL_TILE; static constexpr std::uint32_t DOWN_GROUPS = DOWN_GRID == 0 ? 1 : Dims::KernelConfig::GRID_SIZE / DOWN_GRID; - static_assert(!use_wgmma_v || Dims::HIDDEN_STATES % DOWN_COL_TILE == 0, + static_assert(!use_wgmma::value || Dims::HIDDEN_STATES % DOWN_COL_TILE == 0, "HIDDEN_STATES must be a multiple of DOWN_COL_TILE for the " "WGMMA down-projection (one down-block owns DOWN_COL_TILE " "output cols)"); - static_assert(!use_wgmma_v || Dims::KernelConfig::GRID_SIZE % DOWN_GRID == 0, + static_assert(!use_wgmma::value || Dims::KernelConfig::GRID_SIZE % DOWN_GRID == 0, "GRID_SIZE must be a multiple of DOWN_GRID for the WGMMA " "down-projection (expert groups partition the grid)"); - static_assert(!use_wgmma_v || DOWN_GROUPS <= Dims::NUM_EXPERTS, + static_assert(!use_wgmma::value || DOWN_GROUPS <= Dims::NUM_EXPERTS, "DOWN_GROUPS cannot exceed NUM_EXPERTS (each expert group " "must process at least one expert)"); - // Cross-check that MoEGemmSpec's mirror of DOWN_COL_TILE / DOWN_GROUPS - // (computed locally there to avoid a forward reference) matches this - // one. If they diverge, the kernel's per-block col-stripe ownership - // would disagree with the GM accumulator buffer's size and the - // colstripe barrier's arrival count, silently corrupting Phase 5. + // MoEGemmSpec recomputes these locally (it is defined earlier in this + // file); a divergence would silently corrupt Phase 5. static_assert(MoEGemmSpec::DOWN_COL_TILE == DOWN_COL_TILE, "MoEGemmSpec::DOWN_COL_TILE must match " - "MoECoreDims::DOWN_COL_TILE — check the variant-dependent " - "DOWN_COL_TILE definition in both places."); + "MoECoreDims::DOWN_COL_TILE."); static_assert(MoEGemmSpec::DOWN_GROUPS == DOWN_GROUPS, - "MoEGemmSpec::DOWN_GROUPS must match MoECoreDims::DOWN_GROUPS " - "— check the DOWN_COL_TILE definition in both places."); - - // GEMM 2 matrix tile dimensions. - static constexpr std::uint32_t W_DOWN_MMA_TILE = 16; - static constexpr std::uint32_t W_DOWN_TILE = Dims::HIDDEN_STATES / Dims::KernelConfig::GRID_SIZE; - static constexpr std::uint32_t T_TILE = 8; - - static constexpr unsigned BLOCK_STRIDE = CALC_WARP_COUNT * K_TILE; - - static constexpr unsigned PADDING = - 32; // this works *slightly* better than 16 due to reduced L2 transfers - - // Row padding (in bytes) for the down-projection fp8 tiles (both the - // weight tile w[].down and the activation tile a.down). The MMA inner - // loop reads each row with `byte_offset = row * stride + 4 * (t % 4)` - // plus a row-stride of `t / 4`. For the reads to hit all 32 banks, we - // need `(stride_bytes / 4) % 32 >= 4`, i.e. the row stride in dwords - // must leave at least 4 unique banks per row step so the `t % 4` - // contribution (0..3) doesn't collide across rows. - // - // With N=512 (stride 128 dwords, which is 0 mod 32 → 8-way conflict), - // adding 16 bytes (4 dwords) gives 132 dwords → 4 mod 32. Combined - // with t%4 this covers all 32 banks uniformly. PADDING=32 (the global - // constant above) gives 136 dwords → 8 mod 32, only 4 unique banks - // per 4 rows → 2-way conflict. So we use DOWN_ROW_PADDING=16 here. - static constexpr unsigned DOWN_ROW_PADDING = 16; - static constexpr unsigned K_DIM_PADDED_A = Dims::HIDDEN_STATES; - static constexpr unsigned K_DIM_PADDED_W = Dims::HIDDEN_STATES; - static constexpr unsigned K_DIM_HALF_PADDED_A = Dims::HIDDEN_STATES / 2; + "MoEGemmSpec::DOWN_GROUPS must match " + "MoECoreDims::DOWN_GROUPS."); + + // Per-block token-tile width consumed by the FP8 activation staging + // and the down-proj WGMMA B operand. 8 for BS<=8 (one 8-token SWZ128 + // atom). + static constexpr std::uint32_t T_TILE = 8u; }; -// 1 tile per warp -// 20 warps x 2 params x 1k = 20k pre-fetch +/** + * @brief Dynamic shared-memory layout. + * + * The dominant space is a union whose members have strictly disjoint + * lifetimes (separated by the Phase-2 trailing __syncthreads() and the + * Phase 3 → 4 barrier). See docs/design_docs/monomoe_kernel.md "Shared memory". + */ template struct MoE_SHM { using CoreDims = MoECoreDims; - // `tiny_wgmma_tma` holds the SHM for the TMA+WGMMA path. Its inner - // anonymous unions overlap buffers with disjoint lifetimes (notably the - // Phase-1 `bf16_in_full` over the Phase-3/4 weight tiles), which is where - // the real SHM byte-sharing happens. - - // ── TinyDataWGMMA_TMA: SHM layout for the TMA+WGMMA up-proj path ── - // - // Used when `use_wgmma_v && use_tma_v` are both - // true — the TMA-based activation & weight loading path for the BS8 - // WGMMA up- and down-projections. - // - // Routing-window pipeline (Phase 1 → Phase 2 → Phase 3): - // * `bf16_in_full` — routing-window BF16 buffer. Populated in - // Phase 1 by the TMA launcher via a single 16-issue - // `cp.async.bulk.tensor.2d` loop covering the full per-block - // `[BS][HIDDEN_STATES]` BF16 input tile. Completion is - // signalled on `bar_rwin`; consumed by Phase 2's - // `routing_phase_quantize` and dead by the Phase-2 trailing - // `__syncthreads()`. - // * `fp8_act_full` — routing-phase-quantized FP8 buffer covering - // all `K_BLOCKS_TOTAL` 128-K substeps. Written by Phase 2's - // `routing_phase_quantize` (warps 1..11), read by the Phase-3 - // up-projection K-loop with no double-buffer slot alternation. - // * `a_down_wgmma` — down-projection activation buffer (Phase 4). - // Populated by the down-proj's per-expert TMA bulk activation - // load and consumed by the down-proj WGMMA K-loop. Aliases - // SHM bytes that are dead by the time Phase 4 starts (the - // Phase-3 → Phase-4 grid sync serializes the reuse). - // - // mbarriers (all `alignas(16)` to satisfy the SM90 mbarrier PTX - // alignment requirement): - // * bar_w[2] — weight-tile mbarriers (one per double-buffer - // slot). Armed by the TMA launcher with the - // per-arm weight tx_bytes before the - // `cp.async.bulk.tensor.2d` stripe sequence. - // Consumed by the WGMMA warps via - // `mbarrier.try_wait.parity` in both the up- and - // down-projection K-loops. - // * bar_a[2] — down-projection activation-tile mbarriers (one - // per double-buffer slot). Armed and consumed - // EXCLUSIVELY by `moe_down_projection_BS8_..._tma` - // (Phase 4); re-initialized in the down-proj - // prologue. No up-proj consumer remains — - // Phase-3 sources its activation operand from - // `fp8_act_full`. - // * bar_rwin — routing-window mbarrier (`arrival_count = 1`). - // Armed by the TMA launcher in Phase 1 with - // `tx_bytes = BS * K_BLOCKS_TOTAL * K_STEP_WGMMA * - // sizeof(A_element)` (= 32 KB for Qwen3.5). - // Consumed by warps 1..11 at the start of Phase 2 - // before reading `bf16_in_full`. + // SHM layout for the BS8 TMA+WGMMA path (the only BS8 variant). struct TinyDataWGMMA_TMA { - // ── K-substep constants ──────────────────────────────────────── - // `UP_K_SUBSTEPS` is the number of 128-K SWZ128 atoms per outer - // up-proj K-step (= K_STEP_UP / K_STEP_WGMMA). - static constexpr uint32_t UP_K_SUBSTEPS = CoreDims::K_SUBSTEPS_UP; - // Total number of 128-K SWZ128 atoms per token along the K axis - // (= Dims::HIDDEN_STATES / K_STEP_WGMMA). Equal to 16 for - // Qwen3.5 (HIDDEN_STATES = 2048). Used by the new Phase-1 - // routing-window TMA load (covers the full BF16 input tile in - // K_BLOCKS_TOTAL bulk loads) and by the new single-buffer - // `fp8_act_full` that covers all K substeps for Phase-3 - // direct FP8 reads. + // 128-K SWZ128 atoms per token along the full K axis. static constexpr uint32_t K_BLOCKS_TOTAL = Dims::HIDDEN_STATES / CoreDims::K_STEP_WGMMA; - // BF16 input buffer in tile-major `[K_BLOCKS_TOTAL][BS][K_STEP_WGMMA]` - // (not `[BS][HIDDEN_STATES]`) so each `boxDim=(128,8)` TMA write lands - // in its own 2 KB slab without overlapping the next K-substep; full - // rationale in docs/design_docs/monomoe_kernel.md §5. Total 32 KB, - // unchanged from the natural shape, so the union and SHM budget are - // unaffected. + // Live extents for the BS8 WGMMA+TMA tag (the only variant). BS8 SASS + // bit-identity is preserved (these evaluate identically to the former + // `(Dims::BS <= 16) ? live : 1` since BS = 8). static constexpr uint32_t BF16_IN_FULL_K_BLOCKS = K_BLOCKS_TOTAL; static constexpr uint32_t BF16_IN_FULL_BS = Dims::BS; static constexpr uint32_t BF16_IN_FULL_K = CoreDims::K_STEP_WGMMA; static constexpr uint32_t FP8_ACT_FULL_K_BLOCKS = K_BLOCKS_TOTAL; static constexpr uint32_t FP8_ACT_K_CHUNK = 16; - // Number of 16-K fp8 chunks per ONE 128-K SWZ128 atom (the unit - // shared by the up-proj's per-substep layout and the down-proj's - // per-substep layout). Always 128 / 16 = 8. - static constexpr uint32_t FP8_ACT_NUM_CHUNKS = - CoreDims::K_STEP_WGMMA / FP8_ACT_K_CHUNK; // 128 / 16 = 8 - - // Down-proj activation tile holds one outer K-step's worth of - // fp8 activations: `K_SUBSTEPS_DOWN` SWZ128 atoms stacked along - // the K axis (each atom is 8 tok × 128 K-bytes = 1 KB). For - // K_STEP_DOWN=128 this collapses to the legacy single-atom 1 KB - // slot; for K_STEP_DOWN=256 it grows to 2 KB. + // 16-K fp8 chunks per 128-K SWZ128 atom. + static constexpr uint32_t FP8_ACT_NUM_CHUNKS = CoreDims::K_STEP_WGMMA / FP8_ACT_K_CHUNK; // 8 + static constexpr uint32_t DOWN_ACT_K_SUBSTEPS = CoreDims::K_SUBSTEPS_DOWN; - static constexpr uint32_t DOWN_FP8_ACT_NUM_CHUNKS = - CoreDims::K_STEP_DOWN / FP8_ACT_K_CHUNK; // 128 or 256 / 16 - // 1024-byte alignment required by SWIZZLE_128B on the down-proj - // activation TMA: the XOR pattern uses low bits of the SHM - // address and only behaves consistently within 1024-B-aligned - // regions. - // - // `a_down_wgmma` is the down-projection activation buffer - // (Phase 4). It uses the (sub-step, token, kc, ki) view that - // matches the CUTLASS Major::K B128 layout after the TMA's - // SWZ128 XOR. The sub-step dimension is collapsed into the - // leading axis as a sequence of `DOWN_ACT_K_SUBSTEPS` 1024-B - // atoms — each atom is exactly one K_STEP_WGMMA=128 K-substep - // of the outer K-step. - alignas(1024) - AQ_element a_down_wgmma[2][DOWN_ACT_K_SUBSTEPS][CoreDims::T_TILE][FP8_ACT_NUM_CHUNKS] - [FP8_ACT_K_CHUNK]; // 2 KB (down, K=128) - // 4 KB (down, K=256) - - // ── NEW: single-buffer fp8_act covering all K substeps ────────── - // Single-buffer FP8 activation buffer for the BS8 TMA+WGMMA - // post-fusion Phase-3 reads. Indexed by `k_block ∈ - // [0, K_BLOCKS_TOTAL)`; the up-proj K-loop reads - // `fp8_act_full[s * UP_K_SUBSTEPS + kk][...]` with no slot - // alternation. Layout per `k_block`: - // `[FP8_ACT_NUM_CHUNKS][T_TILE_PADDED][FP8_ACT_K_CHUNK]` - // where `T_TILE_PADDED = T_TILE + 1 = 9`. The 9th token-row in - // each kc atom is unused padding — its purpose is to break the - // 128-byte kc stride that caused an 8-way bank conflict on the - // routing-quantize STS (lanes with the same `t%4` were targeting - // the same bank across kc steps because `kc*128 B = 0 mod 32 - // banks`). With the pad, the kc stride becomes - // `T_TILE_PADDED * FP8_ACT_K_CHUNK = 9 * 16 = 144 B = 36 banks - // mod 32 = 4`, so kc=0..7 write to disjoint banks within each - // `t%4` lane group → conflict-free. - // - // The matching WGMMA B descriptor for the up-proj K-loop is - // updated from `B_LBO = 128` to `B_LBO = T_TILE_PADDED * - // FP8_ACT_K_CHUNK = 144` to step across the new kc stride. The - // 8-row × 16-byte WGMMA core matrix at the head of each kc atom - // is still 128 B contiguous (rows 0..7) and the unused 9th row - // is skipped by the LBO step. - // - // Sizing (Qwen3.5, K_BLOCKS_TOTAL=16): - // * Old: 16 × 8 × 8 × 16 = 16 KB. - // * New: 16 × 8 × 9 × 16 = 18 KB (+2 KB). + // Down-proj activation ring (DOWN_PIPE_DEPTH slots; 2 = the classic + // double buffer): one outer K-step's worth of fp8 activations = + // K_SUBSTEPS_DOWN SWZ128 atoms (8 tok × 128 K-bytes each) per slot. + // 1024-B alignment required by SWIZZLE_128B (the XOR pattern is only + // consistent within 1024-B-aligned regions). + alignas(1024) AQ_element a_down_wgmma[CoreDims::DOWN_PIPE_DEPTH][DOWN_ACT_K_SUBSTEPS] + [CoreDims::T_TILE][FP8_ACT_NUM_CHUNKS][FP8_ACT_K_CHUNK]; + + // Single-buffer FP8 activations covering the full K range, produced + // once per launch by Phase-2 routing_phase_quantize and read directly + // by the Phase-3 K-loop (no slot alternation). // + // The token dim is padded 8 → 9 rows per 16-B chunk: the natural + // 128-B chunk stride put every same-`t%4` lane on the same bank + // (8-way STS conflict); 9 rows make the stride 144 B = 4 banks mod + // 32, conflict-free. The 9th row is never written; the up-proj + // WGMMA B descriptor steps over it with LBO = 144. static constexpr uint32_t FP8_ACT_T_TILE_PADDED = CoreDims::T_TILE + 1u; alignas(1024) AQ_element fp8_act_full[FP8_ACT_FULL_K_BLOCKS][FP8_ACT_NUM_CHUNKS] [FP8_ACT_T_TILE_PADDED][FP8_ACT_K_CHUNK]; - static constexpr uint32_t W_WGMMA_M = 128; // M dim of weight tile (up-proj) - // Down-proj tile M dim tracks DOWN_COL_TILE (Phase 2a): 128 for the - // non-TMA path, 256 for the BS8 TMA+WGMMA variant after the - // Phase-2a layout alignment (DOWN_COL_TILE = 256). Must stay a - // multiple of 128 so the SWIZZLE_128B core-matrix atoms still tile - // the outer M axis cleanly. + static constexpr uint32_t W_WGMMA_M = 128; static constexpr uint32_t W_DOWN_WGMMA_M = CoreDims::DOWN_COL_TILE; - // K dim of the up-proj weight tile is held at K_STEP_WGMMA (= 128) - // so the row stride matches the SWIZZLE_128B core-matrix width. - // For K_STEP_UP > 128 we stack `K_SUBSTEPS_UP` 128-K SWZ128 atoms - // along the M axis (substep 0 → rows [0..127], substep 1 → rows - // [128..255], …) — same trick the down-proj uses for K_STEP_DOWN. - // Each atom remains a self-contained 1024-B-aligned 128×128 region - // so the TMA swizzle and the WGMMA A-descriptor (which addresses - // one 128-row sub-atom per call) both work without a row-stride - // change. static constexpr uint32_t W_WGMMA_K = CoreDims::K_STEP_WGMMA; - static constexpr uint32_t W_WGMMA_M_TOTAL = W_WGMMA_M * CoreDims::K_SUBSTEPS_UP; - // Down-proj outer K-step width (tunable via Dims::KernelConfig:: - // K_STEP_DOWN, default = 128). Each outer K-step packs - // `K_SUBSTEPS_DOWN` 128-K sub-blocks into the same SHM slot, - // stacked along the M axis as additional 128-row atoms (so the - // existing 128×128 SWZ128 atom layout is reused unchanged). + // The up weight tile stacks the K substeps AND the UP_COL_HALVES + // M-atoms along the M axis (substep kk, half h → rows + // [(kk*UCH + h)*128, +128)), so each atom remains a self-contained + // 1024-B-aligned 128×128 SWZ128 region. + static constexpr uint32_t W_WGMMA_M_TOTAL = + W_WGMMA_M * CoreDims::K_SUBSTEPS_UP * CoreDims::UP_COL_HALVES; + // The down weight tile stacks its K substeps along M the same way. static constexpr uint32_t W_DOWN_WGMMA_K = CoreDims::K_STEP_DOWN; static constexpr uint32_t W_DOWN_WGMMA_M_TOTAL = W_DOWN_WGMMA_M * CoreDims::K_SUBSTEPS_DOWN; + static constexpr uint32_t UP_W_SLOTS = CoreDims::UP_W_SLOTS; + + // The three views below alias: bf16_in_full is dead by the Phase-2 + // trailing sync (before any weight TMA fires), and w_wgmma's last + // consumer wait precedes the Phase-4 reuse as w_down_wgmma (the + // site-#2 barrier serializes the transition). union { - // 1024-byte alignment required by SWIZZLE_128B: the XOR - // pattern uses low bits of the SHM address and only behaves - // consistently within 1024-byte-aligned regions. Both - // `w_wgmma` and `w_down_wgmma` alias the same SHM bytes, so - // the alignas applies to both views. - // - // ── NEW: full BF16 input tile, unioned with w_wgmma + w_down_wgmma. - // - // `bf16_in_full[K_BLOCKS_TOTAL][BS][K_STEP_WGMMA]` - // = 16 × 8 × 128 × 2 = 32 KB for Qwen3.5. - // Lifetime: written by the Phase-1 routing-window TMA, read - // by the Phase-2 routing_phase_quantize, dead by the Phase-2 - // trailing __syncthreads(). Aliases bytes with w_wgmma / - // w_down_wgmma whose lifetimes start strictly later (Phase 3 - // up-proj weight TMA / Phase 4 down-proj weight TMA), so the - // union is byte-disjoint at any instant in time. - // - // Tile-major `[K_BLOCKS_TOTAL][BS][K_STEP_WGMMA]` (not - // `[BS][HIDDEN_STATES]`) so each `boxDim=(128,8)` TMA write gets its - // own 2 KB slot in the TMA's compact write order, and - // `routing_phase_quantize` reads `bf16_in_full[kblk][token]` as a - // natural row — rationale in docs/design_docs/monomoe_kernel.md §5. - // - // Aligned to 1024 B to inherit the SWZ128 alignment of the - // unioned weight buffers (the bf16 activation TMA descriptor - // itself uses SWIZZLE_NONE so 16 B alignment would suffice). - // - // - // Sizing (per slot): - // w_wgmma[2][W_WGMMA_M_TOTAL][K_STEP_WGMMA=128] - // K_STEP_UP=128: W_WGMMA_M_TOTAL=128 → 16 KB - // K_STEP_UP=256: W_WGMMA_M_TOTAL=256 → 32 KB - // (2 substeps × 128 M rows × 128 K bytes - // stacked along M) - // w_down_wgmma[2][W_DOWN_WGMMA_M_TOTAL][K_STEP_WGMMA=128] - // DOWN_COL_TILE=128, K_STEP_DOWN=128: 16 KB - // DOWN_COL_TILE=256, K_STEP_DOWN=128: 32 KB - // DOWN_COL_TILE=256, K_STEP_DOWN=256: 64 KB (2 substeps × - // 256 M rows × - // 128 K bytes - // stacked along M) - // - // The union picks max(BF16_IN_FULL_BYTES, W_UP_BYTES, - // W_DOWN_BYTES); the smaller view's tail bytes are unused - // during its phase (Phase 1/2 doesn't touch the weight - // views, Phase 3 doesn't touch the bf16 input view, and - // Phase 4 doesn't touch the up-proj weight view — separated - // by the Phase-2 trailing __syncthreads() and the Phase 3→4 - // grid sync). - alignas(1024) A_element bf16_in_full[BF16_IN_FULL_K_BLOCKS][BF16_IN_FULL_BS] - [BF16_IN_FULL_K]; // 32 KB (Phase 1/2) -#ifdef MONO_PROFILE_BARW_4DEEP - // Up-proj weight slots (BARW_4DEEP variant): 4 slots for the - // 2-iter lookahead pipeline. At iter `s` the launcher - // arms+TMAs slot `(s+2) & 3`; calc waits on `bar_w[s & 3]`. - // Slots wrap modulo 4 every 4 iters, and the calc-side - // wait at iter `s+1` provides the publish acquire on slot - // `(s+1) & 3` before iter `s+3`'s arm targets the same slot - // (3-iter wraparound > 2-iter calc/launcher gap). - // - // SHM cost: same as the 2-slot variant, because the union - // is dominated by `w_down_wgmma` at 128 KB. - alignas( - 1024) W_element w_wgmma[4][W_WGMMA_M_TOTAL][W_WGMMA_K]; // 4 slots × 32 KB = 128 KB total -#else - alignas(1024) - W_element w_wgmma[2][W_WGMMA_M_TOTAL][W_WGMMA_K]; // 128 wide × M stacked atoms (up-proj) -#endif + // Routing-window BF16 input tile (Phase 1/2). Tile-major + // [K_BLOCKS_TOTAL][BS][K_STEP_WGMMA] — NOT [BS][HIDDEN] — because + // each activation TMA writes a compact 8×128 box whose row stride + // is the box's own inner dim (256 B), not the destination's + // logical row stride; each K-substep therefore needs its own + // self-contained 2 KB slab. + alignas(1024) A_element bf16_in_full[BF16_IN_FULL_K_BLOCKS][BF16_IN_FULL_BS][BF16_IN_FULL_K]; + // Up-proj weight slots (Phase 3), UP_W_SLOTS deep. + alignas(1024) W_element w_wgmma[UP_W_SLOTS][W_WGMMA_M_TOTAL][W_WGMMA_K]; + // Down-proj weight ring (Phase 4), DOWN_PIPE_DEPTH slots (2 = the + // classic double buffer). Slot size scales with K_STEP_DOWN, so a + // 4-deep ring at KDN=128 occupies the same bytes as the 2-deep at + // KDN=256. alignas(1024) W_element - w_down_wgmma[2][W_DOWN_WGMMA_M_TOTAL][CoreDims::K_STEP_WGMMA]; // 128 wide × M - // stacked atoms - // (down-proj) + w_down_wgmma[CoreDims::DOWN_PIPE_DEPTH][W_DOWN_WGMMA_M_TOTAL][CoreDims::K_STEP_WGMMA]; }; - static constexpr uint32_t DOWN_ACT_HALVES_PER_EXPERT = - Dims::N / 64u; // 8 for N=512 (one fp32 scale per per-64-K - // up-block per token, full reduction dim) - // Per-token activation scales for the WHOLE expert, loaded once - // at the top of the per-expert loop (NOT per K-step). The K-loop - // indexes this as `a_down_scale[s * K_SUBSTEPS_DOWN * 2 + 2 * kk + - // half][tok]` to pick the half covering the current 64-K - // sub-block. Hoisting to per-expert removes the per-K-step - // cp.async + pipe drain that was the only consumer of the - // `cuda::pipeline` in the down-proj path. - // - // Layout note (bank-conflict avoidance, 2026-05): the inner index - // is `tok` for the same reason as `MoE_SHM::act_scale` above — - // the WGMMA scale-apply broadcasts each `(global_half, tok)` pair - // across the 8 four-lane groups in a warp, so a `[half][tok]` - // layout puts every read on a distinct bank within one 32-B row, - // eliminating the 2-way bank conflict the legacy `[tok][half]` - // layout produced (32-B row stride mod 32 banks lined `tok=0,4` - // up on the same bank). + // Per-expert down-proj activation scales, loaded once per expert + // (not per K-step). [block][tok] layout: the WGMMA scale-apply + // broadcasts each (block, tok) pair across the 8 four-lane groups, + // so the transposed layout puts every read on a distinct bank. + static constexpr uint32_t DOWN_ACT_HALVES_PER_EXPERT = CoreDims::DOWN_ACT_HALVES; S_element a_down_scale[DOWN_ACT_HALVES_PER_EXPERT][CoreDims::T_TILE]; + // Down-proj weight scales: [M-atom half][WG0/WG1][col-block]. static constexpr uint32_t W_DOWN_SCALE_COLS = shm_down_scale_cols::value; - S_element w_down_scale[2][2][W_DOWN_SCALE_COLS]; - - static constexpr uint32_t DOWN_SCALE_TILE_SIZE = - ((CoreDims::W_DOWN_TILE + 127) / 128) * ((Dims::N + 127) / 128); - S_element scale[2][DOWN_SCALE_TILE_SIZE + CoreDims::PADDING]; + static constexpr uint32_t W_DOWN_SCALE_HALVES = CoreDims::DOWN_COL_TILE / 128u; + S_element w_down_scale[W_DOWN_SCALE_HALVES][2][W_DOWN_SCALE_COLS]; + // Up-proj weight scales, ping-pong: expert e consumes slot + // cur_scale_slot while e+1 prefetches into the other slot. static constexpr uint32_t UP_SCALE_TILE_SIZE = 2 * shm_up_scale_cols::value; S_element up_scale[2][UP_SCALE_TILE_SIZE]; + // down_out is intentionally unpadded: its bank conflicts (a 4-way STS on + // the epilogue writeback, a 16-way LDS on the deferred accumulate) sit on + // prefetch/epilogue slots hidden behind WGMMA and TMA waits, so padding + // the stride gave no measured speedup (and +1 regressed the STS.64 pair + // merge). + static constexpr uint32_t DOWN_OUT_ROWS = CoreDims::DOWN_COL_TILE; union { - T_element up[CoreDims::CALC_WARP_COUNT][CoreDims::W_UP_TILE * CoreDims::T_TILE]; - T_element down[CoreDims::W_DOWN_TILE / 2 + CoreDims::CALC_WARP_COUNT / 2] - [CoreDims::W_DOWN_MMA_TILE * CoreDims::T_TILE]; - // wgmma_out: bank-conflict-free row stride. + // Down-proj per-expert output scratch (Phase-4 epilogue → + // deferred accumulate). + T_element down_out[DOWN_OUT_ROWS][CoreDims::T_TILE]; + // Up-proj post-SiLU fp32 scratch: calc warps write the per-lane + // silu(gate)*up*rw combine at the K-loop tail of expert e; PF + // warps drain it during expert e+1's K-loop (deferred epilogue). + // Atom h uses rows [h*128, +128); within an atom only rows + // [0..31] (WG0) and [64..95] (WG1) carry values. The +1 column + // pad makes the [col][tok] read pattern bank-conflict-free + // (row stride 9 floats, gcd(9, 32) = 1). // - // Reader access pattern (in `up_silu_quant_writeback_one_token`): - // every lane in a warp reads `wgmma_out[col_in_half + offset][tok]` - // with `col_in_half = lane` (0..31) and `tok = warp` (uniform). - // Address = base + lane*(row_stride_bytes) + tok*4. With the - // natural row stride of 8 floats = 32 bytes = 8 banks, lane k's - // bank is `(lane*8 + tok) mod 32`, which collapses 32 lanes into - // only 4 distinct banks → 8-way bank conflict on every LDS (4 - // LDS per (lane, tok) for gate1/up1/gate2/up2). - // - // Padding the row stride to 9 floats = 36 bytes makes the bank - // index `(lane*9 + tok) mod 32`, which is bijective over 32 - // lanes (gcd(9, 32) = 1) → conflict-free reads. The 9th column - // is unused. - // - // SHM cost: 128 × 1 × 4 = 512 extra bytes for `wgmma_out`, but - // the union is dominated by `down_out[256][8] = 8 KB`, so the - // total union footprint is unchanged. - T_element wgmma_out[128][CoreDims::T_TILE + 1]; - T_element down_out[CoreDims::DOWN_COL_TILE][CoreDims::T_TILE]; + // Aliasing down_out is safe: down_out belongs to Phase 4, which + // is barrier-separated from every post_silu_scratch access. + T_element post_silu_scratch[CoreDims::UP_COL_HALVES * 128][CoreDims::T_TILE + 1]; } partial_result; static constexpr uint32_t OUT_ACCUM_ROW_PAD = 1; - static constexpr uint32_t OUT_ACCUM_COLS = CoreDims::W_DOWN_TILE > CoreDims::DOWN_COL_TILE - ? CoreDims::W_DOWN_TILE - : CoreDims::DOWN_COL_TILE; - T_element out_accum[Dims::BS][OUT_ACCUM_COLS + OUT_ACCUM_ROW_PAD]; - - // ── TMA-only extensions ───────────────────────────────────────── - // - // Weight-tile mbarriers (one per double-buffer slot). The launcher - // arms `bar_w[slot]` with `mbarrier.arrive.expect_tx tx_bytes=16384` - // before the 4 sub-tile TMAs that populate `w_wgmma[slot]`; WGMMA - // consumers poll via `mbarrier.try_wait.parity`. - // - // ── Sized for the deepest lookahead the up-proj K-loop uses ── - // - // The default 1-deep lookahead (steady-state pipeline) only uses - // slots [0, 1]. The 2-deep lookahead variant (gated on - // `MONO_PROFILE_BARW_4DEEP`) uses all four slots to stagger the - // cross-expert stitch one iter earlier, giving DRAM more time to - // drain between the stitch and the next expert's iter-1 weight - // TMA. The down-proj path (which has its own pipeline structure) - // re-initializes only slots [0, 1] in its prologue and leaves - // slots [2, 3] untouched — they aren't waited on by the down-proj - // K-loop, so leaving them un-init is safe. - // - // Note on SHM impact: `w_wgmma` is unioned with `w_down_wgmma` at - // 128 KB (DOWN_COL_TILE=256, K_STEP_DOWN=256), which dominates - // the union regardless of `w_wgmma`'s slot count. Widening - // `w_wgmma[2]` to `w_wgmma[4]` (also gated on the same macro, - // see below) does not increase the union size. - // - // Down-projection activation-tile mbarriers (one per double- - // buffer slot). Used EXCLUSIVELY by the down-projection - // (Phase 4): the down-proj launcher arms `bar_a[slot]` before - // each per-expert bulk activation TMA into `a_down_wgmma[slot]`, - // and the down-proj WGMMA K-loop waits via - // `mbarrier.try_wait.parity`. Re-initialized in the down-proj - // prologue (`moe_down_projection.cuh`) so the up-side init in - // `moe.cuh`'s prologue is no longer required. No up-projection - // consumer remains — Phase 3 sources its activation operand - // from `fp8_act_full`. - // - // `alignas(16)` satisfies the 16-byte alignment that the - // SM90 `mbarrier.*.shared::cta.b64` instructions require. -#ifdef MONO_PROFILE_BARW_4DEEP - alignas(16) uint64_t bar_w[4]; // 32 B (2-deep lookahead) -#else - alignas(16) uint64_t bar_w[2]; // 16 B (1-deep lookahead) -#endif - alignas(16) uint64_t bar_a[2]; // 16 B - - // ── routing-window mbarrier ───────────────── - // Single mbarrier (`arrival_count = 1`) used to hand off the - // Phase-1 routing-window TMA load (full BF16 input tile, 32 KB) - // from the TMA launcher thread to warps 1..11 at the start of - // Phase 2. Armed once by the launcher with - // `tx_bytes = BS * K_BLOCKS_TOTAL * K_STEP_WGMMA * - // sizeof(A_element)` - // (= 8 × 16 × 128 × 2 = 32 KB for Qwen3.5). Initialized in the - // kernel prologue alongside `bar_w[0..1]`, before the - // `fence_mbarrier_init_release_cluster()` and any - // `mbarrier.arrive.expect_tx`. Re-init not needed; the wait - // drains it. - // - // `alignas(16)` matches `bar_w` / `bar_a` and the SM90 - // `mbarrier.*.shared::cta.b64` instruction alignment. + T_element out_accum[Dims::BS][CoreDims::DOWN_COL_TILE + OUT_ACCUM_ROW_PAD]; + + // ── mbarriers (16-B alignment required by SM90 mbarrier PTX) ───── + // bar_w: up-proj weight pipeline, one per lookahead slot; the + // down-proj reuses slots 0..DOWN_PIPE_DEPTH-1 as its ring (sized + // for whichever phase needs more). bar_a: down-proj activation + // ring, armed/consumed exclusively by Phase 4 (re-initialized + // there). bar_rwin: Phase-1 routing-window load (arrival_count = + // 1), waited on by warps 1..11 at the start of Phase 2. + static constexpr uint32_t BAR_W_COUNT = + (UP_W_SLOTS > CoreDims::DOWN_PIPE_DEPTH) ? UP_W_SLOTS : CoreDims::DOWN_PIPE_DEPTH; + alignas(16) uint64_t bar_w[BAR_W_COUNT]; + alignas(16) uint64_t bar_a[CoreDims::DOWN_PIPE_DEPTH]; alignas(16) uint64_t bar_rwin; - // ── Phase 3 → Phase 4 (expert, token) reorganization tables ───── - // - // Added by the `tma-wgmma-down-projection` spec for the Phase-4 - // TMA activation-load path. Only populated when - // `use_tma_v` is true — on the cp.async reference path - // these fields are allocated inside the `tiny_wgmma_tma` union - // variant but never read or written, so non-TMA SHM layouts stay - // byte-identical. These fields live in the - // `tiny_wgmma_tma` variant only (not in `TinyDataWGMMA`) so the - // non-TMA WGMMA variant's SHM layout is also unchanged. + // ── Phase 3 → Phase 4 (expert, token) reorganization tables ────── // // expert_slot_start[id] = first row in spec->temp_fp8 reserved - // for expert `id` under the expert- - // sorted layout produced by the - // Phase-3 epilogue. Inactive experts - // have the same value as the next - // active expert (zero-width slice). - // expert_routed_count[id] = number of routed (tok, k_in_topk) - // pairs that select expert `id`; - // range [0, batch_size * top_k]. - // sorted_slot[pair] = destination row in spec->temp_fp8 - // for the up-proj SiLU+fp8 writeback, - // where `pair = tok * top_k + k_in_topk`. - // Value = expert_slot_start[eid] + - // intra-expert rank of (tok, k_in_topk). - // - // Sizing for BS=8, top_k=8, NUM_EXPERTS=256: - // expert_slot_start : uint16 × 256 = 512 B (max value < 64) - // expert_routed_count : uint8 × 256 = 256 B (max value ≤ 64) - // sorted_slot : uint8 × 64 = 64 B (max value < 64) - // Total ≤ 832 B, comfortably inside the 228 KB SHM budget. + // for expert id (expert-sorted layout). + // expert_routed_count[id] = routed (tok, k) pairs selecting id. + // sorted_slot[pair] = destination temp_fp8 row for the + // up-proj writeback, + // pair = tok * top_k + k. // - // Access pattern: - // * Phase 3 epilogue reads `sorted_slot[pair]` once per routed - // pair to pick the fp8 writeback row. - // * Phase 4 launcher reads `expert_slot_start[id]` and - // `expert_routed_count[id]` once per expert to parameterize - // the bulk activation TMA. - // * Phase 4 epilogue walks the (tok, k_in_topk) grid - // in `topk_ids_flat`, filters by the current expert id, then - // derives the intra-expert rank as - // `sorted_slot[pair] - expert_slot_start[id]` to index the - // SHM slot — no dedicated inverse table needed. + // alignas(16) on expert_slot_start is REQUIRED, not cosmetic: + // routing Phase B writes it with packed 16-B vector stores whose + // per-lane address is only 16-B aligned if the base is. static constexpr uint32_t MAX_TOPK = 8; static constexpr uint32_t MAX_PAIRS = Dims::BS * MAX_TOPK; - // `alignas(16)` is required (NOT cosmetic): Phase B of - // `prepare_moe_topk_BS8` (in `moe_routing.cuh`) emits a packed - // 16-byte STS.128 store per warp lane via - // `*reinterpret_cast(&expert_slot_start[tid * BLK]) = - // packed_starts;` - // with `BLK = 8` u16 elements (= 16 B) per lane. The compiler - // emits a 128-bit vector shared store that requires the - // destination address to be 16-byte aligned; `tid * BLK * 2 = - // tid * 16` is 16-aligned only if the array base itself is - // 16-aligned. Without this `alignas(16)` the routing-window - // mbarrier `bar_rwin` (8 B + alignas(16) → 8 B of trailing - // padding consumed by the next field) shifts - // `expert_slot_start[]` to an 8-B-aligned-but-not-16-B-aligned - // offset, which causes a `cudaErrorMisalignedAddress` at the - // STS.128 issue. The writer comment in `moe_routing.cuh` - // already documents this expectation; this `alignas(16)` makes - // the contract explicit on the declaration side so future SHM - // layout changes cannot silently break it. alignas(16) uint16_t expert_slot_start[Dims::NUM_EXPERTS]; - // `alignas(16)` is required (NOT cosmetic): `prepare_moe_topk_BS8` - // (in `moe_routing.cuh`) zero-inits this array with a per-lane - // STS.64 (`*reinterpret_cast(&expert_routed_count[tid * - // BLK]) = 0ull`, BLK = 8) and later reads it back with the matching - // 64-bit `reinterpret_cast` load. Both require the array base to be - // ≥8-byte aligned (per-lane base `tid * BLK` is 8-aligned only when - // the base itself is). It currently lands 16-aligned by virtue of - // the preceding `alignas(16) uint16_t expert_slot_start[256]` (= 512 - // B, a multiple of 16), but that is incidental — making the - // alignment explicit here means a future SHM-layout change to the - // preceding field cannot silently shift this to an unaligned offset - // and trigger `cudaErrorMisalignedAddress` at the STS.64 / LD.64. - alignas(16) uint8_t expert_routed_count[Dims::NUM_EXPERTS]; + uint8_t expert_routed_count[Dims::NUM_EXPERTS]; uint8_t sorted_slot[MAX_PAIRS]; - // ── Routing-time inverse map: (expert id, token) → top-k rank ──────── - // - // `expert_tok_krank[eid * Dims::BS + tok]` holds the top-k rank - // `k ∈ [0, top_k)` at which token `tok` routes to expert `eid`, or - // sentinel `0xFF` when the token does not route through that expert. - // - // Built ONCE, at routing time, by `prepare_moe_topk_BS8` (Phase C in - // `moe_routing.cuh`), which already enumerates every routed - // `(tok, k, eid)` pair to fill `sorted_slot`. It scatters `k` into - // this table on the same pass — no extra scan. This is the single - // source of truth both projection epilogues consume instead of each - // re-deriving `k` per expert: - // - // * Up-proj (`up_silu_quant_writeback_one_token`): reads - // `k = expert_tok_krank[id*BS + tok]`; a valid `k` yields the - // routing weight `topk_weights_flat[tok*MAX_TOPK + k]` and the - // fp8 writeback row `sorted_slot[tok*top_k + k]`. - // * Down-proj (Phase-4 epilogue): reads the same `k` and derives - // the intra-expert slot `sorted_slot[tok*top_k + k] - - // expert_slot_start[id]` into the per-expert `rank_for_tok` - // staging array. - // - // Replaces the previous per-expert 8-iter scans over - // `topk_ids_flat` (one at the up-proj K-loop tail, one at the - // down-proj expert-loop tail) that ran O(BS·top_k) work for EVERY - // expert this block processes — pure duplication of routing-time - // information. Because the table is immutable after routing, it - // also removes the single-buffer lifetime hazard the old - // per-expert `up_rank_for_tok` / scan-fed `rank_for_tok` carried - // across the deferred-epilogue expert boundary. - // - // Uniqueness: top-k selection picks DISTINCT experts per token (the - // selection loop masks each chosen expert to -FLT_MAX), so a given - // (eid, tok) pair occurs at most once — the scatter has no - // write conflict and needs no tie-break. - // - // SHM cost: NUM_EXPERTS * BS bytes (2 KB for E=256, BS=8). - // - // `alignas(16)`: `prepare_moe_topk_BS8` sentinel-fills this table with - // a per-lane vectorized `uint4` (STS.128) store, which requires a - // 16-byte-aligned base. It currently lands 16-aligned after the - // 64-B `sorted_slot`, but making it explicit means a future layout - // change to a preceding field cannot silently misalign the fill. - alignas(16) uint8_t expert_tok_krank[Dims::NUM_EXPERTS * Dims::BS]; - // Per-expert per-token cached intra-expert SLOT rank used by the - // down-proj accumulate loop (Phase 4 epilogue). Rebuilt at the top - // of each expert iteration by 8 threads (one per token) — now a - // single `expert_tok_krank` lookup + `sorted_slot` read instead of - // an 8-iter scan. Kept as a per-expert `[BS]` staging array (rather - // than reading the routing table directly) because the inner - // (tok, col) accumulate loop reads it many times per token; a hot - // `[BS]`-sized row keeps that a broadcast. Sentinel 0xFF means - // "this token does not route to the current expert; skip the - // contribution". - uint8_t rank_for_tok[Dims::BS]; + // Per-(expert, token) intra-expert rank, recorded once in routing + // Phase C and read-only afterwards (so any expert's row may be read + // at any point of Phase 4). 0xFF = token does not route to that + // expert. alignas(16) enables the vectorized uint4 0xFF seed. + alignas(16) uint8_t down_rank[Dims::NUM_EXPERTS][Dims::BS]; + // Per-expert routing cache for the up-proj epilogue: for each token, + // the top-k index k with topk_ids_flat[tok*MAX_TOPK + k] == id (0xFF + // if none) and the matching routing weight (0.0f if none — the rw + // value doubles as the routed predicate). Populated at each + // expert's K-loop top; published by the same sync as up_scale. + static constexpr uint32_t UP_RANK_FOR_TOK_LEN = (use_pair_layout::value ? Dims::BS : 0u); + uint8_t up_rank_for_tok[UP_RANK_FOR_TOK_LEN]; + static constexpr uint32_t UP_RW_FOR_TOK_LEN = UP_RANK_FOR_TOK_LEN; + S_element up_rw_for_tok[UP_RW_FOR_TOK_LEN]; + // Snapshot of the PREVIOUS expert's ranks, taken at the calc-warp + // epilogue of expert e (before e+1's K-loop top overwrites + // up_rank_for_tok). The deferred PF writeback of expert e reads + // this during e+1's K-loop. + static constexpr uint32_t UP_RANK_FOR_TOK_PREV_LEN = + (use_pair_layout::value ? Dims::BS : 0u); + uint8_t up_rank_for_tok_prev[UP_RANK_FOR_TOK_PREV_LEN]; } tiny_wgmma_tma; - // ── Aliasing safety static_asserts ───────────────── - // `bf16_in_full` is unioned with `w_wgmma` and `w_down_wgmma` so the BS8 - // TMA+WGMMA Phase-1/2 BF16 input tile shares bytes with the up- and - // down-projection weight tiles (lifetimes are strictly disjoint). Verify at - // compile time that the three views start at the same offset within - // `TinyDataWGMMA_TMA`, so a future layout change that accidentally moves - // `bf16_in_full` out of the inner anonymous union (and therefore breaks - // aliasing) is caught at the build step rather than producing silent SHM - // corruption at runtime. Placed after the struct definition because - // `offsetof` requires a complete type. + // The bf16 input view must alias the weight views exactly — a layout + // change that moves bf16_in_full out of the anonymous union would + // silently corrupt SHM at runtime; catch it at compile time. static_assert(offsetof(TinyDataWGMMA_TMA, bf16_in_full) == offsetof(TinyDataWGMMA_TMA, w_wgmma), "bf16_in_full must alias w_wgmma exactly."); static_assert(offsetof(TinyDataWGMMA_TMA, bf16_in_full) == @@ -957,42 +727,38 @@ struct MoE_SHM { static_assert(Dims::NUM_EXPERTS <= 65535, "Number of experts too high, cannot store as uint16 anymore."); - // act_scale[blk][tok] = max(|x_tok[blk*128..(blk+1)*128-1]|)/448 - // - // Per-token block-wise activation quantization scales for up-projection. - // - // Layout note (bank-conflict avoidance, 2026-05): the inner index is - // `tok` so the row stride along `blk` is `Dims::BS * sizeof(float) = 32 B - // = 8 banks` (for BS=8). The up-proj WGMMA scale-apply broadcasts a - // single `(blk, tok)` pair across the 8 four-lane groups in a warp, so - // every lane-group reads the same `blk` row but a different `tok` - // word. With this layout each `tok ∈ {0,2,4,6}` (resp. {1,3,5,7}) - // lands on a distinct bank within the same row → conflict-free. The - // legacy `[Dims::BS][ACT_SCALE_BLOCKS]` layout had a 64-B row stride - // (= 16 banks); for BS=8 the four toks read from the same warp lane - // mapped to the same bank, producing a 4-way conflict per LDS that - // NCU flagged as the dominant excessive-wavefront source. + // ── Common fields ──────────────────────────────────────────────────────── + + // Per-token per-128-K-block activation quantization scales for the + // up-projection: act_scale[blk][tok] = max(|x_tok[blk*128 .. +128)|)/448. + // [blk][tok] (not [tok][blk]) so the up-proj WGMMA scale-apply broadcast + // reads land on distinct banks. static constexpr uint32_t ACT_BLOCK_SIZE = 128; static constexpr uint32_t ACT_SCALE_BLOCKS = (Dims::HIDDEN_STATES + ACT_BLOCK_SIZE - 1) / ACT_BLOCK_SIZE; S_element act_scale[ACT_SCALE_BLOCKS][Dims::BS]; - // Unique experts active in this batch, with their sorted token ranges. - // Filled by prepare_moe_topk_BS8. + // Launch parity for the sentinel Phase-3→4 handoff (selects which + // temp_act_scale buffer this launch publishes/polls). Written by + // thread 0 in the kernel prologue from spec->launch_flip[blockIdx.x]; + // published to all warps by the prologue __syncthreads. + uint32_t scale_parity; + + // Unique experts active in this batch, ascending id; filled by + // prepare_moe_topk. ExpertRef experts[Dims::NUM_EXPERTS]; std::uint32_t expert_count; - // Flat routing results: [token * MAX_TOPK + k] = expert id / routing weight - // for the k-th selection of that token. Written by topK_BS8. - // MAX_TOPK = 8 covers top_k up to 8. + // Flat routing results: [tok * MAX_TOPK + k] = expert id / routing weight + // of the token's k-th selection. Written by topK. The uint64 + // alignment lets consumers vector-load one token's 8 ids. static constexpr uint32_t MAX_TOPK = 8; alignas(uint64_t) uint16_t topk_ids_flat[(Dims::BS < 8 ? 8 : Dims::BS) * MAX_TOPK]; S_element topk_weights_flat[(Dims::BS < 8 ? 8 : Dims::BS) * MAX_TOPK]; }; /** - * @brief Returns the amount of shared memory necessary to run @c moe_kernel - * with template parameter @p Dims + * @brief Dynamic shared memory required by moe_kernel_topk. */ template __device__ __host__ constexpr size_t get_moe_shmem_size() { @@ -1001,13 +767,19 @@ __device__ __host__ constexpr size_t get_moe_shmem_size() { static_assert(Dims::K <= Dims_Max::K, "Dimension larger than the maximum supported dimension."); static_assert(Dims::NUM_EXPERTS <= Dims_Max::NUM_EXPERTS, "Dimension larger than the maximum supported dimension."); - // Per-block dynamic SHM budget on Hopper (H100) is 228 KB; we target - // 224 KB to leave margin for driver overhead. + // H100/H200 per-block opt-in budget is 228 KB; target 224 KB to leave + // margin for driver overhead. static_assert(sizeof(MoE_SHM) <= 224 * 1024, "MoE_SHM layout exceeds the 224 KB per-block SHM budget."); return sizeof(MoE_SHM); } +constexpr size_t get_moe_max_shmem_size() { return sizeof(MoE_SHM); } + +constexpr size_t get_moe_max_scratchpad_size() { return sizeof(MoEGemmSpec); } + +// ── Warp identity helpers ─────────────────────────────────────────────────── + template inline __device__ bool is_calc_warp() { using CoreDims = MoECoreDims; @@ -1061,27 +833,20 @@ inline __device__ bool is_tma_launcher_thread() { } /** - * @brief Synchronizes the first 256 threads of the calling CUDA block - * - * This is a collective operation that needs to be called by all of the first - * 256 threads in each CUDA block. + * @brief Synchronizes the first 256 threads (the calc warps) of the block. * + * Collective: must be called by all of the first 256 threads. */ template __device__ __forceinline__ void sync_calc_threads() { - // First 256 threads using CoreDims = MoECoreDims; static_assert(CoreDims::CALC_WARP_COUNT * CoreDims::THREADS_PER_WARP == 256, - "Adapt the thread number if sync_calc_threads"); + "Adapt the thread number in sync_calc_threads"); __asm volatile("bar.sync 15, 256;\n"); } /** - * @brief Computes the maximum value within a warp - * - * This is a collective operation. Each thread in a warp needs to call it. - * The resulting maximum value is returned on all threads. - * + * @brief Warp-wide max reduction; the result is returned on all lanes. */ __device__ static inline float warp_reduce_max_float(float value) { for (int i = 16; i >= 1; i /= 2) { diff --git a/csrc/fused_moe/monomoe/src/moe_routing.cuh b/csrc/fused_moe/monomoe/src/moe_routing.cuh index 118e95628ed..7b409ad3e84 100644 --- a/csrc/fused_moe/monomoe/src/moe_routing.cuh +++ b/csrc/fused_moe/monomoe/src/moe_routing.cuh @@ -14,24 +14,25 @@ #include "moe_internal.h" +#define FULL_MASK 0xFFFFFFFFU + namespace monomoe { /** - * @brief Lowest-index expert tie-break for top-k selection. + * @brief Tie-break-by-lowest-expert-index argmax winner. * - * Given each lane's local-argmax (`my_score`, `my_expert`) and the - * warp-wide max score, return the SMALLEST `my_expert` among the lanes - * whose `my_score` equals `warp_max`. This matches the reference - * convention (and CUTLASS): when several experts tie on score, the one - * with the lower index wins. Selecting by lowest *lane* would be wrong - * because lane L owns experts {L, L+32, ...}, so the lowest tied lane can - * hold a higher expert index than a higher tied lane. + * Among all lanes whose `my_max == warp_max`, returns the SMALLEST + * `my_expert` (warp-uniform). Matches the production vLLM `topk_softmax` + * tie-break ("lower expert index wins") — a lowest-lane tie-break would + * pick a different expert because experts map to lanes as `expert % 32`. */ -__device__ static inline uint32_t warp_lowest_tied_expert(float my_score, uint32_t my_expert, - float warp_max) { - uint32_t cand = (my_score == warp_max) ? my_expert : 0xFFFFFFFFU; - for (int off = 16; off >= 1; off /= 2) { - cand = min(cand, __shfl_xor_sync(0xFFFFFFFFU, cand, off, 32)); +__device__ static inline uint32_t warp_min_expert_with_max(float my_max, float warp_max, + uint32_t my_expert) { + uint32_t cand = (my_max == warp_max) ? my_expert : 0xFFFFFFFFu; +#pragma unroll + for (int off = 16; off > 0; off >>= 1) { + uint32_t other = __shfl_xor_sync(FULL_MASK, cand, off); + cand = other < cand ? other : cand; } return cand; } @@ -60,7 +61,7 @@ __device__ static __forceinline__ void warp_softmax_inplace(float* logits) { local_sum += logits[i]; } for (int off = 16; off >= 1; off /= 2) - local_sum += __shfl_xor_sync(0xFFFFFFFFU, local_sum, off, 32); + local_sum += __shfl_xor_sync(FULL_MASK, local_sum, off, 32); float inv_sum = 1.0f / local_sum; #pragma unroll @@ -68,65 +69,33 @@ __device__ static __forceinline__ void warp_softmax_inplace(float* logits) { } /** - * @brief Top-K expert selection for BS <= 8, writing results into shmem. - * - * Computes all K selections via warp reduction and stores them in - * shmem->topk_ids_flat / shmem->topk_weights_flat. - * - * Must be called by calc warps only. + * @brief Top-K expert selection for one token (one warp per token), + * writing shmem->topk_ids_flat / topk_weights_flat. * - * Optimization: only the row max (over all 256 experts) is needed to do - * top-k selection — softmax / sigmoid are both monotonic, so the top-k - * IDs picked by raw `(x - max)` are identical to those picked by - * softmax(x) or sigmoid(x). We therefore defer all `__expf` calls to - * the post-selection step, where only `top_k` (= 8) values are - * exponentiated instead of all `NUM_EXPERTS` (= 256). This cuts - * ~248 expf per warp × 8 warps = ~2000 expf calls per kernel - * invocation, which dominates the routing phase wall clock. + * Calc warps only. * - * For `softmax + renormalize=True` (the Qwen3.5 case) the math - * simplifies further: the softmax denominator `sum_all_exp` cancels - * with the renormalize denominator, so we don't need it at all. - * weight_k = (exp(x_k - max) / sum_all) / (sum_topk / sum_all) - * = exp(x_k - max) / sum_topk_exp + * Fast path: softmax and sigmoid are monotone, so top-k selection runs on + * the raw logits and only the k winners are exponentiated. For + * softmax + renormalize the global denominator cancels against the + * renormalizer (weight_k = exp(x_k - max) / sum_topk_exp), so it is never + * computed. softmax + renormalize=False needs the full denominator and + * falls back to a whole-row softmax. * - * For `softmax + renormalize=False` we still need `sum_all_exp` to - * normalize, which requires all 256 expf calls — that case falls - * back to the original path. */ template -__device__ void topK_BS8(uint32_t top_k, ScoringFunc scoring_func, bool renormalize, - const __nv_bfloat16* __restrict__ router_logits, uint32_t num_tokens, - MoE_SHM* shmem) { - static_assert(Dims::BS <= 8, "Dispatch to incorrect implementation"); +__device__ static __forceinline__ void topK_one_token( + uint32_t warp_idx, uint32_t top_k, ScoringFunc scoring_func, bool renormalize, + const __nv_bfloat16* __restrict__ router_logits, MoE_SHM* shmem) { static_assert(Dims::BS * Dims::NUM_EXPERTS < UINT32_MAX, "Batch size or number of experts too high for uint32 indices."); constexpr uint32_t MAX_TOPK = MoE_SHM::MAX_TOPK; - uint32_t warp_idx = get_calc_warp(); uint32_t tid = get_thread(); - if (warp_idx >= num_tokens) { - if (warp_idx < 8) { - // padding slots — nothing to do for topk path - } - return; - } - - // Per-thread expert slice. Each thread owns experts at indices - // {tid, tid + 32, tid + 64, ...} stepping by warp size, so for - // NUM_EXPERTS == k * 32 every thread holds exactly k entries. - // The `% 32 == 0` invariant lets us replace the previous runtime- - // bounded fill loop (which left `scores[]`/`expert_id[]` on the - // stack frame as local memory and produced uncoalesced LDL - // traffic flagged by the NCU "Local Memory" rule) with a - // statically-bounded `#pragma unroll` loop. ptxas can then - // promote both arrays to registers. static_assert(Dims::NUM_EXPERTS % 32u == 0u, - "topK_BS8 requires NUM_EXPERTS to be a multiple of 32 so " - "every thread owns exactly NUM_EXPERTS/32 experts; this " - "lets the per-thread scores[]/expert_id[] arrays stay " - "in registers (avoiding local-memory spills)."); + "topK requires NUM_EXPERTS to be a multiple of 32 so " + "every thread owns exactly NUM_EXPERTS/32 experts (keeps the " + "per-thread arrays register-resident)."); constexpr uint32_t MAX_PER_THREAD = Dims::NUM_EXPERTS / 32u; float scores[MAX_PER_THREAD]; uint32_t expert_id[MAX_PER_THREAD]; @@ -134,90 +103,69 @@ __device__ void topK_BS8(uint32_t top_k, ScoringFunc scoring_func, bool renormal #pragma unroll for (uint32_t i = 0; i < MAX_PER_THREAD; ++i) { const uint32_t idx = i * 32u + tid; - scores[i] = (float)router_logits[warp_idx * Dims::NUM_EXPERTS + idx]; + const float logit = (float)router_logits[warp_idx * Dims::NUM_EXPERTS + idx]; + // Invalid/padded rows can carry NaN/Inf router scores under CUDA graph + // replay. Treat them as very low scores, but keep them distinct from the + // already-selected sentinel (-inf) so top-k still returns unique experts. + scores[i] = (isnan(logit) || isinf(logit)) ? -FLT_MAX : logit; expert_id[i] = idx; } // ── Slow path: softmax + renormalize=False ───────────────────────────── - // Needs the full softmax denominator (sum over all 256 exp values), so - // we cannot skip the bulk expf calls. Falls back to the original - // warp-cooperative softmax over all experts. if (scoring_func == ScoringFunc::SOFTMAX && !renormalize) { warp_softmax_inplace(scores); + constexpr float EXCLUDED_SCORE = -INFINITY; for (uint32_t k = 0; k < top_k; k++) { - float max_val = -FLT_MAX; - uint32_t max_expert = 0; + float max_val = EXCLUDED_SCORE; + uint32_t max_expert = 0xFFFFFFFFu; #pragma unroll for (uint32_t i = 0; i < MAX_PER_THREAD; i++) { - if (scores[i] > max_val) { + if (scores[i] > max_val || (scores[i] == max_val && expert_id[i] < max_expert)) { max_val = scores[i]; max_expert = expert_id[i]; } } float warp_max = warp_reduce_max_float(max_val); - // Tie-break to the lowest expert index (not the lowest lane). - uint32_t winning_expert = warp_lowest_tied_expert(max_val, max_expert, warp_max); - if (tid == 0) { + uint32_t winning_expert = warp_min_expert_with_max(max_val, warp_max, max_expert); + if (tid == 0u) { shmem->topk_ids_flat[warp_idx * MAX_TOPK + k] = (uint16_t)winning_expert; shmem->topk_weights_flat[warp_idx * MAX_TOPK + k] = warp_max; } #pragma unroll for (uint32_t i = 0; i < MAX_PER_THREAD; i++) { - if (expert_id[i] == winning_expert) scores[i] = -FLT_MAX; + if (expert_id[i] == winning_expert) scores[i] = EXCLUDED_SCORE; } } return; } // ── Fast path: softmax+renormalize=True OR sigmoid (any renorm) ──────── - // - // Selection is done on raw logits for both softmax and sigmoid. - // Both functions are monotonically increasing, so the top-k IDs are - // identical under either the raw-logit or post-activation ordering. - // - // For softmax numerical safety we defer the row_max subtraction to the - // post-selection step: the k=0 winner IS the row maximum, so we - // subtract topk_scores[0] when computing expf — only K values instead - // of all NUM_EXPERTS. This eliminates a full warp reduction + N - // subtractions from the critical path. - - // ── Top-k selection over the (now-shifted-or-raw) logits ────────────── - // Track each selected slot's `score_for_choice` (used for ordering) and - // the expert id. For both paths, `score_for_choice` is the value used - // to pick winners; we'll convert to the actual softmax / sigmoid - // weight in the next step. float topk_scores[MoE_SHM::MAX_TOPK]; uint32_t topk_experts[MoE_SHM::MAX_TOPK]; + constexpr float EXCLUDED_SCORE = -INFINITY; for (uint32_t k = 0; k < top_k; k++) { - float max_val = -FLT_MAX; - uint32_t max_expert = 0; + float max_val = EXCLUDED_SCORE; + uint32_t max_expert = 0xFFFFFFFFu; #pragma unroll for (uint32_t i = 0; i < MAX_PER_THREAD; i++) { - if (scores[i] > max_val) { + if (scores[i] > max_val || (scores[i] == max_val && expert_id[i] < max_expert)) { max_val = scores[i]; max_expert = expert_id[i]; } } float warp_max = warp_reduce_max_float(max_val); - // Tie-break to the lowest expert index (not the lowest lane). - uint32_t winning_expert = warp_lowest_tied_expert(max_val, max_expert, warp_max); + uint32_t winning_expert = warp_min_expert_with_max(max_val, warp_max, max_expert); topk_scores[k] = warp_max; topk_experts[k] = winning_expert; #pragma unroll for (uint32_t i = 0; i < MAX_PER_THREAD; i++) { - if (expert_id[i] == winning_expert) scores[i] = -FLT_MAX; + if (expert_id[i] == winning_expert) scores[i] = EXCLUDED_SCORE; } } - // ── Convert raw selected logits → activation values + (re)normalize ─── - // Only thread 0 does the final write to SHM. All threads on the warp - // hold identical `topk_scores` / `topk_experts` arrays (filled via - // `__shfl_sync` above), so picking thread 0 is arbitrary. if (tid == 0) { if (scoring_func == ScoringFunc::SOFTMAX) { - // Softmax + renormalize=True (the renormalize=False case returned - // earlier). weight_k = exp(x_k - max) / sum_topk_exp. - // topk_scores[0] is the row maximum (k=0 finds the global max). + // softmax + renormalize=True: weight_k = exp(x_k - max) / sum_topk. float row_max = topk_scores[0]; float exp_vals[MoE_SHM::MAX_TOPK]; float sum_exp = 0.0f; @@ -231,9 +179,7 @@ __device__ void topK_BS8(uint32_t top_k, ScoringFunc scoring_func, bool renormal shmem->topk_weights_flat[warp_idx * MAX_TOPK + k] = exp_vals[k] * inv; } } else { - // Sigmoid path: weight_k = 1 / (1 + exp(-x_k)). - // If renormalize, divide by sum of selected sigmoid values (matches - // the original two-step "compute sigmoid → renormalize topk" math). + // Sigmoid: weight_k = sigmoid(x_k), optionally renormalized. float sig_vals[MoE_SHM::MAX_TOPK]; float sum_sig = 0.0f; for (uint32_t k = 0; k < top_k; k++) { @@ -250,132 +196,77 @@ __device__ void topK_BS8(uint32_t top_k, ScoringFunc scoring_func, bool renormal } /** - * @brief Prepares the BS8 tiny path for top-K single-pass. + * @brief Top-K driver: maps calc warps onto tokens and runs + * topK_one_token per (warp, token). + */ +template +__device__ void topK(uint32_t top_k, ScoringFunc scoring_func, bool renormalize, + const __nv_bfloat16* __restrict__ router_logits, uint32_t num_tokens, + MoE_SHM* shmem) { + static_assert(Dims::BS <= 8, "topK supports BS<=8"); + + const uint32_t warp_idx = get_calc_warp(); + if (warp_idx < num_tokens) { + topK_one_token(warp_idx, top_k, scoring_func, renormalize, router_logits, shmem); + } +} + +/** + * @brief Builds the routing tables from topk_ids_flat (warp 0 only). * - * Reads topk_ids_flat (filled by topK_BS8) and builds: - * - experts[0..expert_count-1].id — ordered list of unique expert ids - * active in this batch (first_token/last_token are unused in BS8) - * - expert_count — number of unique experts + * Outputs: + * experts[0..expert_count-1].id — active experts, ascending id + * expert_count + * expert_slot_start[] — first temp_fp8 row per expert + * expert_routed_count[] — routed pairs per expert + * sorted_slot[pair] — temp_fp8 destination row per routed + * (tok, k) pair (expert-sorted layout) + * down_rank[eid][tok] — intra-expert rank (0xFF = unrouted) * - * Token-to-expert assignment is NOT sorted here. The per-expert loop in - * moe_kernel_topk_BS8 scans topk_ids_flat directly for each token. + * Three phases: + * A — vectorized zero of expert_routed_count + 0xFF seed of down_rank, + * then tally via __match_any_sync (each lane's 1–2 pair eids stay + * cached in registers through Phase C). + * B — fused dual warp scan (count prefix + active-expert prefix) → + * expert_slot_start (packed u16 vector stores), experts[] (ascending + * eid by construction: lanes ascend, in-lane entries ascend), and + * expert_count. + * C — intra-expert rank per pair via __match_any_sync + cross-chunk + * carry → sorted_slot and down_rank. */ template -__device__ void prepare_moe_topk_BS8(uint32_t batch_size, uint32_t top_k, - MoE_SHM* __restrict__ shm, - MoEGemmSpec* __restrict__ spec) { - static_assert(Dims::BS <= 8, "Dispatch to incorrect implementation"); - static_assert(use_tma_v, - "BS8 prepare path is TMA-only after the 3-phase rewrite. " - "All instantiated BS8 variants set USE_TMA=true and the " - "kernel asserts use_tma in moe_kernel_topk_BS8 — the " - "non-TMA branch is unreachable."); - // `spec` is currently unused by this helper; suppress the - // unused-parameter warning (kept on the signature for symmetry with - // the other phase helpers and possible future use). - (void)spec; - - // Only warp 0 (threads 0–31) participates; the other calc threads exit - // early and block on the caller's `__syncthreads()`. - if (threadIdx.x >= 32) return; +__device__ void prepare_moe_topk(uint32_t batch_size, uint32_t top_k, + MoE_SHM* __restrict__ shm) { + static_assert(Dims::BS <= 8, "prepare_moe_topk supports BS<=8"); + static_assert(use_tma::value, "BS8 prepare path is TMA-only."); - // ──────────────────────────────────────────────────────────────────────── - // 3-phase prepare for the BS8 TMA+WGMMA path - // ──────────────────────────────────────────────────────────────────────── - // Replaces the previous 6 sub-passes (1a/1b/1c + 2a/2b/2c + 3) with three - // phases. Two structural simplifications drive the speedup: - // - // 1. The 256-bit active-expert bitset (old 1a + 1b) is gone. The - // `expert_routed_count[]` we have to write anyway already encodes - // the same information: `expert_routed_count[eid] > 0` IS the - // active-expert mask. Eliminates 8×reg-OR builds, 8×5 SHFL.B32 - // butterfly OR-reduce, and the lane-0..7 popcount/scan pair. - // - // 2. Each lane caches its (up to 2) routed eids in registers across - // Phases A and C — Phase C's two `load_eid` SHM reads (≤ 64 SHM - // loads warp-wide, on the post-syncthreads critical path) become - // register reads. - // - // Phase A — Tally + cache eids (folds 1a + 2a + 2b) - // * Each lane loads its 1–2 pair eids (eid0, eid1) and keeps them - // in registers. - // * Cooperative zero of `expert_routed_count[256]` (each lane - // writes BLK = 8 contiguous u8 entries). - // * Tally via __match_any_sync — peers sharing an eid form a - // warp peer group; the lowest-id lane writes the popcount. - // - // Phase B — Fused prefix sum + active-expert enumeration (folds 1c + 2c) - // * Each lane sweeps its 8 contiguous expert_routed_count[] entries - // in one 8-iter loop, computing two per-lane locals: - // lane_total = Σ counts (drives expert_slot_start) - // lane_actives = Σ (count > 0) (drives experts[].id) - // plus the two exclusive-prefix arrays count_prefix[8], - // active_prefix[8] in registers. - // * Single dual-value warp scan: 5-step butterfly carries both - // totals through the same shuffle traffic. - // * Each lane writes back 8 entries: - // expert_slot_start[eid] = slot_offset + count_prefix[i] - // and for every active eid (count > 0) appends to experts[]: - // experts[active_offset + active_prefix[i]].id = eid - // * Lane 0 publishes `expert_count` for downstream consumers. - // - // Phase C — Slot assignment (Pass 3, register-fed) - // * Identical math: __match_any_sync intra-chunk rank + cross-chunk - // ballot-shfl carry → sorted_slot[pair]. The two `load_eid` calls - // are gone; eid0/eid1 are already in registers from Phase A. - // - // Ordering invariants preserved end-to-end: - // * `experts[].id` monotonically increasing in eid - // (lanes process in ascending tid; within - // a lane, the 8 entries are in ascending - // eid order). - // * `sorted_slot[pair]` strictly ascending within each expert - // when pairs are enumerated in lex order - // — byte-identical to the v3/v1 semantics. + // Only warp 0 participates; other threads exit and block on the + // caller's __syncthreads(). + if (threadIdx.x >= 32) return; constexpr uint32_t MAX_TOPK = MoE_SHM::MAX_TOPK; - constexpr uint32_t MAX_PAIRS = Dims::BS * MAX_TOPK; // ≤ 64 for BS=8 - constexpr uint32_t BLK = Dims::NUM_EXPERTS / 32; // 8 for E=256 + constexpr uint32_t MAX_PAIRS = Dims::BS * MAX_TOPK; // 64 (BS8) + constexpr uint32_t BLK = Dims::NUM_EXPERTS / 32; static_assert(Dims::NUM_EXPERTS % 32 == 0, "NUM_EXPERTS must be a multiple of 32 for warp blocking of " "expert_routed_count[] / expert_slot_start[]."); - static_assert(MAX_PAIRS <= 64, "Phase A caches up to 2 pair-eids per lane (BS·top_k ≤ 64)."); + static_assert(MAX_PAIRS <= 128, "Phase A caches up to 4 pair-eids per lane (BS * top_k <= 128)."); const uint32_t tid = threadIdx.x; const uint32_t n_pairs = batch_size * top_k; auto* tma_shm = &shm->tiny_wgmma_tma; - // Sentinel-fill the routing-time inverse map `expert_tok_krank[E*BS]` - // to 0xFF ("token does not route to this expert") before the Phase C - // scatter overwrites the routed (eid, tok) cells. Total bytes = - // NUM_EXPERTS * BS. The 32 lanes sweep the array as a strided grid of - // 16-byte STS.128 stores: at step `v` lane `tid` writes vector - // `v*32 + tid` (so the warp covers 512 B contiguously per step, then - // strides on). The STS.128 base is 16-aligned by the `alignas(16)` on - // the array. This runs on warp 0 alongside the rest of the prepare - // phase; the epilogues read the table only after the caller's Phase-2 - // trailing `__syncthreads()`. - { - constexpr uint32_t KRANK_BYTES = Dims::NUM_EXPERTS * Dims::BS; - static_assert(KRANK_BYTES % (32u * 16u) == 0u, - "expert_tok_krank fill assumes NUM_EXPERTS*BS is a multiple " - "of 32 lanes x 16 B (STS.128 per lane)."); - constexpr uint32_t FILL_VECS_PER_LANE = KRANK_BYTES / (32u * 16u); - const uint4 sentinel = make_uint4(0xFFFFFFFFu, 0xFFFFFFFFu, 0xFFFFFFFFu, 0xFFFFFFFFu); - uint4* base = reinterpret_cast(&tma_shm->expert_tok_krank[0]); -#pragma unroll - for (uint32_t v = 0; v < FILL_VECS_PER_LANE; ++v) { - base[v * 32u + tid] = sentinel; - } - } - __syncwarp(); - - // ───────────────── Phase A — Tally + cache eids ───────────────────────── + // ───────────────── Phase A — tally + cache eids ───────────────────────── - // Cache eid0 / eid1 in registers — reused in Phase A tally AND Phase C - // ranking. Out-of-range pairs hold the 0xFFFF sentinel. + // Cache eid0 / eid1 in registers — reused in the Phase-A tally AND the + // Phase-C ranking. Out-of-range pairs hold the 0xFFFF sentinel. const uint32_t p0 = tid; // chunk-0 pair index (lane → pair) const uint32_t p1 = tid + 32u; // chunk-1 pair index + // chunk-2 / chunk-3 pair indices — only meaningful when MAX_PAIRS > 64 + // (BS=16: 4 pairs/lane). On BS=8 they are unused and DCE'd, so no new + // SASS is emitted for the BS8 instantiation. + [[maybe_unused]] const uint32_t p2 = tid + 64u; // chunk-2 pair index + [[maybe_unused]] const uint32_t p3 = tid + 96u; // chunk-3 pair index auto load_pair_eid = [&](uint32_t pair) -> uint16_t { if (pair >= n_pairs) return (uint16_t)0xFFFF; const uint32_t tok = pair / top_k; @@ -384,23 +275,56 @@ __device__ void prepare_moe_topk_BS8(uint32_t batch_size, uint32_t top_k, }; const uint16_t eid0 = load_pair_eid(p0); const uint16_t eid1 = load_pair_eid(p1); + // chunk-2 / chunk-3 eid caches: the SHM loads are gated under + // `MAX_PAIRS > 64u` so BS=8 issues no load and the variables fold to a + // dead sentinel that ptxas eliminates. + [[maybe_unused]] uint16_t eid2 = (uint16_t)0xFFFF; + [[maybe_unused]] uint16_t eid3 = (uint16_t)0xFFFF; + if constexpr (MAX_PAIRS > 64u) { + eid2 = load_pair_eid(p2); + eid3 = load_pair_eid(p3); + } - // Cooperative zero of expert_routed_count[NUM_EXPERTS]. Each lane owns - // BLK = 8 contiguous u8 entries; issue as one STS.64 per lane (32 lanes - // × 8 B = 256 B → 2 SHM transactions) instead of eight STS.U8 (8 - // transactions). `expert_routed_count` is declared `alignas(16)` so - // the per-lane base `tid * BLK` is always 8-byte aligned for BLK=8. - static_assert(BLK == 8u, - "Vectorized zero assumes BLK = 8 (one uint64 per lane). " - "Update the cast width if NUM_EXPERTS / 32 ever changes."); - *reinterpret_cast(&tma_shm->expert_routed_count[tid * BLK]) = 0ull; + // Vectorized zero of expert_routed_count: each lane owns BLK contiguous + // u8 entries; the store width must equal the lane slice (the base is + // only BLK-byte aligned). + static_assert(BLK == 2u || BLK == 4u || BLK == 8u || BLK == 16u, + "Vectorized zero supports BLK in {2,4,8,16} (NUM_EXPERTS in " + "{64,128,256,512}); add a store width for other counts."); + { + auto* zbase = &tma_shm->expert_routed_count[tid * BLK]; + if constexpr (BLK == 2u) { + *reinterpret_cast(zbase) = 0u; + } else if constexpr (BLK == 4u) { + *reinterpret_cast(zbase) = 0u; + } else if constexpr (BLK == 8u) { + *reinterpret_cast(zbase) = 0ull; + } else { // BLK == 16: two u64 (the base is only 8-byte aligned) + reinterpret_cast(zbase)[0] = 0ull; + reinterpret_cast(zbase)[1] = 0ull; + } + } + + // Seed down_rank to the 0xFF "unrouted" sentinel (uint4 stores; the + // array is alignas(16) and NUM_EXPERTS*BS is a multiple of 16). Phase C + // overwrites only the routed cells. + { + constexpr uint32_t DOWN_RANK_BYTES = Dims::NUM_EXPERTS * Dims::BS; + static_assert(DOWN_RANK_BYTES % 16u == 0u, + "down_rank uint4 seed requires NUM_EXPERTS*BS % 16 == 0"); + auto* rbase = reinterpret_cast(&tma_shm->down_rank[0][0]); + const uint4 fill = make_uint4(0xFFFFFFFFu, 0xFFFFFFFFu, 0xFFFFFFFFu, 0xFFFFFFFFu); +#pragma unroll + for (uint32_t i = tid; i < DOWN_RANK_BYTES / 16u; i += 32u) { + rbase[i] = fill; + } + } __syncwarp(); - // Tally via __match_any_sync. For each pair-slot, peers sharing an eid - // form a warp peer group; the lowest-id lane writes the popcount-sized - // increment. Sentinel lanes form their own peer group, but the - // `eid < NUM_EXPERTS` guard suppresses the write. __syncwarp() between - // slots serializes slot-1's RMW against slot-0's stores. + // Tally via __match_any_sync: peers sharing an eid form a peer group; + // the lowest lane writes the popcount. Sentinel lanes form their own + // group but the eid bound suppresses the write. __syncwarp between the + // two chunks serializes chunk-1's RMW against chunk-0's stores. { const uint32_t key = static_cast(eid0); const uint32_t match = __match_any_sync(FULL_MASK, key); @@ -421,26 +345,58 @@ __device__ void prepare_moe_topk_BS8(uint32_t batch_size, uint32_t top_k, } __syncwarp(); } + if constexpr (MAX_PAIRS > 64u) { + { + const uint32_t key = static_cast(eid2); + const uint32_t match = __match_any_sync(FULL_MASK, key); + const uint32_t count = __popc(match); + const uint32_t lowest = __ffs(match) - 1u; + if (eid2 < Dims::NUM_EXPERTS && tid == lowest) { + tma_shm->expert_routed_count[eid2] += static_cast(count); + } + __syncwarp(); + } + { + const uint32_t key = static_cast(eid3); + const uint32_t match = __match_any_sync(FULL_MASK, key); + const uint32_t count = __popc(match); + const uint32_t lowest = __ffs(match) - 1u; + if (eid3 < Dims::NUM_EXPERTS && tid == lowest) { + tma_shm->expert_routed_count[eid3] += static_cast(count); + } + __syncwarp(); + } + } - // ────────── Phase B — Fused prefix sum + active-expert enum ───────────── + // ────────── Phase B — fused prefix sum + active-expert enum ───────────── - // Per-lane sweep over the 8 owned entries. Builds local counts + - // exclusive prefixes for both totals (count and active flag) in one - // pass. `local_counts[i]` is cached so the eid emit pass below - // doesn't re-read SHM. - // - // Bulk-load all 8 u8 counts as a single uint64 (8 B, lane-aligned) - // instead of 8 separate LDS.U8 — one SHM transaction per lane. + // Per-lane sweep over the owned counts: bulk-load them as one vector + // (width == BLK bytes — the lane base is only BLK-byte aligned), build + // both exclusive prefixes (count and active flag) in one pass. uint32_t local_counts[BLK]; - uint32_t count_prefix[BLK]; // exclusive prefix of counts within block - uint32_t active_prefix[BLK]; // exclusive prefix of (count > 0) within block + uint32_t count_prefix[BLK]; + uint32_t active_prefix[BLK]; uint32_t lane_total = 0; uint32_t lane_actives = 0; - const uint64_t packed_counts = - *reinterpret_cast(&tma_shm->expert_routed_count[tid * BLK]); + uint64_t packed_lo = 0, packed_hi = 0; // hi used only for BLK==16 + { + const auto* cbase = &tma_shm->expert_routed_count[tid * BLK]; + if constexpr (BLK == 2u) { + packed_lo = *reinterpret_cast(cbase); + } else if constexpr (BLK == 4u) { + packed_lo = *reinterpret_cast(cbase); + } else if constexpr (BLK == 8u) { + packed_lo = *reinterpret_cast(cbase); + } else { // BLK == 16 + packed_lo = reinterpret_cast(cbase)[0]; + packed_hi = reinterpret_cast(cbase)[1]; + } + } #pragma unroll for (uint32_t i = 0; i < BLK; ++i) { - const uint32_t v = static_cast((packed_counts >> (i * 8u)) & 0xFFu); + const uint64_t src = (i < 8u) ? packed_lo : packed_hi; + const uint32_t sh = (i & 7u) * 8u; + const uint32_t v = static_cast((src >> sh) & 0xFFu); local_counts[i] = v; count_prefix[i] = lane_total; active_prefix[i] = lane_actives; @@ -449,8 +405,7 @@ __device__ void prepare_moe_topk_BS8(uint32_t batch_size, uint32_t top_k, } // Dual-value warp inclusive scan: both totals share the same 5-step - // butterfly traffic. Sequential dependency is on the `if (tid >= off)` - // accumulator only — the two add chains are independent. + // butterfly traffic. uint32_t scan_total = lane_total; uint32_t scan_active = lane_actives; #pragma unroll @@ -462,38 +417,37 @@ __device__ void prepare_moe_topk_BS8(uint32_t batch_size, uint32_t top_k, scan_active += t_active; } } - const uint32_t lane_slot_offset = scan_total - lane_total; // exclusive - const uint32_t lane_active_offset = scan_active - lane_actives; // exclusive - // Total active expert count comes from lane 31's inclusive scan. + const uint32_t lane_slot_offset = scan_total - lane_total; + const uint32_t lane_active_offset = scan_active - lane_actives; const uint32_t expert_count = __shfl_sync(FULL_MASK, scan_active, 31); - // Combined writeback: every lane writes its 8 expert_slot_start entries - // in ascending eid order, and emits an experts[].id entry for each - // active eid. Since lanes process in ascending tid and within a lane - // entries are in ascending eid, the global experts[] enumeration is - // monotonically increasing in eid — same invariant as the old bitset - // path. - // - // The 8 expert_slot_start writes are packed into one STS.128 per lane: - // `expert_slot_start` is u16, BLK = 8, so each lane's slice is exactly - // 16 B and lane base `tid * BLK * 2 = tid * 16` is naturally 16-B - // aligned. Values are bounded by `n_pairs <= 64`, so casting through - // u16 is safe. Sparse `experts[].id` writes stay scalar — their - // targets are non-contiguous across lanes. - uint4 packed_starts; + // Writeback: expert_slot_start as packed u16 vector stores (values are + // bounded by n_pairs <= 64, so the u16 cast is safe; the alignas(16) + // base makes every width naturally aligned), plus a scalar experts[].id + // emit per active eid. Lanes ascend and in-lane entries ascend, so the + // experts[] enumeration is ascending in eid. { - uint32_t lo[8]; + static_assert(BLK == 2u || BLK == 4u || BLK == 8u || BLK == 16u, + "expert_slot_start packed store supports BLK in {2,4,8,16}."); + uint32_t w[8]; #pragma unroll - for (uint32_t i = 0; i < BLK; ++i) { - lo[i] = lane_slot_offset + count_prefix[i]; + for (uint32_t j = 0; j < BLK / 2u; ++j) { + const uint32_t a = lane_slot_offset + count_prefix[2u * j]; + const uint32_t b = lane_slot_offset + count_prefix[2u * j + 1u]; + w[j] = a | (b << 16); + } + auto* dst = reinterpret_cast(&tma_shm->expert_slot_start[tid * BLK]); + if constexpr (BLK == 2u) { + dst[0] = w[0]; + } else if constexpr (BLK == 4u) { + *reinterpret_cast(dst) = make_uint2(w[0], w[1]); + } else if constexpr (BLK == 8u) { + *reinterpret_cast(dst) = make_uint4(w[0], w[1], w[2], w[3]); + } else { // BLK == 16: two uint4 + *reinterpret_cast(dst) = make_uint4(w[0], w[1], w[2], w[3]); + *(reinterpret_cast(dst) + 1) = make_uint4(w[4], w[5], w[6], w[7]); } - // Pack 8 u16 lanes into a uint4 (4 × u32 = 8 × u16). - packed_starts.x = lo[0] | (lo[1] << 16); - packed_starts.y = lo[2] | (lo[3] << 16); - packed_starts.z = lo[4] | (lo[5] << 16); - packed_starts.w = lo[6] | (lo[7] << 16); } - *reinterpret_cast(&tma_shm->expert_slot_start[tid * BLK]) = packed_starts; #pragma unroll for (uint32_t i = 0; i < BLK; ++i) { const uint32_t eid = tid * BLK + i; @@ -505,35 +459,24 @@ __device__ void prepare_moe_topk_BS8(uint32_t batch_size, uint32_t top_k, } __syncwarp(); - // Lane 0 publishes expert_count (used by downstream consumers in the - // up- and down-projection helpers, which iterate `shm->experts[e].id` - // directly for e ∈ [0, expert_count)). if (tid == 0) { shm->expert_count = expert_count; } - // ───────────────── Phase C — Slot assignment ──────────────────────────── - // Identical math to the v3 Pass 3 — see the long comment block in git - // history for the evolution from v1 (single-threaded write_head) to v2 - // (warp-parallel inner serial scan) to v3 (__match_any_sync). The - // only change here is that eid0 / eid1 are register-resident from - // Phase A, eliminating the two `load_eid` SHM reads per lane (≤ 64 - // SHM loads warp-wide on the critical path). + // ───────────────── Phase C — slot assignment ──────────────────────────── + // eid0 / eid1 are register-resident from Phase A. const uint32_t lane_mask = (1u << tid) - 1u; - // Chunk-0 intra-chunk rank. + // Intra-chunk ranks. const uint32_t match0 = __match_any_sync(FULL_MASK, static_cast(eid0)); const uint32_t rank0 = __popc(match0 & lane_mask); - // Chunk-1 intra-chunk rank. const uint32_t match1 = __match_any_sync(FULL_MASK, static_cast(eid1)); const uint32_t rank1_intra = __popc(match1 & lane_mask); - // Chunk-1 cross-chunk carry: for each lane's eid1, count how many - // chunk-0 pairs share that eid. Rotate eid1 through the warp via 32 - // shfl+ballot+popc rounds. Skipped when n_pairs ≤ 32 (no chunk-1 - // pairs to rank). + // Chunk-1 cross-chunk carry: for each lane's eid1, count the chunk-0 + // pairs sharing that eid (32 shfl+ballot+popc rounds). uint32_t rank1_carry = 0; if (n_pairs > 32) { #pragma unroll @@ -544,23 +487,71 @@ __device__ void prepare_moe_topk_BS8(uint32_t batch_size, uint32_t top_k, } } + // Chunk-2 / chunk-3 ranking (BS=16 only, MAX_PAIRS > 64). A pair's + // global rank within its expert's slab is its intra-chunk rank plus the + // count of same-eid pairs in all LOWER-indexed chunks (chunk order is + // pair index order: tid, tid+32, tid+64, tid+96). + [[maybe_unused]] uint32_t rank2_intra = 0; + [[maybe_unused]] uint32_t rank2_carry = 0; + [[maybe_unused]] uint32_t rank3_intra = 0; + [[maybe_unused]] uint32_t rank3_carry = 0; + if constexpr (MAX_PAIRS > 64u) { + const uint32_t match2 = __match_any_sync(FULL_MASK, static_cast(eid2)); + rank2_intra = __popc(match2 & lane_mask); + const uint32_t match3 = __match_any_sync(FULL_MASK, static_cast(eid3)); + rank3_intra = __popc(match3 & lane_mask); + + // Chunk-2 carry: same-eid pairs in chunks 0 and 1. + if (n_pairs > 64) { +#pragma unroll + for (int src = 0; src < 32; ++src) { + const uint32_t q = __shfl_sync(FULL_MASK, static_cast(eid2), src); + const uint32_t b0 = __ballot_sync(FULL_MASK, static_cast(eid0) == q); + const uint32_t b1 = __ballot_sync(FULL_MASK, static_cast(eid1) == q); + if (static_cast(tid) == src) rank2_carry = __popc(b0) + __popc(b1); + } + } + // Chunk-3 carry: same-eid pairs in chunks 0, 1 and 2. + if (n_pairs > 96) { +#pragma unroll + for (int src = 0; src < 32; ++src) { + const uint32_t q = __shfl_sync(FULL_MASK, static_cast(eid3), src); + const uint32_t b0 = __ballot_sync(FULL_MASK, static_cast(eid0) == q); + const uint32_t b1 = __ballot_sync(FULL_MASK, static_cast(eid1) == q); + const uint32_t b2 = __ballot_sync(FULL_MASK, static_cast(eid2) == q); + if (static_cast(tid) == src) rank3_carry = __popc(b0) + __popc(b1) + __popc(b2); + } + } + } + + // Record sorted_slot and down_rank together — `rank` is exactly the + // value the down-proj would otherwise recompute per expert. Each + // (eid, tok) pair is unique (a token's top-k experts are distinct), so + // the writes are race-free. if (p0 < n_pairs && eid0 != 0xFFFF) { - tma_shm->sorted_slot[p0] = static_cast(tma_shm->expert_slot_start[eid0] + rank0); - // Scatter the (eid, tok) → k rank into the routing-time inverse map. - // `p0 = tok*top_k + k`, so k = p0 % top_k and tok = p0 / top_k. - // Top-k selection guarantees distinct experts per token, so - // (eid0, tok) is unique — no write conflict with the p1 store below - // or with any other lane. - const uint32_t tok0 = p0 / top_k; - const uint32_t k0 = p0 - tok0 * top_k; - tma_shm->expert_tok_krank[eid0 * Dims::BS + tok0] = static_cast(k0); + const uint8_t slot0 = static_cast(tma_shm->expert_slot_start[eid0] + rank0); + tma_shm->sorted_slot[p0] = slot0; + tma_shm->down_rank[eid0][p0 / top_k] = static_cast(rank0); } if (p1 < n_pairs && eid1 != 0xFFFF) { - tma_shm->sorted_slot[p1] = + const uint8_t slot1 = static_cast(tma_shm->expert_slot_start[eid1] + rank1_intra + rank1_carry); - const uint32_t tok1 = p1 / top_k; - const uint32_t k1 = p1 - tok1 * top_k; - tma_shm->expert_tok_krank[eid1 * Dims::BS + tok1] = static_cast(k1); + tma_shm->sorted_slot[p1] = slot1; + tma_shm->down_rank[eid1][p1 / top_k] = static_cast(rank1_intra + rank1_carry); + } + if constexpr (MAX_PAIRS > 64u) { + if (p2 < n_pairs && eid2 != 0xFFFF) { + const uint32_t rank2 = rank2_intra + rank2_carry; + const uint8_t slot2 = static_cast(tma_shm->expert_slot_start[eid2] + rank2); + tma_shm->sorted_slot[p2] = slot2; + tma_shm->down_rank[eid2][p2 / top_k] = static_cast(rank2); + } + if (p3 < n_pairs && eid3 != 0xFFFF) { + const uint32_t rank3 = rank3_intra + rank3_carry; + const uint8_t slot3 = static_cast(tma_shm->expert_slot_start[eid3] + rank3); + tma_shm->sorted_slot[p3] = slot3; + tma_shm->down_rank[eid3][p3 / top_k] = static_cast(rank3); + } } } diff --git a/csrc/fused_moe/monomoe/src/moe_scale_inputs.cuh b/csrc/fused_moe/monomoe/src/moe_scale_inputs.cuh index 905bcd378d6..27ff63cc872 100644 --- a/csrc/fused_moe/monomoe/src/moe_scale_inputs.cuh +++ b/csrc/fused_moe/monomoe/src/moe_scale_inputs.cuh @@ -12,7 +12,6 @@ #include #include -#include "moe_grid_barrier.h" #include "moe_interface.h" #include "moe_internal.h" #include "ptx_utils.h" @@ -29,166 +28,42 @@ __device__ static __forceinline__ __nv_bfloat162 mask_NaNs_to_zero(__nv_bfloat16 return type_pun<__nv_bfloat162>(type_pun(xs) & __heq2_mask(xs, xs)); } -// Internal linkage -namespace { - /** - * @brief Struct for keeping a chunk of 8 bfloat16 in registers. - */ -struct BF16x8 { - float4 raw; // Storage for 8 BFloat16 values. Never accessed as fp32. - - /** - * @brief Loads a BF16x8 from memory. - * - * The address @p a must be BF16x8 aligned. - */ - __device__ static BF16x8 load(const A_element* a) { - assert(reinterpret_cast(a) % 16 == 0); - BF16x8 val{*reinterpret_cast(a)}; - return val; - } - - /** - * @brief Stores a BF16x8 to memory. - * - * The address @p a must be BF16x8 aligned. - */ - __device__ void store_to(A_element* a) { - assert(reinterpret_cast(a) % 16 == 0); - *reinterpret_cast(a) = raw; - } - - /** - * @brief Returns bfloat16 0 and 1 as pair. - */ - __device__ __nv_bfloat162 first_pair() const { return type_pun<__nv_bfloat162>(raw.x); } - /** - * @brief Returns bfloat16 2 and 3 as pair. - */ - __device__ __nv_bfloat162 second_pair() const { return type_pun<__nv_bfloat162>(raw.y); } - /** - * @brief Returns bfloat16 5 and 5 as pair. - */ - __device__ __nv_bfloat162 third_pair() const { return type_pun<__nv_bfloat162>(raw.z); } - /** - * @brief Returns bfloat16 6 and 7 as pair. - */ - __device__ __nv_bfloat162 fourth_pair() const { return type_pun<__nv_bfloat162>(raw.w); } - - /** - * @brief Converts 8 Bfloat16 values to FP8 E4M3 in accordance with vLLM's MoE - * activation quantization. - * - * Scales, clamps (incl. NaN replacement), rounds and converts each BFloat16 - * to FP8 E4M3. Scaling is done with float accuracy. Clamping and saturation - * are implemented via __NVSATFINITE semantics of the FP8 conversion. - * - * @param scale Scaling factor to use. - * @returns Eight FP8 E4M3 packed into a uint64_t - */ - __device__ uint64_t to_fp8x8(float scale) const { - // We do not need to actually clamp. Clamping is handled implicitly by the - // satfinite semantics of the float->e4m3 conversion. We only need to - // swallow NaNs. Here, we set them to 0. - __nv_bfloat162 bf0 = mask_NaNs_to_zero(first_pair()); - __nv_bfloat162 bf1 = mask_NaNs_to_zero(second_pair()); - __nv_bfloat162 bf2 = mask_NaNs_to_zero(third_pair()); - __nv_bfloat162 bf3 = mask_NaNs_to_zero(fourth_pair()); - - float2 f0 = __bfloat1622float2(bf0); - float2 f1 = __bfloat1622float2(bf1); - float2 f2 = __bfloat1622float2(bf2); - float2 f3 = __bfloat1622float2(bf3); - - __nv_fp8x4_e4m3 converted0{float4{f0.x * scale, f0.y * scale, f1.x * scale, f1.y * scale}}; - __nv_fp8x4_e4m3 converted1{float4{f2.x * scale, f2.y * scale, f3.x * scale, f3.y * scale}}; - - return type_pun(converted0) | ((uint64_t)type_pun(converted1) << 32); - } -}; - -} // namespace - -/** - * @brief Per-K-tile bf16 → fp8 quantization (single-row BF16 view). - * - * Called by exactly one warp per `(token, k_block)` pair. Each call - * converts 128 bf16 K-values for ONE token into 128 fp8 K-values with - * a per-token-per-128-K-block scale. - * - * Input layout: - * bf16_row[0..127] — contiguous bf16 activations for the - * token slot `tok`, for the current 128-K - * substep. - * - * Output layout (canonical WGMMA K-major): - * fp8_act[kc][tok][ki] — where kc = 0..7, tok = 0..7, ki = 0..15, - * and kc*16 + ki = global K within the tile. - * The helper writes ONLY the slice - * [kc][tok][ki] for the caller-supplied - * `tok`; other tokens at the same k_block - * are written by other warps. - * - * Scale output: - * act_scale_for_step — one fp32 scale value for this (tok, k_block) - * pair. Caller supplies a pointer to the - * `&shmem->act_scale[k_block][tok]` slot. - * - * Thread distribution: 32 threads per warp, each owning 4 K-values - * (4 × 32 = 128 = one full 128-K substep). Warp-reduce finds the - * block max. If `tok >= batch_size`, the warp zero-fills its fp8 slot - * and writes `act_scale = 1.0f` (neutral — the scale-apply will - * multiply by zero via the `as_0X = (tok < batch_size) ? ... : 0.f` - * guard in the up-proj kernel, so this scale value is never consumed). - * - * The canonical fp8 output layout means thread t writes its 4 quantized - * values at - * fp8_act[(col+i)/16][tok][(col+i)%16] - * where col = t * 4 and i in 0..3. With 4 consecutive K-values per - * thread and a 16-wide chunk, all 4 values fall in the same kc. - * - * Refactor note: - * The BF16 view was narrowed from a `[T_TILE=8][128]` 2 KB atom to a - * `[128]` single-row view. This unblocks calling the helper from the - * routing-phase fusion path, where the BF16 source is the full - * tile-major `bf16_in_full[K_BLOCKS_TOTAL][BS][K_STEP_WGMMA]` SHM - * buffer populated by `moe_load_full_bf16_input` — the caller passes - * `bf16_in_full[k_block][token]` directly as a natural `[128]` row - * (no row-stride reinterpretation needed). All FP8 writes and the - * scale-output convention are unchanged — the refactored helper - * still accepts `tok` and writes the same `fp8_act[kc][tok][ki]` - * bytes as before. Existing callers that previously passed - * `slot[kk]` (a `[8][128]` tile) now pass `slot[kk][tok]` (a `[128]` - * row). - * - * @tparam Dims MoE dims. - * @tparam BF16InCols Must be K_STEP_WGMMA (128). - * @tparam Fp8NumChunks Must be K_STEP_WGMMA / 16 (8). - * @tparam Fp8Tok Must be T_TILE (8). - * @tparam Fp8KInner Must be 16. - * @param bf16_row SHM-resident bf16 row for token `tok`, - * for the current 128-K substep. - * @param fp8_act SHM output fp8 tile - * [Fp8NumChunks][T_TILE][Fp8KInner]. - * @param tok Token slot this call is writing. - * @param batch_size Number of real tokens (remaining zero-filled). - * @param act_scale_for_step fp32 destination for this (tok, k_block) - * scale. + * @brief Per-128-K-block bf16 → fp8 quantization for one token. + * + * Called by exactly one warp per (token, k_block) pair: converts the + * token's 128 bf16 K-values into fp8 with one per-(token, block) scale. + * Each of the 32 lanes owns 4 consecutive K-values; a warp reduce finds + * the block max. + * + * Output layout (canonical WGMMA K-major): fp8_act[kc][tok][ki] with + * kc*16 + ki = K within the tile; only the caller's `tok` row is written + * (other tokens are covered by other warps). The token dim may be padded + * to 9 rows (bank-conflict avoidance — see fp8_act_full in + * moe_internal.h); the 9th row is never written. + * + * For `tok >= batch_size` the slot is zero-filled and the scale set to a + * neutral 1.0f (never consumed — the scale-apply zeroes padded tokens). + * + * @param bf16_row SHM bf16 row for this (token, k_block). + * @param fp8_act SHM fp8 output atom [kc][tok][ki]. + * @param tok Token slot to write. + * @param batch_size Real token count. + * @param act_scale_for_step fp32 destination for this pair's scale + * (`&shmem->act_scale[k_block][tok]`). */ template __device__ __forceinline__ void moe_streaming_quantize_k128( const A_element (&bf16_row)[BF16InCols], AQ_element (&fp8_act)[Fp8NumChunks][Fp8Tok][Fp8KInner], std::uint32_t tok, std::uint32_t batch_size, float* __restrict__ act_scale_for_step) { - static_assert(Dims::BS <= 8, "Streaming quantize is for BS<=8"); + static_assert(Dims::BS <= 8, "Streaming quantize supports BS<=8"); static_assert(BF16InCols == 128, "bf16_row must have 128 K cols"); static_assert(Fp8NumChunks == 8, "fp8_act must have 8 K-chunks of 16"); - static_assert(Fp8Tok == 8 || Fp8Tok == 9, - "fp8_act must have 8 (legacy) or 9 (kc-padded for " - "bank-conflict avoidance) token rows; only the first " - "8 are written, the 9th — when present — is unused " - "padding that breaks the 128-byte kc stride"); + static_assert(Fp8Tok == MoECoreDims::T_TILE || Fp8Tok == MoECoreDims::T_TILE + 1, + "fp8_act must have T_TILE or T_TILE+1 (kc-padded) token " + "rows; only the first T_TILE are written. T_TILE is 8 for " + "BS<=8, so this resolves to 8/9 on the BS8 path."); static_assert(Fp8KInner == 16, "fp8_act inner dim must be 16"); const std::uint32_t thread = get_thread(); // 0..31 @@ -222,7 +97,11 @@ __device__ __forceinline__ void moe_streaming_quantize_k128( float local_max = fmaxf(fmaxf(fabsf(r0), fabsf(r1)), fmaxf(fabsf(r2), fabsf(r3))); float blk_max = warp_reduce_max_float(local_max); - if (blk_max < __FLT_MIN__) blk_max = 1.f; + // Eps-clamp tiny maxima: blk_max slightly above FLT_MIN still overflows + // blk_inv_scale (448/blk_max > FLT_MAX for blk_max < ~1.32e-36), NaN-ing + // the whole block after the fp8 cast. 1e-10 matches vLLM's group-quant + // eps. + blk_max = fmaxf(blk_max, 1e-10f); const float blk_act_scale = blk_max * FP8_MAX_INV; const float blk_inv_scale = FP8_MAX / blk_max; @@ -243,75 +122,20 @@ __device__ __forceinline__ void moe_streaming_quantize_k128( } /** - * @brief Phase-2 routing-window BF16 → FP8 quantization (BS8 TMA+WGMMA only). - * - * Called from `moe_kernel_topk_BS8`'s Phase-2 dispatch on warps 1..11 - * (warp 0 runs `prepare_moe_topk_BS8` instead). Distributes the - * `BS * K_BLOCKS_TOTAL = 128` (token, k_block) quantization tasks - * across the 11 participating warps using a stride-11 partition over - * the linear pair index `i = token * K_BLOCKS_TOTAL + k_block`. Each - * warp-owned pair invokes `moe_streaming_quantize_k128` exactly - * once with a single-row BF16 view onto the prefetched - * `bf16_in_full[k_block][token]`. - * - * The BF16 source uses the tile-major - * `[K_BLOCKS_TOTAL][BS][K_STEP_WGMMA]` SHM layout populated by the - * Phase-1 routing-window TMA (`moe_load_full_bf16_input`). Each - * K-substep slot is a self-contained 2 KB region whose bytes match - * the activation TMA's compact `boxDim = (128, 8)` write layout — - * see the doc comment on `TinyDataWGMMA_TMA::bf16_in_full` in - * `moe_internal.h` for the rationale. - * - * Caller contract (NOT enforced inside the helper): - * 1. The caller MUST gate warp 0 OUT of this call. Warp 0 runs - * `prepare_moe_topk_BS8` concurrently and is also gated out of - * the `bar_rwin` wait described below. - * 2. The caller MUST wait on the routing-window mbarrier - * (`tiny_wgmma_tma.bar_rwin`) on every warp 1..11 thread before - * invoking this helper. Reading `bf16_in_full` before the wait - * succeeds is a data race against the in-flight Phase-1 TMA load. - * 3. The caller MUST emit a block-wide `__syncthreads()` AFTER this - * helper returns to publish the FP8 atom + scale writes to all - * warps before the Phase-3 up-projection K-loop reads them. - * 4. Ragged batches (`token >= batch_size`) are handled inside this - * helper via the existing zero-fill + scale = 1.0f path of - * `moe_streaming_quantize_k128`. - * - * Scope: this helper is only valid when - * `Dims::BS <= 8` AND the call site is on the BS8 TMA+WGMMA path. - * The static_assert below makes miss-instantiation a build error. - * - * Work distribution: warp `w ∈ [1, 12)` owns pair indices - * { i ∈ [0, BS * K_BLOCKS_TOTAL) : (i % 11) == (w - 1) }. - * With `BS = 8`, `K_BLOCKS_TOTAL = 16`, `PAIRS_TOTAL = 128`, and 11 - * warps, every pair is owned by exactly one warp. Warp 0 owns no - * pair. Imbalance is at most one extra pair per warp (~9%), which - * is acceptable given the alternative is wasting warps. - * - * @tparam Dims MoE dims. - * @tparam KBlocks Outer extent of `bf16_in_full` - * (= K_BLOCKS_TOTAL). - * @tparam Bs Middle extent of `bf16_in_full` (= Dims::BS). - * @tparam KStep Inner extent of `bf16_in_full` (= K_STEP_WGMMA - * = 128). - * @tparam Fp8KBlocks Outer extent of `fp8_act_full` (= K_BLOCKS_TOTAL). - * @tparam Fp8NumChunks Must be 8 (= K_STEP_WGMMA / FP8_ACT_K_CHUNK). - * @tparam Fp8Tok Must be 8 (= T_TILE). - * @tparam Fp8KInner Must be 16 (= FP8_ACT_K_CHUNK). - * @tparam ScaleBs Outer extent of `act_scale` (= Dims::BS). - * @tparam ScaleKBlocks Inner extent of `act_scale` (= ACT_SCALE_BLOCKS - * = HIDDEN_STATES / 128). - * - * @param bf16_in_full SHM-resident BF16 input tile populated by the - * Phase-1 routing-window TMA load, shaped - * `[K_BLOCKS_TOTAL][BS][K_STEP_WGMMA]`. - * @param fp8_act_full SHM-resident FP8 output, single-buffer indexed - * by `k_block`. - * @param act_scale Per-token per-128-K-block FP8 scales. Lives - * in the `MoE_SHM` common region (next to the - * routing scratchpad). - * @param batch_size Real token count (≤ Dims::BS); ragged tokens - * get the helper's zero-fill + scale = 1.0f path. + * @brief Phase-2 routing-window BF16 → FP8 quantization (warps 1..11). + * + * Distributes the BS * K_BLOCKS_TOTAL (token, k_block) quantization tasks + * across the 11 participating warps (stride-11 over the linear pair + * index; warp 0 runs prepare_moe_topk instead). Each pair invokes + * moe_streaming_quantize_k128 once with a single-row view onto the + * prefetched tile-major `bf16_in_full[k_block][token]`. + * + * Caller contract (enforced at the call site in moe.cu): + * 1. Gate warp 0 OUT of this call. + * 2. Wait on bar_rwin on every warp 1..11 thread first — reading + * bf16_in_full earlier races the in-flight Phase-1 TMA. + * 3. Emit a block-wide __syncthreads() AFTER this returns to publish + * the FP8 atoms + scales before Phase 3 reads them. */ template ; - // Scope guard — BS8 TMA+WGMMA only. - static_assert(Dims::BS <= 8, "routing_phase_quantize is BS8-only"); - // 128-K SWZ128 atoms per token along K (= HIDDEN_STATES / 128). 16 - // for Qwen3.5. This is the same constant declared as - // TinyDataWGMMA_TMA::K_BLOCKS_TOTAL; we recompute it locally so the - // helper does not need to friend that struct. + static_assert(Dims::BS <= 8, "routing_phase_quantize supports BS<=8"); constexpr std::uint32_t K_BLOCKS_TOTAL = Dims::HIDDEN_STATES / CoreDims::K_STEP_WGMMA; - static_assert(KBlocks == K_BLOCKS_TOTAL, - "bf16_in_full outer extent must be K_BLOCKS_TOTAL for BS8"); - static_assert(Bs == Dims::BS, "bf16_in_full middle extent must be Dims::BS for BS8"); + static_assert(KBlocks == K_BLOCKS_TOTAL, "bf16_in_full outer extent must be K_BLOCKS_TOTAL"); + static_assert(Bs == Dims::BS, "bf16_in_full middle extent must be Dims::BS"); static_assert(KStep == CoreDims::K_STEP_WGMMA, "bf16_in_full inner extent must be K_STEP_WGMMA (128)"); static_assert(Fp8NumChunks == 8, "fp8_act_full middle dim must be 8"); static_assert(Fp8Tok == CoreDims::T_TILE || Fp8Tok == CoreDims::T_TILE + 1, - "fp8_act_full token dim must be T_TILE (legacy) or " - "T_TILE+1 (padded layout that breaks the 128-byte kc " - "stride to avoid bank conflicts on the routing-quantize " - "STS — see comment on `MoE_SHM::TinyDataWGMMA_TMA::" - "fp8_act_full` for the design)"); + "fp8_act_full token dim must be T_TILE or T_TILE+1 (padded)"); static_assert(Fp8KInner == 16, "fp8_act_full inner dim must be 16"); static_assert(ScaleBs == Dims::BS, "act_scale inner extent must be Dims::BS"); - static_assert(Fp8KBlocks == K_BLOCKS_TOTAL, - "fp8_act_full outer extent must be K_BLOCKS_TOTAL for BS8"); + static_assert(Fp8KBlocks == K_BLOCKS_TOTAL, "fp8_act_full outer extent must be K_BLOCKS_TOTAL"); static_assert(ScaleKBlocks == K_BLOCKS_TOTAL, "act_scale outer extent must be K_BLOCKS_TOTAL"); constexpr std::uint32_t PAIRS_TOTAL = Dims::BS * K_BLOCKS_TOTAL; - // Warps 1..11 participate (warp 0 runs prepare_moe_topk_BS8). constexpr std::uint32_t NUM_QUANT_WARPS = 11u; - const std::uint32_t warp = get_any_warp(); // ∈ [1, 12) - // Defense-in-depth: warp 0 must be gated out by the caller. Failing - // this assert at runtime would mean warp 0 also wrote some pair — - // since `w_idx = warp - 1u` would underflow, we'd partition the work - // wrong. This is checked in the caller's `if (warp == 0) { ... } - // else { routing_phase_quantize(...) }` dispatch. + const std::uint32_t warp = get_any_warp(); // in [1, 12) assert(warp >= 1u && warp < 12u); - const std::uint32_t w_idx = warp - 1u; // ∈ [0, 11) + const std::uint32_t w_idx = warp - 1u; -// Stride-NUM_QUANT_WARPS partition over the linear pair index. -// `#pragma unroll 1` keeps the loop body small — each iteration is -// already a moe_streaming_quantize_k128 call which is __forceinline. #pragma unroll 1 for (std::uint32_t i = w_idx; i < PAIRS_TOTAL; i += NUM_QUANT_WARPS) { const std::uint32_t token = i / K_BLOCKS_TOTAL; const std::uint32_t kblk = i % K_BLOCKS_TOTAL; - // Tile-major BF16 source: `bf16_in_full[kblk][token]` is the - // natural `[K_STEP_WGMMA = 128]` row written by the Phase-1 TMA's - // compact 2 KB box for this K-substep. No row-stride - // reinterpretation is needed — the array reference type already - // matches the helper's `[128]` row signature. const auto& bf_row = bf16_in_full[kblk][token]; - - // FP8 view for this k_block: fp8_act_full[kblk] — same - // [kc][tok][ki] shape the helper writes into. The helper's `tok` - // argument selects which token slot to write FP8 bytes into; other - // tokens at the same k_block are written by other warps owning - // other pairs. auto& fp8_atom = fp8_act_full[kblk]; moe_streaming_quantize_k128(bf_row, fp8_atom, /*tok=*/token, batch_size, diff --git a/csrc/fused_moe/monomoe/src/moe_up_projection.cuh b/csrc/fused_moe/monomoe/src/moe_up_projection.cuh index 3ee40fd8176..16bb4f5fb85 100644 --- a/csrc/fused_moe/monomoe/src/moe_up_projection.cuh +++ b/csrc/fused_moe/monomoe/src/moe_up_projection.cuh @@ -10,533 +10,291 @@ #include #include -#include "moe_down_projection.cuh" #include "moe_interface.h" #include "moe_internal.h" #include "moe_tma.h" #include "ptx_utils.h" -// Phase 3 up-projection — `moe_up_projection_BS8_..._tma` -// (docs/design_docs/monomoe_kernel.md §1/§5/§6). It -// streams fp8 weight tiles via a single TMA launcher (warp 8 lane 0) into -// double-buffered SHM (TinyDataWGMMA_TMA layout, see moe_internal.h) and the -// calc warps consume them via chained `wgmma.mma_async`. Per-function and -// per-line specifics are documented inline below. - namespace monomoe { /** - * @brief Load this block's slice of block-wise up-projection scales into SHM. + * @brief Async (cp.async) per-expert up-projection block-scale prefetch. + * + * Issues the expert's block-scale tile as non-blocking 4-byte cp.async + * copies so the cold-miss DRAM latency overlaps the previous expert's + * K-loop instead of sitting exposed at the cross-expert boundary. The + * caller must cp_async_commit_group() after issuing and drain with + * cp_async_wait_group<0>() before the values are read. * - * `base_row_up` is the first weight row (in the lower half of the 2*N rows) - * owned by this block, i.e. `base_row_up ∈ [0, N)` with 8-row granularity. - * This lets callers decouple the scale fetch from `blockIdx.x` — needed - * by the two-expert-group BS8 design where both groups reuse the same - * row-tile layout but with different blockIdx ranges. + * `base_row_up` is the first weight row (in the lower, gate half of the + * 2*N rows) owned by this block. Prefetch-warp 0 only; the 32-strided + * loop covers tiles larger than one warp (TILE = 2 * UP_SCALE_COLS, e.g. + * 48 for K=3072 — a plain `thread < TILE` guard would silently drop the + * upper up-half scales). */ template -__device__ inline void moe_request_up_scale_for_row(const S_element* __restrict__ expert_scales_up, - std::uint32_t id, unsigned base_row_up, - S_element* __restrict__ dest) { - constexpr uint32_t COLS = Dims::UP_SCALE_COLS; // e.g. 16 for K=2048 +__device__ inline void moe_prefetch_up_scale_for_row_async( + const S_element* __restrict__ expert_scales_up, std::uint32_t id, unsigned base_row_up, + S_element* __restrict__ dest) { + constexpr uint32_t COLS = Dims::UP_SCALE_COLS; constexpr uint32_t TILE = 2 * COLS; const unsigned thread = get_thread(); const unsigned warp = get_prefetch_warp(); - // Only the first prefetch warp loads the scales — 32 scalars total for - // Qwen3.5 (2×16). Synchronous shared-memory writes are fine; we don't - // need async copy for 128 bytes. - if (warp == 0 && thread < TILE) { - uint32_t rb_local = thread / COLS; // 0 → low half, 1 → upper half - uint32_t kb = thread % COLS; - uint32_t row = base_row_up + rb_local * Dims::N; - uint32_t rb_global = row / Dims::BLOCK_SCALE_ROW; - dest[thread] = expert_scales_up[id * Dims::UP_SCALE_ROWS * Dims::UP_SCALE_COLS + - rb_global * Dims::UP_SCALE_COLS + kb]; - } -} - -/////////////////////////////////////////////////////////////////////////////// -// -// moe_up_projection_BS8_allexperts_wgmma_tma -// -// TMA+WGMMA up-projection for BS<=8. Only variant of the BS8 up-proj -// kernel: the cp.async reference path has been removed. Replaces the -// prefetch-warp `cp.async` loaders for the fp8 expert-weight tile with -// `cp.async.bulk.tensor.2d` issued by a single TMA launcher thread -// (warp 8, lane 0). Completion is signalled via SHM mbarrier `bar_w[2]`; -// consumer warps wait with `mbarrier.try_wait.parity` instead of -// `cuda::pipeline_consumer_wait_prior`. The activation operand is -// sourced from `fp8_act_full` (populated by Phase 1 + Phase 2 of -// `moe_kernel_topk_BS8`); no per-K-step bf16-input TMA or `bar_a` arm -// fires from this helper. -// -// Descriptors are built host-side in the torch binding wrapper and passed -// to the top-level kernel as `__grid_constant__ CUtensorMap const` -// parameters. At the device-side inlined helper boundary (this function), -// they appear as `CUtensorMap const&` — the `__grid_constant__` qualifier -// only applies at the kernel-function boundary. -// - -// ── Per-(token, lane) SiLU + fp8 quantization + writeback body ───────── -// -// Factored out of the up-proj epilogue so the same body can run -// (a) on calc warps inline for the LAST expert in a block's per-expert -// loop (no future iter-0 to defer to) and (b) on prefetch warps as -// "deferred work for the previous expert" at iter-0 of the next -// expert, overlapped with calc warps' WGMMA. The two paths differ -// only in the (warp → tok) mapping, not in the per-(tok, lane) work. -// -// Caller contract: -// * `wgmma_out` MUST have been written by the producing expert's -// end-of-K-loop final_d store and published to the calling warps. -// - Calc-warp inline path (last expert): the `__syncthreads()` -// AFTER the wgmma_out write covers this. -// - Deferred prefetch path (non-last experts): the same sync — -// which sits at the bottom of expert e's loop body — also gates -// iter-0 of expert e+1 where this helper is invoked. -// * `lane` MUST be in [0, 32); `tok` MUST be in [0, BS). Out-of- -// range tokens must be filtered by the caller. -// * All 32 lanes of the warp MUST call this in lockstep with the -// same `tok` so the warp-reduce in the body sees all 64 cols. -// * `id` is the producing expert's id (the one whose final_d sits -// in `wgmma_out`), NOT necessarily the current iter's expert. -// -// Hazard: writes only `spec->temp_fp8` / `spec->temp_act_scale` (GM) -// and reads `wgmma_out` + `shmem->topk_ids_flat` + `shm->sorted_slot` -// (SHM). No writes to SHM that calc warps touch in the K-loop, so -// the prefetch-warp variant runs concurrently with calc warps' iter-0 -// WGMMA without contention. -template -__device__ __forceinline__ void up_silu_quant_writeback_one_token( - MoE_SHM* __restrict__ shmem, MoEGemmSpec* __restrict__ spec, - typename MoE_SHM::TinyDataWGMMA_TMA* __restrict__ shm, std::uint32_t id, - std::uint32_t tok, std::uint32_t col_in_half, std::uint32_t lane, std::uint32_t base_row_up, - std::uint32_t effective_bid, std::uint32_t top_k, std::uint32_t batch_size) { - constexpr std::uint32_t MAX_TOPK = MoE_SHM::MAX_TOPK; - - // Uniform-across-warp: find this token's top-K match for the - // current expert. All 32 lanes of the warp agree on these. - bool store = false; - float rw = 0.f; - std::uint32_t dest_row = 0; - if (tok < batch_size) { - // Single lookup into the routing-time inverse map - // `expert_tok_krank[id][tok]` (built once by `prepare_moe_topk_BS8`, - // see moe_internal.h) — replaces the per-expert 8-iter scan over - // `topk_ids_flat` that both the inline and deferred paths used to - // run. A valid `k` yields the routing weight and the fp8 writeback - // row; sentinel 0xFF means this token does not route to expert `id`. - const uint8_t k = shm->expert_tok_krank[id * Dims::BS + tok]; - if (k != 0xFFu) { - store = true; - rw = shmem->topk_weights_flat[tok * MAX_TOPK + k]; - const std::uint32_t pair = tok * top_k + k; - dest_row = shm->sorted_slot[pair]; - } - } - - // Compute val1 / val2 on every lane of the warp (needed so that the - // subsequent warp-reduce sees all 64 cols of this up-block). - const float gate1 = shm->partial_result.wgmma_out[col_in_half][tok]; - const float up1 = shm->partial_result.wgmma_out[col_in_half + 32][tok]; - const float gate2 = shm->partial_result.wgmma_out[col_in_half + 64][tok]; - const float up2 = shm->partial_result.wgmma_out[col_in_half + 96][tok]; - - float val1 = rw * up1 * gate1 / (1.0f + __expf(-gate1)); - float val2 = rw * up2 * gate2 / (1.0f + __expf(-gate2)); - - const std::uint32_t out_col_1 = base_row_up + col_in_half; - const std::uint32_t out_col_2 = base_row_up + 32 + col_in_half; - const bool write1 = store && (out_col_1 < Dims::N); - const bool write2 = store && (out_col_2 < Dims::N); - - if (!write1) val1 = 0.f; - if (!write2) val2 = 0.f; - - // Warp-reduce max(|val1|, |val2|) across the 32 lanes → max over all - // 64 output cols of this up-block for this token. - float local_max = fmaxf(fabsf(val1), fabsf(val2)); - float block_max = warp_reduce_max_float(local_max); - if (block_max < __FLT_MIN__) block_max = 1.0f; - - constexpr float FP8_MAX = 448.0f; - constexpr float FP8_MAX_INV = 1.0f / 448.0f; - const float block_scale = block_max * FP8_MAX_INV; - const float inv_scale = FP8_MAX / block_max; - - const AQ_element q1 = (AQ_element)(val1 * inv_scale); - const AQ_element q2 = (AQ_element)(val2 * inv_scale); - - if (store && tok < batch_size) { - if (write1) { - spec->temp_fp8[dest_row * Dims::N + out_col_1] = q1; - } - if (write2) { - spec->temp_fp8[dest_row * Dims::N + out_col_2] = q2; - } - if (lane == 0) { - constexpr std::uint32_t SCALE_COLS = - MoEGemmSpec::TEMP_ACT_SCALE_COLS; // = Dims::N / 64 - spec->temp_act_scale[dest_row * SCALE_COLS + effective_bid] = block_scale; + if (warp == 0) { + for (uint32_t i = thread; i < TILE; i += 32u) { + uint32_t rb_local = i / COLS; // 0 → gate half, 1 → up half + uint32_t kb = i % COLS; + uint32_t row = base_row_up + rb_local * Dims::N; + uint32_t rb_global = row / Dims::BLOCK_SCALE_ROW; + const S_element* src = &expert_scales_up[id * Dims::UP_SCALE_ROWS * Dims::UP_SCALE_COLS + + rb_global * Dims::UP_SCALE_COLS + kb]; + cp_async_cg_4(&dest[i], src); } } } +/** + * @brief Up-projection for BS <= 8, single-atom interleaved layout + * (UP_COL_HALVES == 1). + * + * TMA + WGMMA pipeline; see docs/design_docs/monomoe_kernel.md "Phase 3 — up-projection". The + * weight tensor must be pre-interleaved in Python + * (interleave_for_tma_wgmma_up_v2) so one 128×128 TMA fetches a full WGMMA + * A-tile in the gate/up pair layout. The activation operand comes from + * `fp8_act_full`, produced once per launch by Phase 2. + * + * Entry contract (established by moe_kernel_topk_impl): + * * bar_w[*] initialized and release-fenced; slot 0 NOT pre-armed (this + * helper primes the pipeline for expert_start; for later experts the + * previous expert's cross-expert stitch does). + * * fp8_act_full / act_scale populated and published by the Phase-2 + * trailing __syncthreads(). + */ template -__device__ inline void moe_up_projection_BS8_allexperts_wgmma_tma( +__device__ inline void moe_up_projection_allexperts_wgmma_tma( const A_element* __restrict__ activations_in, const W_element* __restrict__ expert_weights_up, const S_element* __restrict__ expert_scales_up, std::uint32_t top_k, std::uint32_t batch_size, MoEGemmSpec* __restrict__ spec, MoE_SHM* __restrict__ shmem, CUtensorMap const& up_weights_desc, CUtensorMap const& activations_desc, std::uint32_t up_block_idx = 0xffffffffu, std::uint32_t expert_start = 0, std::uint32_t expert_stride = 1) { - static_assert(Dims::BS <= 8); + static_assert(Dims::BS <= 8, "allexperts up-proj supports BS<=8."); using CoreDims = MoECoreDims; - // `activations_in` / `expert_weights_up` are retained on the parameter - // list for signature parity with the `cp.async` reference but are not - // dereferenced on the TMA path — all GM reads go through the two TMA - // descriptors. + // All GM reads go through the TMA descriptors; the raw pointers stay on + // the signature for parity with the kernel interface. (void)activations_in; (void)expert_weights_up; - // Caller contract: - // * The Phase-1 routing-window TMA (in `moe.cuh`) has already - // fetched the full BF16 input tile into `bf16_in_full`. - // * Phase 2 has run `routing_phase_quantize` and a block-wide - // `__syncthreads()`, so `fp8_act_full[k_block]` and - // `act_scale[token][k_block]` are visible to every calc warp - // for `k_block in [0, K_BLOCKS_TOTAL)`. - // * `bar_w[0..1]` have been initialized and release-fenced. - // - // Stage A pipeline: - // * Pre-loop: helper arms bar_w[0] + TMAs w[0] of expert_start at k=0. - // * K-loop: iter s waits bar_w[s%2], runs WGMMA + - // scale-apply (B operand from `fp8_act_full`), and the - // launcher arms the NEXT slot's bar_w + weight TMAs - // (intra-expert s+1 or next expert's k=0 stitch). - // * No bar_a, no bf16 TMAs, no QUANT half, no QUANT/COMPUTE - // __syncthreads() — the activation operand is already in - // `fp8_act_full` for the entire K range. - - // ── Compile-time constants (v1) ───────────────────────────────────── - // Byte-for-byte mirror of the `cp.async` reference variant's constants - // so that SHM layouts, WGMMA descriptors, and K-step sizing remain - // identical across the two paths (design P1/P2). - constexpr uint32_t W_UP_M = CoreDims::W_UP_TILE_WGMMA; // 128 - constexpr uint32_t K_STEP_WGMMA = CoreDims::K_STEP_WGMMA; // 128 - constexpr uint32_t K_STEP = CoreDims::K_STEP_UP; // 128 / 256 - constexpr uint32_t K_SUBSTEPS = CoreDims::K_SUBSTEPS_UP; // 1 / 2 - constexpr uint32_t K_TILES = CoreDims::K_TILES_UP; // K/K_STEP + constexpr uint32_t W_UP_M = CoreDims::W_UP_TILE_WGMMA; // 128 + constexpr uint32_t K_STEP_WGMMA = CoreDims::K_STEP_WGMMA; // 128 + constexpr uint32_t K_STEP = CoreDims::K_STEP_UP; + constexpr uint32_t K_SUBSTEPS = CoreDims::K_SUBSTEPS_UP; + constexpr uint32_t K_TILES = CoreDims::K_TILES_UP; constexpr uint32_t WGMMAS_PER_SUBSTEP = CoreDims::WGMMAS_PER_STEP; // 4 - constexpr uint32_t UP_SCALE_COLS = Dims::UP_SCALE_COLS; // 16 - - // Descriptor strides for 128×128 Major::K B128-swizzled A operand. - // - // The TMA hardware applies the 8-row × 128-byte core-matrix XOR - // swizzle at write time, so each 1024-B atom holds one 8-row M-block. - // CUTLASS Major::K B128 layout: - // LBO = 16 B (one K-core-matrix within the 1024-B atom) - // SBO = 1024 B (next M-block atom) - // swizzle_mode = 1 - // The Python pre-interleave repacks gate/up row stripes so that a - // single 128x128 TMA fetches the full WGMMA A-tile; it does NOT - // apply the canonical core-matrix byte permutation (TMA does that). + constexpr uint32_t UP_SCALE_COLS = Dims::UP_SCALE_COLS; + // Weight-TMA lookahead depth + derived arm distance (see MoECoreDims). + constexpr uint32_t SLOTS = CoreDims::UP_W_SLOTS; + constexpr uint32_t ARM_DISTANCE = CoreDims::UP_ARM_DISTANCE; + + // A operand: 128×128 Major::K B128-swizzled weight tile. The TMA + // hardware applies the core-matrix XOR swizzle at write time; the + // matching CUTLASS strides are LBO=16 (K-core-matrix within the 1024-B + // atom), SBO=1024 (next M-atom), swizzle=1. constexpr uint64_t A_LBO = 16ULL; constexpr uint64_t A_SBO = 1024ULL; constexpr uint32_t A_SWIZZLE = 1u; - // B operand (K-major, N=8): 1 N-block, LBO between K-core-matrices. - // Always SWIZZLE_NONE — the activation tile is 8-token × 128-K bf16 - // and small enough that bank-conflict cost is bounded. - // - // `B_LBO` = bytes between successive 8-row × 16-byte WGMMA core - // matrices along K = the byte stride between successive kc atoms in - // `fp8_act_full`'s `[FP8_NUM_CHUNKS][T_TILE_PADDED][FP8_K_CHUNK]` - // per-kblk layout (see comment on `fp8_act_full` in `moe_internal.h` - // for the kc-padding design). The pad widens each kc atom from 128 - // B (T_TILE=8) to 144 B (T_TILE_PADDED=9), and the 9th token row of - // every kc atom is unused — the WGMMA core matrix is still rows - // [0..7] × bytes [0..15] (= 128 B contiguous) at the head of each - // atom, and `B_LBO = 144` steps over the unused 9th row to land on - // the next kc atom's core matrix. + // B operand: fp8 activations from fp8_act_full, SWIZZLE_NONE. LBO steps + // between successive 16-B K-chunks; the padded 9-token-row layout makes + // that 9 * 16 = 144 B (the 9th row is skipped — see fp8_act_full). constexpr uint64_t B_LBO = static_cast(MoE_SHM::TinyDataWGMMA_TMA::FP8_ACT_T_TILE_PADDED) * - static_cast(MoE_SHM::TinyDataWGMMA_TMA::FP8_ACT_K_CHUNK); // 9 × 16 = - // 144 B - constexpr uint64_t B_SBO = B_LBO; // unused (only 1 N-block for N=8) + static_cast(MoE_SHM::TinyDataWGMMA_TMA::FP8_ACT_K_CHUNK); + // B_SBO = stride between adjacent WGMMA N core matrices (8 tokens each). + // BS<=8: the m64n8k32 issue has a single N core matrix, so the hardware + // never consumes SBO; keep it equal to B_LBO so the emitted descriptor + // immediate stays byte-identical to the historical BS8 stream (the value + // is inert). + constexpr uint64_t B_SBO = B_LBO; const unsigned thread_in_block = threadIdx.x; const unsigned warp = thread_in_block / 32; // 0..11 const unsigned lane = thread_in_block & 31; - const bool is_wg0 = (warp < 4); const bool is_wg1 = (warp >= 4 && warp < 8); const bool is_calc = (warp < 8); - const unsigned warp_in_wg = warp & 3; // 0..3 within each WG - // Gate/up split within each WG: warps 0,1 (in-WG) → gate rows [0..31]; - // warps 2,3 (in-WG) → up rows [32..63] (within the WG's 64-row stripe). - const bool is_gate_half = (warp_in_wg < 2); - (void)thread_in_block; - (void)is_wg0; - - // TMA path uses the `tiny_wgmma_tma` union variant (byte-identical to - // `tiny_wgmma` plus 32 B of mbarriers at the tail). + const unsigned warp_in_wg = warp & 3; + auto* shm = &shmem->tiny_wgmma_tma; const unsigned effective_bid = (up_block_idx == 0xffffffffu) ? blockIdx.x : up_block_idx; - // Each block owns 128 M rows = 2 WG stripes × 64 rows. WG0's gate - // rows start at base_row_up; WG1's gate rows start at base_row_up + 32. + // Each block owns 128 M rows = 2 WG stripes × 64 rows; WG0's gate rows + // start at base_row_up, WG1's at base_row_up + 32. const unsigned base_row_up = effective_bid * (W_UP_M / 2); const std::uint32_t expert_count = shmem->expert_count; - // Per-thread fp32 accumulators for WGMMA m64n8k32. - // WG0 and WG1 threads each hold their own 4-register accumulator for - // their respective M stripe. + // Per-thread fp32 accumulators for WGMMA m64n8k32 (BS<=8). float chunk_d0 = 0.f, chunk_d1 = 0.f, chunk_d2 = 0.f, chunk_d3 = 0.f; float final_d0 = 0.f, final_d1 = 0.f, final_d2 = 0.f, final_d3 = 0.f; - // ── Phase-3 preamble ────────────────────────────────────────────────── - // - // Entry contract (post-fusion): - // * `bar_w[0..1]` are initialized (arrival_count=1) and - // release-fenced by the kernel prologue in `moe.cuh`. - // * Phase 1 + Phase 2 have populated `bf16_in_full` and then - // `fp8_act_full` + `act_scale[token][k_block]` for every - // `k_block ∈ [0, K_BLOCKS_TOTAL)`; the Phase-2 trailing - // `__syncthreads()` published those writes to all warps. - // * `bar_a[0..1]` are NOT initialized by `moe.cuh`'s prologue — - // they are reused by the down-projection in Phase 4 and - // re-initialized in the down-proj prologue. - // - // This helper never re-initializes barriers and never issues - // bf16-input TMAs; the K-loop reads FP8 activations directly from - // `fp8_act_full`. - - // Stage A requires an even K_TILES so the end-of-K-loop launcher arm - // lands on `next_slot = K_TILES % 2 = 0`. That slot-0 stitch is what - // the next expert's iter-0 COMPUTE waits on; an odd K_TILES would - // land the stitch on slot 1, breaking the cross-expert mbarrier - // chain. At K_STEP_UP=128 (default) HIDDEN_STATES=2048 → K_TILES=16; - // at K_STEP_UP=256 → K_TILES=8; both satisfy the invariant. - static_assert(K_TILES % 2 == 0, - "Stage-A pipeline requires K_TILES to be even so the " - "end-of-loop stitch arms the same slot that the next " - "expert's iter-0 COMPUTE waits on."); - - // ── Pre-loop: arm bar_w[0] + TMA w[0] of expert_start at k=0 ────────── - // - // bar_w[0] is not pre-armed by the caller; this helper fires the - // first expert's weight TMA here. iter-0 COMPUTE waits on - // bar_w[0] before issuing WGMMAs. - // For subsequent experts inside the same helper invocation, the - // previous expert's K-loop stitch (at s=K_TILES-1 COMPUTE) arms - // bar_w[0] + TMAs w[0] of the next expert. No pre-loop work there. + // A non-multiple K_TILES would phase-shift the slot index across the + // expert boundary and break the mbarrier parity chain (authoritative + // check in MoECoreDims; mirrored here at the consuming kernel). + static_assert(K_TILES % SLOTS == 0, + "SLOTS-deep up-proj pipeline requires K_TILES_UP to be a " + "multiple of UP_W_SLOTS so the cross-expert stitch lands " + "the next expert's iters [0,A) on slots [0,A)."); + constexpr uint32_t UP_W_TX_BYTES_PER_SUBSTEP = 16384u; // 128×128 fp8 atom - constexpr uint32_t UP_W_TX_BYTES_TOTAL = UP_W_TX_BYTES_PER_SUBSTEP * K_SUBSTEPS; // 16 KB / 32 KB - // The bf16-input TMA + `bar_a` arm have been removed from this - // helper. Phase-1 + Phase-2 in `moe.cuh` populate - // `fp8_act_full` once per kernel invocation; the K-loop reads it - // directly. The legacy `UP_A_TX_BYTES_*` constants live in the - // kernel prologue for now (until a later cleanup removes the legacy - // hoisted Step A entirely). - if (is_tma_launcher_thread() && expert_start < expert_count) { - const uint32_t first_id = shmem->experts[expert_start].id; - mbarrier_arrive_expect_tx(&shm->bar_w[0], - /*tx_bytes=*/UP_W_TX_BYTES_TOTAL); + constexpr uint32_t UP_W_TX_BYTES_TOTAL = UP_W_TX_BYTES_PER_SUBSTEP * K_SUBSTEPS; + + // Issue the K_SUBSTEPS weight TMAs for one slot of (expert, outer-K + // iter). Caller pre-arms bar_w[slot] with UP_W_TX_BYTES_TOTAL. + auto tma_slot = [&](uint32_t slot, uint32_t eid, uint32_t k_iter) { #pragma unroll for (uint32_t kk = 0; kk < K_SUBSTEPS; ++kk) { - tma_load_up_wgmma_tile(up_weights_desc, /*expert_id=*/first_id, - /*N=*/Dims::N, + tma_load_up_wgmma_tile(up_weights_desc, /*expert_id=*/eid, /*N=*/Dims::N, /*base_row_up=*/base_row_up, - /*k_start=*/kk * K_STEP_WGMMA, - /*dest_slot=*/&shm->w_wgmma[0][kk * W_UP_M][0], - /*bar=*/&shm->bar_w[0]); + /*k_start=*/k_iter * K_STEP + kk * K_STEP_WGMMA, + /*dest_slot=*/&shm->w_wgmma[slot][kk * W_UP_M][0], + /*bar=*/&shm->bar_w[slot]); } -#ifdef MONO_PROFILE_BARW_4DEEP - // 2-deep lookahead variant: also pre-arm bar_w[1] with - // expert_start's iter-1 weight tile, so iter-1's calc-warp - // wait doesn't have to wait for the launcher to issue the TMA - // from cold. This stitches the lookahead 1 iter earlier than - // the default pipeline: the launcher starts at iter 0 arming - // bar_w[2] for iter 2, then the wraparound is 4-deep instead - // of 2-deep. - static_assert(K_TILES >= 4, - "BARW_4DEEP requires K_TILES >= 4 to fit a 2-deep lookahead " - "without wrap-around collisions on bar_w[4]."); - mbarrier_arrive_expect_tx(&shm->bar_w[1], - /*tx_bytes=*/UP_W_TX_BYTES_TOTAL); + }; + + // ── Pre-loop: prime slots [0, ARM_DISTANCE) for expert_start ────────── + // At iter s the launcher arms slot (s+A) % S for logical iter s+A; the + // pre-loop primes iters 0..A-1. + if (is_tma_launcher_thread() && expert_start < expert_count) { + const uint32_t first_id = shmem->experts[expert_start].id; #pragma unroll - for (uint32_t kk = 0; kk < K_SUBSTEPS; ++kk) { - tma_load_up_wgmma_tile(up_weights_desc, /*expert_id=*/first_id, - /*N=*/Dims::N, - /*base_row_up=*/base_row_up, - /*k_start=*/K_STEP + kk * K_STEP_WGMMA, - /*dest_slot=*/&shm->w_wgmma[1][kk * W_UP_M][0], - /*bar=*/&shm->bar_w[1]); + for (uint32_t a = 0; a < ARM_DISTANCE; ++a) { + mbarrier_arrive_expect_tx(&shm->bar_w[a], UP_W_TX_BYTES_TOTAL); + tma_slot(a, first_id, a); } -#endif // MONO_PROFILE_BARW_4DEEP } - // ── Deferred-writeback bookkeeping ──────────────────────────────────── - // - // Phase-3's per-expert SiLU+fp8 quant writeback runs in two modes: - // - // 1. INLINE (default, when the macro below is undefined): runs - // on calc warps at the bottom of each expert iteration with - // two surrounding __syncthreads, exactly as before. The - // timestamps `t_up_e0_iter0_after_*`, `t_up_e0_iter1_after_*`, - // `t_up_e0_after_expert0_*` capture this path's cost. - // - // 2. DEFERRED (when MONO_PROFILE_DEFER_UP_EPILOGUE is defined): - // the writeback is moved to iter `s == 0` of the next expert, - // handled by prefetch warps (8..11), so calc warps' iter-0 - // WGMMAs run concurrently with the previous expert's - // SiLU+quant. The LAST expert in the per-block range has no - // next iter-0 to defer to and runs its writeback inline on - // calc warps after the expert loop ends. - // - // The macro lets us A/B-test the two paths against the same - // phase-timing instrumentation so we can attribute every µs in - // the cross-expert window to a specific stage. - // - // `prev_id_for_writeback` and `has_pending_writeback` are uniform - // across threads (the loop runs in lockstep) and only matter under - // the deferred path. - uint32_t prev_id_for_writeback = 0; + // Deferred-writeback state: expert e's SiLU + fp8 quant + GM writeback + // runs on prefetch warps during expert e+1's K-loop; the LAST expert + // drains inline after the loop. Uniform across threads. bool has_pending_writeback = false; - (void)prev_id_for_writeback; - (void)has_pending_writeback; - // ── Phase-3 expert loop ─────────────────────────────────────────────── + // Scale ping-pong: expert e consumes up_scale[cur_scale_slot] and + // prefetches e+1 into the other slot during its K-loop. + uint32_t cur_scale_slot = 0; + { + if (is_prefetch_warp() && expert_start < expert_count) { + moe_prefetch_up_scale_for_row_async(expert_scales_up, shmem->experts[expert_start].id, + base_row_up, shm->up_scale[0]); + cp_async_commit_group(); + } + } + + // Per-slot mbarrier parity, hoisted OUT of the expert loop so it stays + // continuously synced with the bar_w[slot] hardware phase across expert + // transitions (same reasoning as the down-proj's hoisted parity_w/parity_a). + // A per-expert reset to 0 is only correct when each slot completes an + // EVEN number of phases per expert (K_TILES / SLOTS even); for an odd + // quotient (e.g. K_TILES=12, SLOTS=4 → 3) the barrier ends the expert at + // phase 1 and a blind reset makes the next expert's first wait pass on + // the stale phase, corrupting the arm/wait pairing. + uint32_t parity_w[SLOTS]; +#pragma unroll + for (uint32_t i = 0; i < SLOTS; ++i) parity_w[i] = 0u; + + // ── Expert loop ─────────────────────────────────────────────────────── for (uint32_t e = expert_start; e < expert_count; e += expert_stride) { const uint32_t id = shmem->experts[e].id; const bool has_next_e = (e + expert_stride < expert_count); const uint32_t next_id = has_next_e ? shmem->experts[e + expert_stride].id : 0u; - // Per-expert parity state. bar_w[0] is always pre-armed at the - // start of each expert (by the helper pre-loop above for - // expert_start, or by the prior expert's stitch for subsequent - // experts), so register 0 correctly expects physical 1 on - // the first try_wait.parity. bar_w[1] is first armed inside - // this expert's iter 0 COMPUTE, so register 0 expects physical 1 - // on iter 1's first wait. -#ifdef MONO_PROFILE_BARW_4DEEP - uint32_t parity_w[4] = {0, 0, 0, 0}; -#else - uint32_t parity_w[2] = {0, 0}; -#endif - - // Reset per-expert accumulators. final_d0 = final_d1 = final_d2 = final_d3 = 0.f; - // Load this expert's block-wise weight scales. Scales cover 2 - // row-blocks (gate + up) × UP_SCALE_COLS col-blocks. Both WGs share - // the same scales (see moe_internal.h comment on UP_SCALE_TILE_SIZE). - // Synchronous SHM write (32 elements) by prefetch warp 0; the - // iter-0 QUANT→COMPUTE sync below publishes it to calc warps. - if (is_prefetch_warp()) { - moe_request_up_scale_for_row(expert_scales_up, id, base_row_up, shm->up_scale[0]); + // Drain this expert's prefetched scale (issued a full K-loop ago); + // prefetch the next expert's into the other ping-pong slot. + { + if (is_prefetch_warp()) { + cp_async_wait_group<0>(); + if (has_next_e) { + moe_prefetch_up_scale_for_row_async(expert_scales_up, next_id, base_row_up, + shm->up_scale[cur_scale_slot ^ 1u]); + cp_async_commit_group(); + } + } } - // Publish the per-expert `up_scale` write from the prefetch - // warp (above) to the calc warps that consume it inside the - // K-loop scale-apply. The legacy QUANT/COMPUTE sync used to - // serve this purpose; it has been removed. This sync sits OUTSIDE - // the K-loop, so the "at most one __syncthreads() per outer K-step - // iteration" invariant is preserved. + // ── Per-expert routing cache populate ── + // One calc thread per token: vector-load the token's 8 topk ids (16 B) + // and all 8 weights up front, then select the match in registers. + // This avoids the dependent SHM chain (id scan → weight load at a + // rank-dependent address) that otherwise stalls all 384 threads at the + // publish sync below. The same sync publishes up_scale and the cache. + { + constexpr std::uint32_t MAX_TOPK = MoE_SHM::MAX_TOPK; + if (thread_in_block < batch_size && MAX_TOPK == 8u) { + const std::uint32_t tok = thread_in_block; + // topk_ids_flat is 8-byte aligned; each token slab is 16 B in, so + // two uint2 loads are safely aligned. + const uint16_t* idb = &shmem->topk_ids_flat[tok * MAX_TOPK]; + uint16_t ids[8]; + *reinterpret_cast(&ids[0]) = *reinterpret_cast(idb); + *reinterpret_cast(&ids[4]) = *reinterpret_cast(idb + 4); + + const S_element* wb = &shmem->topk_weights_flat[tok * MAX_TOPK]; + float w[8]; +#pragma unroll + for (std::uint32_t k = 0; k < 8u; ++k) w[k] = wb[k]; + + // Branchless select — topk ids are distinct, so at most one match. + const uint16_t target = (uint16_t)id; + uint8_t k_found = 0xFFu; + float rw_found = 0.f; +#pragma unroll + for (std::uint32_t k = 0; k < 8u; ++k) { + const bool m = (k < top_k) && (ids[k] == target); + if (m) { + k_found = static_cast(k); + rw_found = w[k]; + } + } + shm->up_rank_for_tok[tok] = k_found; + shm->up_rw_for_tok[tok] = rw_found; + } + } + + // Publish up_scale (prefetch warp) + the routing cache (calc warps) + // to the whole block. Outside the K-loop, so the loop still has at + // most one __syncthreads per iteration. __syncthreads(); - // ── Main K-loop (FP8-direct: COMPUTE-only, mbarrier-only sync) ───── - // - // Pipeline per iteration: - // COMPUTE half: - // calc: wait bar_w[s%2]; K_SUBSTEPS × (4× WGMMA + scale-apply). - // B operand reads `fp8_act_full[s * K_SUBSTEPS + kk]` - // — single-buffer FP8 produced once per kernel - // invocation by Phase 2's `routing_phase_quantize` - // and published by the Phase-2 trailing - // `__syncthreads()` in `moe.cuh`. - // launcher: arm + TMA the NEXT slot's K_SUBSTEPS weight atoms - // (UP_W_TX_BYTES_TOTAL bytes total). No bar_a arm - // and no bf16-input TMA. - // target = (s+1, current expert) for intra-expert - // steps, or (0, next expert) on the last - // step when a next expert is scheduled. - // When no next step and no next expert, skip — the - // trailing barriers are left idle; Phase 4 reinits. - // No QUANT half, no QUANT/COMPUTE __syncthreads(). The next - // iter's COMPUTE wait on bar_w[next_slot] re-establishes acquire - // ordering for the weight TMA's async writes. + // ── Main K-loop ─────────────────────────────────────────────────── + // Per iteration: calc warps wait bar_w[s % S] then run K_SUBSTEPS × + // (4 chained WGMMAs + scale-apply); the launcher concurrently arms + + // TMAs the slot A iters ahead (intra-expert, or the next expert's + // first iters via the cross-expert stitch). for (uint32_t s = 0; s < K_TILES; ++s) { -#ifdef MONO_PROFILE_BARW_4DEEP - // 2-deep lookahead: launcher arms `bar_w[(s+2) & 3]` and - // calc waits on `bar_w[s & 3]`. Wraparound is 4 iters; the - // launcher's arm at iter `s+2` lands 2 iters before the - // matching consumer wait, giving DRAM extra time to drain - // the cross-expert stitch and the iter-1 weight TMA. - const uint32_t cur_slot = s & 3u; - const uint32_t next_slot = (s + 2u) & 3u; - const bool has_next_s = (s + 2u < K_TILES); -#else - const uint32_t cur_slot = s & 1; - const uint32_t next_slot = (s + 1) & 1; - const bool has_next_s = (s + 1 < K_TILES); -#endif + const uint32_t cur_slot = s & (SLOTS - 1u); + const uint32_t arm_slot = (s + ARM_DISTANCE) & (SLOTS - 1u); - // ───── COMPUTE half ───────────────────────────────────────────── if (is_calc) { - // Wait on weight tile arrival. Compiled in/out together with - // the launcher's arm; under SKIP_PREFETCH the launcher elides - // the arm so skipping the wait avoids a spin-forever deadlock. while (!mbarrier_try_wait_parity(&shm->bar_w[cur_slot], parity_w[cur_slot])) { } parity_w[cur_slot] ^= 1; - // Phase-timing: after-wait on iter 0 / iter 1 of expert 0 and - // expert 1 (calc warp 0 lane 0 = threadIdx.x == 0). - - // WGMMA descriptor bases per WG. In the M-stacked SHM layout, - // substep `kk` occupies SHM rows `[kk*128 .. kk*128 + 128)`, - // so the WG row offset (0 for WG0, 64 for WG1) is added on top - // of `kk * 128` to pick the per-WG 64-row half within each - // 128-row substep atom. - // WG0 substep 0: rows [0..63] → &w_wgmma[slot][0][0] - // WG1 substep 0: rows [64..127] → &w_wgmma[slot][64][0] - // WG0 substep 1: rows [128..191] → &w_wgmma[slot][128][0] - // WG1 substep 1: rows [192..255] → &w_wgmma[slot][192][0] + // Substep kk occupies SHM rows [kk*128, +128); the WG row offset + // (0 / 64) picks the per-WG half within each atom. const void* a_slot_base = (const void*)&shm->w_wgmma[cur_slot][0][0]; const uint32_t wg_offset_bytes = is_wg1 ? 8192u : 0u; - // Bytes between consecutive 128-row substep atoms in - // `w_wgmma[slot]`: 128 rows × 128 K-bytes = 16 KB. constexpr uint32_t K_SUBSTEP_W_BYTES = 16384u; - - // Per-substep activation base: B operand reads - // `fp8_act_full[s * K_SUBSTEPS + kk]` (single buffer covering - // all K substeps; produced once per kernel invocation by - // Phase 2's `routing_phase_quantize`). - - // Chain 4 WGMMAs per K-substep, each consuming K=32 (= 2 - // consecutive K-chunks of 16 from the fp8 activation tile). - // Scales are applied at every K=128 boundary (matching the - // block-wise FP8 scale granularity). constexpr uint32_t A_K_STRIDE = 2u * static_cast(A_LBO); + #pragma unroll for (uint32_t kk = 0; kk < K_SUBSTEPS; ++kk) { - // A new `wgmma.fence` is required at the start of every group - // of dependent WGMMAs (one fence ↔ one commit-group/wait-group - // pair below). + // One fence per dependent-WGMMA group (paired with the + // commit/wait below). wgmma_fence(); - // Per-substep weight base: kk-th 128-row substep atom + this - // WG's 64-row half within the atom. const void* a_kk_base = (const void*)((const char*)a_slot_base + kk * K_SUBSTEP_W_BYTES + wg_offset_bytes); - - // Single-buffer activation atom for this (s, kk): - // fp8_act_full[s * K_SUBSTEPS + kk][...] - // Replaces the legacy `fp8_act[cur_slot][kk]` indexing. - // `cur_slot` is unused for the activation - // operand and remains in scope only for the weight tile. const uint32_t kblk = s * K_SUBSTEPS + kk; #pragma unroll @@ -551,315 +309,252 @@ __device__ inline void moe_up_projection_BS8_allexperts_wgmma_tma( wgmma_commit_group(); wgmma_wait_group<0>(); - // ── Scale-apply at the K=128 boundary (per-substep) ────────── - // - // Scale indices for outer step `s`, substep `kk`: - // * activation: `act_scale[tok][s * K_SUBSTEPS + kk]` - // * weight: `up_scale[0][s * K_SUBSTEPS + kk + ws_off]` - // Indexing matches the legacy form; the values - // are now produced by `routing_phase_quantize` instead of - // by the per-K-step `moe_streaming_quantize_k128` call. - const uint32_t ws_off = is_gate_half ? 0u : UP_SCALE_COLS; - const float ws = shm->up_scale[0][kblk + ws_off]; + // Scale-apply at the K=128 boundary (the block-wise FP8 scale + // granularity). Pair layout: d0/d1 are gate rows, d2/d3 up + // rows within the same warp, each with its own weight scale. const uint32_t tok_02 = (lane % 4) * 2; const uint32_t tok_13 = tok_02 + 1; - // SHM `act_scale` is laid out as `[blk][tok]` (see comment on - // its declaration in `MoE_SHM`); the index swap from the - // legacy `[tok][blk]` form is cosmetic at the source level - // but eliminates the 4-way bank conflict NCU flagged on - // these LDS sites. const float as_02 = shmem->act_scale[kblk][tok_02]; const float as_13 = shmem->act_scale[kblk][tok_13]; - final_d0 += chunk_d0 * ws * as_02; - final_d1 += chunk_d1 * ws * as_13; - final_d2 += chunk_d2 * ws * as_02; - final_d3 += chunk_d3 * ws * as_13; + { + const S_element* ws_buf = shm->up_scale[cur_scale_slot]; + const float ws_gate = ws_buf[kblk + 0u]; + const float ws_up = ws_buf[kblk + UP_SCALE_COLS]; + final_d0 += chunk_d0 * ws_gate * as_02; + final_d1 += chunk_d1 * ws_gate * as_13; + final_d2 += chunk_d2 * ws_up * as_02; + final_d3 += chunk_d3 * ws_up * as_13; + } chunk_d0 = chunk_d1 = chunk_d2 = chunk_d3 = 0.f; } } - // Phase-timing: after-compute on iter 0 / iter 1 of expert 0 - // and expert 1. Outside the calc-only block so the macro's - // `is_calc` gating doesn't suppress threadIdx.x == 0 — but - // threadIdx.x == 0 is itself in calc, so the capture lands - // at the same point either way. - - // Launcher runs IN PARALLEL with the WGMMA above. Only the - // weight TMA + bar_w arm remain; the bf16-input TMA + bar_a - // arm have been removed. The activation operand is - // sourced from `fp8_act_full`, which is produced once per - // kernel invocation by Phase 2 — there is nothing to fetch - // per K-step on the activation side. - // - // For K_STEP > K_STEP_WGMMA the launcher issues K_SUBSTEPS_UP - // back-to-back weight TMAs per slot (one per 128-K substep, - // stacked along the K axis in SHM). bar_w is armed once with - // the TOTAL tx_bytes so a single `mbarrier.try_wait.parity` on - // the calc side drains all atoms. + // Launcher (runs in parallel with the WGMMAs above): arm + TMA the + // slot A iters ahead — intra-expert while s+A < K_TILES, else the + // cross-expert stitch into the next expert's iters [0, A). On the + // last expert's last A iters the barriers are left idle (Phase 4 + // re-initializes them). if (is_tma_launcher_thread()) { -#ifdef MONO_PROFILE_BARW_4DEEP - // 2-deep lookahead: at iter `s` arm `bar_w[(s+2)&3]` for - // the iter-(s+2) weight tile. Three cases by source: - // (A) Intra-expert: s+2 < K_TILES → fetch CURRENT expert's - // iter-(s+2) tile. - // (B) Cross-expert iter-0: s+2 == K_TILES (i.e. s == - // K_TILES-2) AND has_next_e → fetch - // NEXT expert's iter-0 tile. - // (C) Cross-expert iter-1: s+2 == K_TILES+1 (i.e. s == - // K_TILES-1) AND has_next_e → fetch - // NEXT expert's iter-1 tile. - // Else: idle. - // - // Cases (B) and (C) together replace the single-deep - // "stitch" from the original pipeline; they pre-load both - // iter-0 AND iter-1 of the next expert during the current - // expert's last two K-iters. The matching pre-loop in the - // helper does the same for the first expert. - if (has_next_s) { - // Case (A): intra-expert fetch of (s+2)-th tile. - const uint32_t next_k_start = (s + 2u) * K_STEP; - mbarrier_arrive_expect_tx(&shm->bar_w[next_slot], + const uint32_t target_iter = s + ARM_DISTANCE; + if (target_iter < K_TILES) { + mbarrier_arrive_expect_tx(&shm->bar_w[arm_slot], /*tx_bytes=*/UP_W_TX_BYTES_TOTAL); -#pragma unroll - for (uint32_t kk = 0; kk < K_SUBSTEPS; ++kk) { - tma_load_up_wgmma_tile(up_weights_desc, /*expert_id=*/id, - /*N=*/Dims::N, - /*base_row_up=*/base_row_up, - /*k_start=*/next_k_start + kk * K_STEP_WGMMA, - /*dest_slot=*/&shm->w_wgmma[next_slot][kk * W_UP_M][0], - /*bar=*/&shm->bar_w[next_slot]); - } + tma_slot(arm_slot, id, target_iter); } else if (has_next_e) { - // Cases (B)/(C): cross-expert stitch. - // At s == K_TILES-2: fetch next expert's iter-0. - // At s == K_TILES-1: fetch next expert's iter-1. - const uint32_t next_e_iter = (s == K_TILES - 2u) ? 0u : 1u; - const uint32_t next_e_k_start = next_e_iter * K_STEP; - mbarrier_arrive_expect_tx(&shm->bar_w[next_slot], + mbarrier_arrive_expect_tx(&shm->bar_w[arm_slot], /*tx_bytes=*/UP_W_TX_BYTES_TOTAL); -#pragma unroll - for (uint32_t kk = 0; kk < K_SUBSTEPS; ++kk) { - tma_load_up_wgmma_tile(up_weights_desc, /*expert_id=*/next_id, - /*N=*/Dims::N, - /*base_row_up=*/base_row_up, - /*k_start=*/next_e_k_start + kk * K_STEP_WGMMA, - /*dest_slot=*/&shm->w_wgmma[next_slot][kk * W_UP_M][0], - /*bar=*/&shm->bar_w[next_slot]); - } + tma_slot(arm_slot, next_id, target_iter - K_TILES); } - // Else: last expert, last two iters — leave barriers idle. -#else // !MONO_PROFILE_BARW_4DEEP - if (has_next_s) { - // Intra-expert: fetch (s+1) tile of the CURRENT expert. - const uint32_t next_k_start = (s + 1) * K_STEP; - mbarrier_arrive_expect_tx(&shm->bar_w[next_slot], - /*tx_bytes=*/UP_W_TX_BYTES_TOTAL); -#pragma unroll - for (uint32_t kk = 0; kk < K_SUBSTEPS; ++kk) { - tma_load_up_wgmma_tile(up_weights_desc, /*expert_id=*/id, - /*N=*/Dims::N, - /*base_row_up=*/base_row_up, - /*k_start=*/next_k_start + kk * K_STEP_WGMMA, - /*dest_slot=*/&shm->w_wgmma[next_slot][kk * W_UP_M][0], - /*bar=*/&shm->bar_w[next_slot]); - } - } else if (has_next_e) { - // End-of-expert stitch: fetch iter-0 weight tile of the - // NEXT expert. For K_TILES even, `next_slot == 0` — - // matches the next expert's iter-0 cur_slot. - mbarrier_arrive_expect_tx(&shm->bar_w[next_slot], - /*tx_bytes=*/UP_W_TX_BYTES_TOTAL); -#pragma unroll - for (uint32_t kk = 0; kk < K_SUBSTEPS; ++kk) { - tma_load_up_wgmma_tile(up_weights_desc, /*expert_id=*/next_id, - /*N=*/Dims::N, - /*base_row_up=*/base_row_up, - /*k_start=*/kk * K_STEP_WGMMA, - /*dest_slot=*/&shm->w_wgmma[next_slot][kk * W_UP_M][0], - /*bar=*/&shm->bar_w[next_slot]); - } - } - // Else: last expert's last iteration — leave barriers idle. -#endif // MONO_PROFILE_BARW_4DEEP } -#ifdef MONO_PROFILE_DEFER_UP_EPILOGUE // ── Deferred SiLU + fp8 quant writeback for the PREVIOUS expert ── // - // Runs on prefetch warps (8..11) of every expert AFTER the first. - // Scheduling goal (two constraints together): - // (1) FULLY USE THE 4 PREFETCH WARPS whenever the epilogue runs — - // one warp per token (32 lanes cover a token's 64 output cols - // via 4 gate/up pairs, and `warp_reduce_max_float` for the - // fp8 block-scale needs the whole warp), so a "wave" is - // PF = PREFETCH_WARP_COUNT = 4 tokens processed in lockstep. - // (2) DISTRIBUTE THE WAVES ACROSS K-STEPS — the BS tokens split - // into `WAVES = ceil(BS / PF)` waves, each fired at ONE - // K-loop iteration, spaced evenly over the first - // `DEFER_ITERS = K_TILES - 1` iterations (the LAST iteration, - // s == K_TILES-1, is left free — it carries the cross-expert - // weight-TMA stitch on the launcher thread). - // - // Wave w fires at iteration `s_w = w * DEFER_ITERS / WAVES`; within - // it prefetch warp 8+i handles token `w*PF + i`. Examples: - // * BS=8, K_TILES=8 → WAVES=2, waves at s=0,3 (4 warps each). - // * BS=16, K_TILES=8 → WAVES=4, waves at s=0,1,3,5 (4 warps each, - // four iterations — the requested layout). - // vs. the old burst (all waves back-to-back at s=0,1): same 4-warp - // width, but spacing the waves lets DRAM drain the `temp_fp8` store - // burst between waves and overlaps each with more calc-warp WGMMA. - // - // `WAVES <= DEFER_ITERS` guarantees every wave lands on its own - // iteration (distinct `s_w`), so the helper is called at most once - // per warp per iteration — no double-processing. - // - // Numerically identical to any schedule: `wgmma_out` holds the - // PREVIOUS expert's data for the entire current K-loop (the current - // expert overwrites it only AFTER the loop), and `expert_tok_krank` - // / `sorted_slot` / `topk_weights_flat` are routing-time-immutable, - // so which iteration a token is processed at does not change the - // result. + // One PF warp per token (32 lanes cover a token's 64 output features + // via 2 post_silu reads; warp_reduce_max needs the whole warp), so a + // wave is PF = 4 tokens. Waves are spaced evenly over the first + // K_TILES-1 iterations — the last iteration stays free for the + // cross-expert stitch, and spacing lets DRAM drain between the + // temp_fp8 store bursts. Numerically schedule-invariant: + // post_silu_scratch holds the previous expert's values for the whole + // current K-loop and the routing tables are immutable. static_assert(K_TILES >= 2, "Deferred up-proj writeback requires K_TILES >= 2."); constexpr uint32_t PF = CoreDims::PREFETCH_WARP_COUNT; // 4 - constexpr uint32_t WAVES = (Dims::BS + PF - 1u) / PF; // ceil(BS/PF) + constexpr uint32_t WAVES = (Dims::BS + PF - 1u) / PF; constexpr uint32_t DEFER_ITERS = K_TILES - 1u; static_assert(WAVES <= DEFER_ITERS, - "Not enough K-loop iterations to give each up-proj epilogue " - "wave its own K-step (need ceil(BS/4) <= K_TILES-1)."); + "Not enough K-loop iterations to give each up-proj " + "epilogue wave its own K-step (need ceil(BS/4) <= " + "K_TILES-1)."); if (has_pending_writeback && is_prefetch_warp() && s < DEFER_ITERS) { const unsigned pf_warp = warp - CoreDims::CALC_WARP_COUNT; // 0..3 const uint32_t col_in_half = lane; // 0..31 #pragma unroll for (uint32_t w = 0; w < WAVES; ++w) { - // Uniform across the block (s) and the warp (w, pf_warp are - // lane-independent), so all 32 lanes stay in lockstep for the - // warp-reduce inside the helper. - if (s == w * DEFER_ITERS / WAVES) { - const uint32_t tok = w * PF + pf_warp; - if (tok < Dims::BS) { - up_silu_quant_writeback_one_token(shmem, spec, shm, prev_id_for_writeback, tok, - col_in_half, lane, base_row_up, effective_bid, - top_k, batch_size); + // s, w, pf_warp are lane-uniform, so the warp stays in lockstep + // for the reduce; distinct s per wave ⇒ each token once. + if (s != w * DEFER_ITERS / WAVES) continue; + const uint32_t tok = w * PF + pf_warp; + + // Read the PREVIOUS expert's rank snapshot (the current expert's + // K-loop top already overwrote up_rank_for_tok). Also filters + // tokens that don't route to the previous expert. + bool store_local = false; + std::uint32_t dest_row_local = 0; + if (tok < batch_size) { + const uint8_t k = shm->up_rank_for_tok_prev[tok]; + if (k != 0xFFu) { + store_local = true; + dest_row_local = shm->sorted_slot[tok * top_k + k]; } } + + // rw * silu(gate) * up was already baked in by the calc-warp + // epilogue; rows [0..31] = WG0, [64..95] = WG1. + const float val1_l = shm->partial_result.post_silu_scratch[col_in_half][tok]; + const float val2_l = shm->partial_result.post_silu_scratch[col_in_half + 64][tok]; + + const std::uint32_t out_col_1_l = base_row_up + col_in_half; + const std::uint32_t out_col_2_l = base_row_up + 32 + col_in_half; + const bool write1_l = store_local && (out_col_1_l < Dims::N); + const bool write2_l = store_local && (out_col_2_l < Dims::N); + float v1 = write1_l ? val1_l : 0.f; + float v2 = write2_l ? val2_l : 0.f; + + float local_max_l = fmaxf(fabsf(v1), fabsf(v2)); + float block_max_l = warp_reduce_max_float(local_max_l); + // Eps-clamp tiny maxima: a block_max slightly above FLT_MIN + // still overflows inv_scale (448/block_max > FLT_MAX for + // block_max < ~1.32e-36), NaN-ing the whole block after the + // fp8 cast. 1e-10 matches vLLM's group-quant eps. + block_max_l = fmaxf(block_max_l, 1e-10f); + constexpr float FP8_MAX = 448.0f; + constexpr float FP8_MAX_INV = 1.0f / 448.0f; + const float block_scale_l = block_max_l * FP8_MAX_INV; + const float inv_scale_l = FP8_MAX / block_max_l; + const AQ_element q1_l = (AQ_element)(v1 * inv_scale_l); + const AQ_element q2_l = (AQ_element)(v2 * inv_scale_l); + + if (store_local && tok < batch_size) { + // (warp-uniform branch: tok / store_local are per-warp values) + if (write1_l) { + spec->temp_fp8[dest_row_local * Dims::N + out_col_1_l] = q1_l; + } + if (write2_l) { + spec->temp_fp8[dest_row_local * Dims::N + out_col_2_l] = q2_l; + } + // Sentinel handoff: payload first, then the scale as a + // release-published readiness flag (syncwarp + fence inside). + moe_publish_act_scale(spec, shmem->scale_parity, dest_row_local, effective_bid, + block_scale_l, lane); + } } } -#endif // MONO_PROFILE_DEFER_UP_EPILOGUE - // ── Inter-iteration sync ── - // - // The launcher arms `bar_w[next_slot]` at iter s. Two - // iterations later (iter s+2), the launcher arms the SAME - // `bar_w[next_slot]` again (because the slot index repeats every - // 2 iters in the ping-pong). For the second arm not to - // double-arm an mbarrier whose current phase is still pending, - // the calc-warp consume of that slot at iter s+1 must complete - // BEFORE iter s+2's launcher arm runs. - // - // The legacy QUANT/COMPUTE __syncthreads() served this role. - // Without it, the launcher (a single warp-8-lane-0 thread that - // never waits) can race ahead through all K_TILES launcher - // arms before any calc warp consumes its bar_w wait. This - // single end-of-iter sync re-establishes ordering: every iter, - // all warps (including launcher and calc) rendezvous at the - // sync, so the launcher cannot arm the next-slot mbarrier until - // the calc warps' wait on the same slot has completed. - // - // At most one __syncthreads() per outer K-step iteration; - // this sync publishes the launcher's `mbarrier_arrive_expect_tx` - // (a producer-side state mutation on bar_w) to the calc warps - // that will issue `try_wait_parity` against it next iter. + // Inter-iteration sync: the launcher re-arms a slot SLOTS iters + // after its previous arm; without this rendezvous the launcher (a + // single never-waiting thread) could race through all arms before + // the calc warps consume the matching waits, double-arming a + // still-pending mbarrier. __syncthreads(); } // end K-loop - // ── End-of-expert: write final_d to partial_result.wgmma_out[128][8] ── - // Canonical WGMMA D-matrix layout per thread (m64n8k32): - // d[0]: row = warp_in_wg*16 + lane/4 + 0, col = (lane%4)*2 + 0 - // d[1]: row = warp_in_wg*16 + lane/4 + 0, col = (lane%4)*2 + 1 - // d[2]: row = warp_in_wg*16 + lane/4 + 8, col = (lane%4)*2 + 0 - // d[3]: row = warp_in_wg*16 + lane/4 + 8, col = (lane%4)*2 + 1 - // For WG1, rows shift by +64 in the full 128-row output tile. + // ── Calc-warp epilogue: per-lane combine → post_silu_scratch ── // - // Up-projection epilogue: (a) the wgmma_out SHM store, (b) the - // inter-warp sync that publishes wgmma_out, and (c) the - // SiLU+fp8-quant writeback helper. - if (is_calc) { - const uint32_t wg_row_offset = is_wg1 ? 64u : 0u; - const uint32_t row_base = wg_row_offset + warp_in_wg * 16 + lane / 4; - const uint32_t col_base = (lane % 4) * 2; - shm->partial_result.wgmma_out[row_base + 0][col_base + 0] = final_d0; - shm->partial_result.wgmma_out[row_base + 0][col_base + 1] = final_d1; - shm->partial_result.wgmma_out[row_base + 8][col_base + 0] = final_d2; - shm->partial_result.wgmma_out[row_base + 8][col_base + 1] = final_d3; - } + // Pair layout after the K-loop: + // final_d0 = gate(r) tok_even final_d1 = gate(r) tok_odd + // final_d2 = up(r) tok_even final_d3 = up(r) tok_odd + // with r = warp_in_wg*8 + lane/4 within the WG's 32-row half. + // Calc warps only combine and store; reduce-max / quantize / GM + // stores are deferred to the PF body above during the next expert. + { + if (is_calc) { + const std::uint32_t tok_even = (lane % 4) * 2; + const std::uint32_t tok_odd = tok_even + 1; - // (The per-expert K-loop-tail scan that populated `up_rank_for_tok` - // is gone: the up-proj epilogue now reads the routing-time - // `expert_tok_krank[id][tok]` table built once in - // `prepare_moe_topk_BS8`. See `up_silu_quant_writeback_one_token`.) + // up_rw_for_tok is 0.0f for unrouted tokens, so the rw value + // doubles as the route predicate. + float rw_even = 0.f, rw_odd = 0.f; + bool store_even = false, store_odd = false; - __syncthreads(); + if (tok_even < batch_size) { + rw_even = shm->up_rw_for_tok[tok_even]; + store_even = (rw_even != 0.f); + } + if (tok_odd < batch_size) { + rw_odd = shm->up_rw_for_tok[tok_odd]; + store_odd = (rw_odd != 0.f); + } + + // silu(gate) * up * rw. __fdividef (approximate reciprocal) is + // bit-adequate here — the result is fp8-quantized downstream — + // and shortens the SFU dependency chain vs the IEEE divide. + float val0 = __fdividef(rw_even * final_d2 * final_d0, 1.0f + __expf(-final_d0)); + float val1 = __fdividef(rw_odd * final_d3 * final_d1, 1.0f + __expf(-final_d1)); + + if (!store_even) val0 = 0.f; + if (!store_odd) val1 = 0.f; - // Phase-timing: after the wgmma_out store + publish sync. The - // SiLU+fp8-quant helper that follows reads `wgmma_out`, so the - // sync must complete first. Δ to `t_up_after_expert0_kloop` - // measures the cost of the wgmma_out store + the publish sync. - -#ifdef MONO_PROFILE_DEFER_UP_EPILOGUE - // Deferred path: mark this expert's SiLU+quant writeback as - // pending; the prefetch-warp body inside the next expert's - // K-loop iters 0/1 will perform it. - prev_id_for_writeback = id; - has_pending_writeback = true; -#else - // Inline path (default): SiLU + fp8 quant + GM writeback runs - // here on calc warps with the same (warp → tok) mapping as - // before. See `up_silu_quant_writeback_one_token` for the - // per-(tok, lane) body. - if (is_calc) { - const uint32_t tok = warp; // 0..7, one per calc warp - const uint32_t col_in_half = lane; // 0..31 - up_silu_quant_writeback_one_token(shmem, spec, shm, id, tok, col_in_half, lane, - base_row_up, effective_bid, top_k, batch_size); + const uint32_t row_in_tile = (is_wg1 ? 64u : 0u) + warp_in_wg * 8 + lane / 4; + shm->partial_result.post_silu_scratch[row_in_tile][tok_even] = val0; + shm->partial_result.post_silu_scratch[row_in_tile][tok_odd] = val1; + + // Snapshot this expert's ranks for the next expert's PF body (the + // next K-loop top overwrites up_rank_for_tok). Published by the + // inter-expert __syncthreads below. + if (warp == 0 && lane < Dims::BS) { + shm->up_rank_for_tok_prev[lane] = shm->up_rank_for_tok[lane]; + } + } + + has_pending_writeback = true; } -#endif // MONO_PROFILE_DEFER_UP_EPILOGUE - // ── Tail of expert loop ── - // - // The next expert's iter-0 TMAs (weight + bf16) were already issued - // during this expert's s=K_TILES-1 COMPUTE half via the - // cross-expert stitch (see the launcher branch in the K-loop). - // No tail prefetch is needed here; the mbarrier chain carries - // across the expert boundary without any __syncthreads(). - // - // A single trailing __syncthreads() publishes the SiLU writeback's - // spec->temp_fp8 / spec->temp_act_scale writes to every thread in - // the block before the next iteration's prefetch warp overwrites - // `shm->up_scale[0]`. This sync also aligns the launcher thread - // with calc warps so the launcher cannot race ahead and issue the - // stitch-triggered mbarrier arm for expert e+2 before expert e+1's - // iter-0 QUANT wait has consumed the stitch arrival for expert e+1. + // Publishes post_silu_scratch + the rank snapshot to PF warps, and + // keeps the launcher from racing ahead of the calc warps' stitch + // consumption. The next expert's first weight TMAs were already + // issued by the in-loop stitch — the mbarrier chain carries across + // the expert boundary with no extra work here. __syncthreads(); + cur_scale_slot ^= 1u; } // end expert loop -#ifdef MONO_PROFILE_DEFER_UP_EPILOGUE - // ── Post-loop drain for the LAST expert (deferred path only) ── - // - // The deferred path inside the K-loop processes expert e's - // wgmma_out at iter 0/1 of expert e+1. The LAST expert visited - // (expert_count - expert_stride for stride==1) has nothing to - // defer to, so we run its writeback inline now, on calc warps, - // with the original (warp → tok) mapping (warps 0..7, 1 token - // each). All warps are free at this point — the K-loop is done. + // ── Post-loop drain: the LAST expert has no successor to defer to ───── + // Same math as the PF body, run inline on calc warps (one token per + // warp) now that the K-loop is done. if (has_pending_writeback && is_calc) { - const uint32_t tok = warp; // 0..7 - const uint32_t col_in_half = lane; // 0..31 - up_silu_quant_writeback_one_token(shmem, spec, shm, prev_id_for_writeback, tok, - col_in_half, lane, base_row_up, effective_bid, top_k, - batch_size); + // BS<=8: one pass, tok = warp (0..7). + constexpr uint32_t DRAIN_PASSES = (Dims::BS + 7u) / 8u; // == 1 for BS<=8 + const uint32_t col_in_half = lane; // 0..31 +#pragma unroll + for (uint32_t t_off = 0; t_off < DRAIN_PASSES; ++t_off) { + const uint32_t tok = warp + t_off * CoreDims::CALC_WARP_COUNT; + bool store_local = false; + std::uint32_t dest_row_local = 0; + if (tok < batch_size) { + const uint8_t k = shm->up_rank_for_tok_prev[tok]; + if (k != 0xFFu) { + store_local = true; + dest_row_local = shm->sorted_slot[tok * top_k + k]; + } + } + + const float val1_l = shm->partial_result.post_silu_scratch[col_in_half][tok]; + const float val2_l = shm->partial_result.post_silu_scratch[col_in_half + 64][tok]; + + const std::uint32_t out_col_1_l = base_row_up + col_in_half; + const std::uint32_t out_col_2_l = base_row_up + 32 + col_in_half; + const bool write1_l = store_local && (out_col_1_l < Dims::N); + const bool write2_l = store_local && (out_col_2_l < Dims::N); + float v1 = write1_l ? val1_l : 0.f; + float v2 = write2_l ? val2_l : 0.f; + + float local_max_l = fmaxf(fabsf(v1), fabsf(v2)); + float block_max_l = warp_reduce_max_float(local_max_l); + // Eps-clamp tiny maxima (overflow-safe inv_scale); see the + // pair-layout epilogue above for the full rationale. + block_max_l = fmaxf(block_max_l, 1e-10f); + constexpr float FP8_MAX = 448.0f; + constexpr float FP8_MAX_INV = 1.0f / 448.0f; + const float block_scale_l = block_max_l * FP8_MAX_INV; + const float inv_scale_l = FP8_MAX / block_max_l; + const AQ_element q1_l = (AQ_element)(v1 * inv_scale_l); + const AQ_element q2_l = (AQ_element)(v2 * inv_scale_l); + + if (store_local && tok < batch_size) { + // (warp-uniform branch: tok is per-warp here) + if (write1_l) { + spec->temp_fp8[dest_row_local * Dims::N + out_col_1_l] = q1_l; + } + if (write2_l) { + spec->temp_fp8[dest_row_local * Dims::N + out_col_2_l] = q2_l; + } + // Sentinel handoff publish (see moe_publish_act_scale). + moe_publish_act_scale(spec, shmem->scale_parity, dest_row_local, effective_bid, + block_scale_l, lane); + } + } } -#endif // MONO_PROFILE_DEFER_UP_EPILOGUE } } // namespace monomoe diff --git a/csrc/fused_moe/monomoe/src/ptx_utils.h b/csrc/fused_moe/monomoe/src/ptx_utils.h index dfba85c6499..011e0034199 100644 --- a/csrc/fused_moe/monomoe/src/ptx_utils.h +++ b/csrc/fused_moe/monomoe/src/ptx_utils.h @@ -11,36 +11,41 @@ namespace monomoe { -// ── Hopper WGMMA (sm_90a) helpers ───────────────────────────────────────── -// -// These thin wrappers expose the `wgmma.mma_async` family of instructions -// for fp8 (e4m3) operands with fp32 accumulators. -// -// WGMMA semantics (key differences from `mma.sync`): -// -// * Issued by a full **warpgroup** (4 consecutive warps = 128 threads). -// Every thread in the warpgroup must execute the instruction. +// ── cp.async scalar helpers (sm_80+) ────────────────────────────────────── // -// * A and B operands live in **shared memory**, addressed by 64-bit -// "matrix descriptors" that encode base address, leading- and stride- -// dimension byte offsets, and a swizzle mode. We use SWIZZLE_NONE for -// correctness-first bring-up; upgrade to 128B swizzle later for perf. +// Non-blocking 4-byte global→shared copies for small latency-sensitive +// prefetches (e.g. the per-expert block-scale tile). Issue with +// `cp_async_cg_4`, checkpoint with `cp_async_commit_group`, drain with +// `cp_async_wait_group()` before reading the destination. + +__device__ static inline void cp_async_cg_4(void* smem_dst, const void* gmem_src) { + const std::uint32_t smem_addr = static_cast(__cvta_generic_to_shared(smem_dst)); + asm volatile("cp.async.ca.shared.global [%0], [%1], 4;\n" ::"r"(smem_addr), "l"(gmem_src)); +} + +__device__ static inline void cp_async_commit_group() { + asm volatile("cp.async.commit_group;\n" ::: "memory"); +} + +template +__device__ static inline void cp_async_wait_group() { + asm volatile("cp.async.wait_group %0;\n" ::"n"(N) : "memory"); +} + +// ── Hopper WGMMA (sm_90a) helpers ───────────────────────────────────────── // -// * The accumulator D is kept in **registers**, distributed across the -// warpgroup. For `m64n8k32` each thread holds 4 fp32 values; for -// larger N, more. +// Wrappers for `wgmma.mma_async` with fp8 (e4m3) operands and fp32 +// accumulators. Key semantics vs `mma.sync`: // -// * WGMMA is **asynchronous**. After issuing one or more WGMMAs you -// must `wgmma.commit_group.sync` to checkpoint, and -// `wgmma.wait_group.sync N` to wait for all but the last N groups -// to finish. Before loading new operands into SHM slots that a -// pending WGMMA reads, use `wgmma.fence.sync.aligned` to establish -// ordering between register writes and the SHM reads. +// * Issued by a full warpgroup (4 warps); every thread must execute it. +// * A and B live in shared memory, addressed by 64-bit matrix +// descriptors (base address + leading/stride byte offsets + swizzle). +// * The accumulator D stays in registers, distributed across the WG. +// * Asynchronous: `commit_group` checkpoints, `wait_group` waits for +// all but the last N groups, and `wgmma_fence` orders prior register +// writes before the SHM reads of subsequent WGMMAs. // -// References: -// - PTX ISA 8.5 §9.7.15 "Asynchronous Warpgroup Level Matrix Multiply- -// Accumulate Instructions" -// - NVIDIA Hopper H100 architecture whitepaper +// Reference: PTX ISA §9.7.15 (Asynchronous Warpgroup MMA). /** * @brief Build a WGMMA 64-bit shared-memory matrix descriptor. @@ -96,7 +101,10 @@ __device__ static __forceinline__ std::uint64_t make_wgmma_desc(const void* addr __device__ static __forceinline__ void wgmma_fence() { cute::warpgroup_arrive(); } /** - * @brief Close the currently-outstanding WGMMA group and start a new one. + * @brief Commit all previously-issued WGMMAs as a single trackable group. + * + * Subsequent WGMMAs belong to the next group; `wgmma_wait_group()` counts + * committed groups that are still in flight. */ __device__ static __forceinline__ void wgmma_commit_group() { cute::warpgroup_commit_batch(); } @@ -110,41 +118,21 @@ __device__ __forceinline__ void wgmma_wait_group() { } /** - * @brief wgmma.mma_async m64n8k32 fp8×fp8 → fp32 with SHM A and SHM B. + * @brief wgmma.mma_async m64n8k32 fp8×fp8 → fp32, SHM A and SHM B. * - * Accumulator layout (per thread in the warpgroup, for N=8): - * d[0..3] — 4 fp32 values. Thread (lane l, warp w in {0..3}) in the - * warpgroup owns: - * d[0]: row = w*16 + l/4 + 0, col = (l%4)*2 + 0 - * d[1]: row = w*16 + l/4 + 0, col = (l%4)*2 + 1 - * d[2]: row = w*16 + l/4 + 8, col = (l%4)*2 + 0 - * d[3]: row = w*16 + l/4 + 8, col = (l%4)*2 + 1 - * (Same mapping as mma.sync m16n8k32, replicated 4× across the warps.) + * Accumulator layout per thread (lane l, warp w in the WG), same mapping as + * mma.sync m16n8k32 replicated 4× across the warps: + * d[0]: row = w*16 + l/4 + 0, col = (l%4)*2 + 0 + * d[1]: row = w*16 + l/4 + 0, col = (l%4)*2 + 1 + * d[2]: row = w*16 + l/4 + 8, col = (l%4)*2 + 0 + * d[3]: row = w*16 + l/4 + 8, col = (l%4)*2 + 1 * - * PTX form (from CUTLASS mma_sm90_gmma.hpp, MMA_64x8x32_F32E4M3E4M3_SS_TN): - * { - * .reg .pred p; - * setp.ne.b32 p, , 0; - * wgmma.mma_async.sync.aligned.m64n8k32.f32.e4m3.e4m3 - * {d0, d1, d2, d3}, desc_a, desc_b, p, , ; - * } - * where scaleA / scaleB are immediates (+1 or -1). - * - * This wrapper hard-codes: - * scale_D = 1 (accumulate: D = A·B + D) - * scaleA = 1, scaleB = 1 - * which are the only modes our kernel uses. - * - * @param desc_a Matrix descriptor for operand A (weights, M×K) - * @param desc_b Matrix descriptor for operand B (activations, K×N) - * @param d0..d3 4 fp32 accumulator registers (read-modify-write) + * Hard-codes scale_D = 1 (accumulate) and scaleA = scaleB = +1. */ __device__ static __forceinline__ void wgmma_m64n8k32_e4m3_e4m3_f32(std::uint64_t desc_a, std::uint64_t desc_b, float& d0, float& d1, float& d2, float& d3) { -#if (defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 900) - // scale_D = 1 → accumulate into d0..d3. constexpr std::uint32_t scale_D = 1; asm volatile( "{\n" @@ -155,48 +143,22 @@ __device__ static __forceinline__ void wgmma_m64n8k32_e4m3_e4m3_f32(std::uint64_ "}\n" : "+f"(d0), "+f"(d1), "+f"(d2), "+f"(d3) : "l"(desc_a), "l"(desc_b), "r"(scale_D), "n"(1), "n"(1)); -#else - (void)desc_a; - (void)desc_b; - (void)d0; - (void)d1; - (void)d2; - (void)d3; - asm volatile("trap;"); -#endif -} - -__device__ inline std::uint32_t rotate_col_32(std::uint32_t col, std::uint32_t row) { - std::uint32_t col_base = col & 0xff9f; - std::uint32_t col_rot = (col + 0x20 * row) & 0x60; - return col_base | col_rot; } // ── Hopper mbarrier helpers (sm_90a) ────────────────────────────────────── // -// Thin PTX wrappers around the `mbarrier.*` family used to gate TMA -// (`cp.async.bulk.tensor.*`) transfers. An mbarrier is a 64-bit shared- -// memory object (16-byte aligned) with two internal counters: +// Wrappers around the `mbarrier.*` family used to gate TMA transfers. An +// mbarrier is a 64-bit, 16-byte-aligned SHM object with two counters: // -// 1. Arrival counter — decremented by `mbarrier.arrive*`. -// Initialized by `mbarrier.init` to `arrival_count`. -// 2. Transaction-bytes — decremented by the TMA engine as bytes land in -// SMEM. Initialized to 0, then *set* by -// `mbarrier.arrive.expect_tx` (or `expect_tx`). +// 1. Arrival counter — set by `mbarrier.init`, decremented by arrives. +// 2. Transaction bytes — set by `arrive.expect_tx`, decremented by the +// TMA engine as bytes land in SHM. // -// The barrier "completes" (flips its parity bit) when both counters reach -// zero. Consumers spin on `mbarrier.try_wait.parity` with a self-cycling -// parity register, avoiding explicit reset between uses. +// The barrier completes (flips its parity bit) when both reach zero. +// Consumers spin on `try_wait.parity` with a self-cycling parity register, +// so no explicit reset is needed between uses. // -// All of these instructions require SM90+; the bodies are compiled out on -// older targets to avoid emitting invalid PTX (`ptxas` would otherwise -// reject them). -// -// References: -// - PTX ISA 8.5 §9.7.12 "Parallel Synchronization Instructions: -// mbarrier" -// - CUDA Hopper Tuning Guide §1.4.1.2 "Asynchronous Memory Copy with -// mbarrier" +// Reference: PTX ISA §9.7.12; CUDA Hopper Tuning Guide §1.4.1.2. /** * @brief Convert a generic SHM pointer to a 32-bit shared state-space @@ -218,19 +180,20 @@ __device__ static __forceinline__ std::uint32_t cvta_to_shared_u32(const void* p /** * @brief Initialize an mbarrier in SHM. * - * Sets the arrival counter to `arrival_count` and the transaction-bytes - * counter to 0. Must be called exactly once per barrier before any - * arrive / wait, and must be followed by a release fence - * (`fence.mbarrier_init.release.cluster`) before any remote arrival - * or TMA issue targeting this barrier. - * - * @param bar 16-B aligned pointer to the barrier in SHM. - * @param arrival_count Expected number of `mbarrier.arrive*` calls - * (typically 1 for TMA-only completion). + * Must run exactly once per barrier before any arrive/wait, and must be + * followed by `fence_mbarrier_init_release_cluster()` before any remote + * arrival or TMA issue targeting the barrier. */ __device__ static __forceinline__ void mbarrier_init(std::uint64_t* bar, std::uint32_t arrival_count) { - cute::initialize_barrier(*bar, static_cast(arrival_count)); +#if (defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 900) + std::uint32_t bar_addr = cvta_to_shared_u32(bar); + asm volatile("mbarrier.init.shared::cta.b64 [%0], %1;\n" ::"r"(bar_addr), "r"(arrival_count)); +#else + (void)bar; + (void)arrival_count; + asm volatile("trap;"); +#endif } /** @@ -254,21 +217,46 @@ __device__ static __forceinline__ void fence_mbarrier_init_release_cluster() { /** * @brief Arrive on an mbarrier and set its transaction-bytes counter. * - * Combined arrive + expect_tx operation: - * - Decrements the arrival counter by 1. - * - Adds `tx_bytes` to the transaction-bytes counter. - * - * Consumers synchronize via `mbarrier_try_wait_parity`. Callers must issue - * the TMA (`cp.async.bulk.tensor.*`) targeting this same barrier *after* this - * call so the hardware-emitted `complete_tx` decrements the counter we just - * primed. - * - * @param bar 16-B aligned pointer to the barrier in SHM. - * @param tx_bytes Expected total bytes the TMA engine will deliver. + * The caller must issue the TMA(s) targeting this barrier AFTER this call; + * `tx_bytes` must cover the total bytes of every TMA pointing at it. */ __device__ static __forceinline__ void mbarrier_arrive_expect_tx(std::uint64_t* bar, std::uint32_t tx_bytes) { - cute::set_barrier_transaction_bytes(*bar, tx_bytes); +#if (defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 900) + std::uint32_t bar_addr = cvta_to_shared_u32(bar); + [[maybe_unused]] std::uint64_t state; + asm volatile("mbarrier.arrive.expect_tx.shared::cta.b64 %0, [%1], %2;\n" + : "=l"(state) + : "r"(bar_addr), "r"(tx_bytes) + : "memory"); +#else + (void)bar; + (void)tx_bytes; + asm volatile("trap;"); +#endif +} + +/** + * @brief Plain arrive on an mbarrier (no transaction bytes). + * + * Consumer-side "slot empty" signal for producer/consumer pipelines: each + * consuming warp arrives once per phase after its last read of the guarded + * buffer; the producer waits the phase via mbarrier_try_wait_parity before + * overwriting. The arrive carries release semantics for the consumer's + * prior SHM reads. + */ +__device__ static __forceinline__ void mbarrier_arrive(std::uint64_t* bar) { +#if (defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 900) + std::uint32_t bar_addr = cvta_to_shared_u32(bar); + [[maybe_unused]] std::uint64_t state; + asm volatile("mbarrier.arrive.shared::cta.b64 %0, [%1];\n" + : "=l"(state) + : "r"(bar_addr) + : "memory"); +#else + (void)bar; + asm volatile("trap;"); +#endif } /** @@ -319,61 +307,21 @@ __device__ static __forceinline__ bool mbarrier_try_wait_parity(std::uint64_t* b } // ── Hopper TMA bulk-tensor copy (sm_90a) ────────────────────────────────── -// -// Thin PTX wrapper around `cp.async.bulk.tensor.2d.shared::cluster.global.tile. -// mbarrier::complete_tx::bytes`. The TMA engine reads a rectangular tile -// from a tensor in global memory (described by a host-built `CUtensorMap`) -// and writes it into shared memory, decrementing the transaction-bytes -// counter of the supplied mbarrier as bytes land. -// -// Caller contract: -// - Issued by exactly one thread in the block (the "TMA launcher"). -// - `desc` is a `__grid_constant__ CUtensorMap const` kernel parameter, -// or otherwise lives in memory coherent with every thread. Passing a -// generic C++ reference keeps the source readable; the PTX operand -// is its address, fetched via `&desc`. Parameter-space addresses are -// coherent with all threads on SM90+, so no `cvta.param.u64` is -// required — the driver-supplied descriptor address is already usable -// as a 64-bit global-coherent pointer (this matches the usage pattern -// in CUTLASS SM90 TMA helpers and in `gpt_oss_router_gemm.cuh`). -// - The caller must pre-arm `bar_smem` once with -// `mbarrier_arrive_expect_tx(bar_smem, tx_bytes)` where `tx_bytes` -// covers every TMA issue pointing at this same barrier, before -// calling this function. The hardware `complete_tx` emitted by each -// TMA decrements that counter. -// -// Coordinate convention matches `cuTensorMapEncodeTiled`: -// - `coord0` is along the innermost (fastest) global axis. -// - `coord1` is along the outer axis. -// For our use cases both descriptors have innermost = K, so `coord0 = -// k_start`. -// -// References: -// - PTX ISA §9.7.8.24 "cp.async.bulk.tensor" -// - CUDA Hopper Tuning Guide §1.4.1.2 -// - CUTLASS `include/cute/arch/copy_sm90_tma.hpp` /** * @brief Issue one 2D TMA bulk-tensor load, tracked by an mbarrier. * - * Emits: - * `cp.async.bulk.tensor.2d.shared::cluster.global.tile.mbarrier::complete_tx::bytes` - * ` [dst_smem_addr], [desc, {coord0, coord1}], [bar_smem_addr];` - * - * The instruction returns immediately; the TMA engine performs the copy - * asynchronously and signals completion on `bar_smem` via the - * transaction-bytes mechanism. Consumers wait via - * `mbarrier_try_wait_parity`. - * - * Byte count per issue is determined by the descriptor's `boxDim` and - * element type, NOT by this wrapper — it is the caller's responsibility - * to sum all issues' byte counts into `tx_bytes` when arming the barrier. + * The TMA engine copies one `boxDim` tile of the tensor described by + * `desc` (a `__grid_constant__ CUtensorMap` kernel parameter — parameter + * space is coherent with all threads on SM90+) into SHM, decrementing the + * barrier's transaction-bytes counter as bytes land. Returns immediately. * - * @param desc `__grid_constant__` 2D tensor descriptor. - * @param coord0 Tile coordinate along the innermost global axis. - * @param coord1 Tile coordinate along the outer global axis. - * @param dst_smem 16-B aligned SHM destination pointer. - * @param bar_smem 16-B aligned SHM barrier (pre-armed with `expect_tx`). + * Caller contract: + * - Issued by exactly one thread in the block (the TMA launcher). + * - `bar_smem` must be pre-armed with `mbarrier_arrive_expect_tx` + * covering the total byte count of every TMA issue targeting it. + * - Coordinate order matches `cuTensorMapEncodeTiled`: coord0 = innermost + * (fastest) global axis, coord1 = outer axis. */ __device__ static __forceinline__ void tma_load_2d(CUtensorMap const& desc, std::uint32_t coord0, std::uint32_t coord1, void* dst_smem, @@ -382,11 +330,8 @@ __device__ static __forceinline__ void tma_load_2d(CUtensorMap const& desc, std: std::uint32_t dst_addr = cvta_to_shared_u32(dst_smem); std::uint32_t bar_addr = cvta_to_shared_u32(bar_smem); std::uint64_t desc_addr = reinterpret_cast(&desc); - // `.shared::cluster` dst (not `.shared::cta`, which needs PTX ISA 8.6 / - // CUDA 12.8+ and fails on older ptxas). Equivalent for a non-cluster - // launch; same form CUTLASS emits in cute/arch/copy_sm90_tma.hpp. asm volatile( - "cp.async.bulk.tensor.2d.shared::cluster.global.tile" + "cp.async.bulk.tensor.2d.shared::cta.global.tile" ".mbarrier::complete_tx::bytes" " [%0], [%1, {%2, %3}], [%4];\n" : diff --git a/docs/design_docs/monomoe_kernel.md b/docs/design_docs/monomoe_kernel.md index 6ddc00eb644..8bc00f131f5 100644 --- a/docs/design_docs/monomoe_kernel.md +++ b/docs/design_docs/monomoe_kernel.md @@ -1,239 +1,503 @@ -# MonoMoe kernel — design - -A single-kernel ("mono") top-K MoE for the Qwen3.5-35B block-FP8 shape on -Hopper (SM90a). One `cudaLaunchKernel` of `moe_kernel_topk` runs the whole -MoE — routing, up-projection + SiLU, down-projection, reduction — with grid-wide -ordering between phases provided by software barriers (no cooperative-groups -launch, so it is CUDA-Graph-capturable). - -This document is the single home for the cross-cutting concepts. Source comments -in `csrc/fused_moe/monomoe/` describe what a given line does and link here -(`see docs/design_docs/monomoe_kernel.md §N`) for the shared "why". When you -change a mechanism, update the section here rather than re-explaining it in -another file. - -Fixed shape (`Dims_BS8_E256_Qwen3_5_35B_BlockFP8_WGMMA_TMA`, see -`csrc/fused_moe/monomoe/src/moe_interface.h`): `E=256` experts, -`K = HIDDEN_STATES = 2048`, `N = 512` -(gate and up each have `N` rows), `BS ≤ 8` tokens, block-FP8 (128×128) weights, -`GRID_SIZE = 128`, `BLOCK_SIZE = 384` (12 warps). The kernel is hard-specialized -to this shape; `BS ≤ 8` is enforced by `static_assert`. - ---- - -## §1 — Five-phase pipeline - -`moe_kernel_topk` → `moe_kernel_topk_BS8` runs five phases separated by two -grid-wide syncs. Warps within a block split into **calc warps** `[0, 8)` and -**prefetch warps** `[8, 12)`; the TMA launcher thread is warp 8 lane 0 (see §6). - -| Phase | What | Sync after | -|-------|------|------------| -| 1 | Routing (softmax/sigmoid top-K + optional renormalize) on calc warps, **in parallel** with the prefetch warps issuing the routing-window TMA that pulls the full per-block BF16 input tile into `bf16_in_full`. | block `__syncthreads()` | -| 2 | warp 0 runs `prepare_moe_topk_BS8` (expert ids, `sorted_slot`, `expert_slot_start[]`); warps 1..11 wait on `bar_rwin` then quantize BF16→FP8 into `fp8_act_full` + `act_scale`. | block `__syncthreads()` | -| 3 | Up-projection: streaming dual-warpgroup K=128 WGMMA reads FP8 directly from `fp8_act_full` → SiLU → FP8 writeback to `spec->temp_fp8`. | **grid:** Expert_Barrier (§2, site #2) | -| 4 | Down-projection: streaming WGMMA; each block `atomicAdd`s its fp32 partial into the single-buffer `spec->down_partial_out[tok][col]`. | **grid:** ColStripe_Barrier (§2, site #3) | -| 5 | Cast fp32 → bf16 into `activations_out`. | — | - -The two grid syncs are Partial_Barriers, not full `grid_barrier`s: phase 3→4 only -needs the producer/consumer blocks for a given expert group to rendezvous, and -4→5 only the blocks sharing a column stripe. See §2 for why that is sufficient -and §6 for the group geometry (`UP_GRID`, `UP_GROUPS`, `DOWN_GRID`, -`DOWN_GROUPS`). - ---- - -## §2 — Software grid / partial barriers (seed + high-bit protocol) - -Defined in `csrc/fused_moe/monomoe/src/moe_grid_barrier.h`. `grid_barrier` (all blocks) and -`partial_barrier` (a caller-specified arrival set) give -cooperative-groups-equivalent happens-before with a standard launch. The thin -aliases `expert_barrier` / `colstripe_barrier` are `partial_barrier` with the -per-site argument recipe baked in. - -**Counter layout.** Each barrier owns a *Counter_Pair* — two `uint32_t` slots -selected by `phase & 1` (ping-pong). `grid_barrier` uses one pair -(`spec->grid_barrier.slot[2]`); `partial_barrier` uses one pair per id -(`expert_slot[NUM_EXPERTS][2]`, `colstripe_slot[DOWN_GRID][2]`). - -**Protocol** (`N` = arrival count): - -1. `__syncthreads()` — publish pre-barrier per-thread writes within the block. -2. thread 0 issues `__threadfence()` — release the block's pre-barrier *global* - writes so other SMs observe them before our arrival. -3. The **seed block** `atomicExch`es the slot to - `SEED = 0x80000000u - (N - 1)`, then folds back any early arrivals - (`prior & 0x7FFFFFFFu`). Non-seed blocks `atomicAdd(c, 1)`. When all `N` - blocks have contributed, the slot equals `0x80000000u` (bit 31 set). -4. thread 0 spins on `atomicAdd(c, 0u)` (an uncached device-scope read, same - codegen as `ld.acquire.gpu` on SM90) until bit 31 flips. Only thread 0 spins; - the rest of the block waits at the step-6 `__syncthreads()`. -5. `__threadfence()` — post-barrier reads/writes happen-after the bit-31 - observation. -6. `__syncthreads()` — re-gather the block and release the non-spinning threads. -7. `++phase` — next call targets the other ping-pong slot. - -**Why the high bit, and why two slots.** The high bit `0x80000000u` doubles as -the *exit-state marker* left by the previous call on a slot. On entry a slot may -be `0`, `k` (early arrivals), `0x80000000u` (leftover marker), or -`0x80000000u + k`. Masking the seeder's `prior` with `0x7FFFFFFFu` strips the -leftover marker and keeps only the real early-arrival count, so the invariant -`SEED + (N - 1) = 0x80000000u` holds regardless of `atomicExch`/`atomicAdd` -interleaving. The two ping-pong slots guarantee call `N+2`'s seeder cannot -observe a stale high bit from call `N`. This is why the slots are -**self-maintaining**: only the *first* use of a buffer needs host zero-init -(§4); every call afterward resets its slot via the step-3 `atomicExch`. - -**Bound.** `N ≤ GRID_SIZE ≤ 132` on H200, so `SEED ≥ 0x80000000u - 131` never -wraps. The protocol is correct for any `1 ≤ N ≤ 2³¹`. - -**Degenerate `N == 1`** short-circuits (a lone block has nothing to order) but -still `++phase`. `partial_barrier` takes `arrival_count` as a runtime argument -(not a template param) so the primitive isn't instantiated twice; every call -site passes a compile-time constant (`UP_GRID`, `DOWN_GROUPS`), so the compiler -still folds `SEED` and the degenerate gate. - -**Caller contract.** A block MUST NOT call `partial_barrier` for an `id` whose -arrival set it isn't in. Each `phase` is per-(region, id-at-call-site) register -state, initialized to 0 at kernel entry. Seed-block / arrival-set recipe per -site: - -- **Site #2 Expert_Barrier** (phase 3→4): `id = up_group`, - `arrival_count = UP_GRID = 8`, `seed_blockidx = up_group * UP_GRID`. Arrival - set = the 8 blocks with `blockIdx.x / UP_GRID == up_group` — exactly the - blocks that wrote expert group `g`'s `temp_fp8` rows and will read them back. -- **Site #3 ColStripe_Barrier** (phase 4→5): `id = blockIdx.x % DOWN_GRID`, - `arrival_count = DOWN_GROUPS = 16`, `seed_blockidx = id`. The Phase-5 writer - for col stripe `c` is `blockIdx.x == c`, which is in the arrival set and is - the seed. - ---- - -## §3 — Co-residency invariant (why the spin can't deadlock) - -The barrier spin (§2 step 4) is only deadlock-free if every participating block -is resident on the GPU for the kernel's whole lifetime — a block must never spin -waiting on a block that hasn't been scheduled yet. The kernel guarantees this: - -- `GRID_SIZE <= SM_count` so every block gets a slot. The host checks this once - before launch (`csrc/fused_moe/monomoe/monomoe_wrapper.cuh`); `GRID_SIZE` is a - compile-time constant and SM count is a static device property. -- `__launch_bounds__(BLOCK_SIZE, 1)` pins one block per SM. -- Opt-in dynamic SHM (> half the per-SM budget) reinforces one-block-per-SM - occupancy. - ---- - -## §4 — Scratchpad (`MoEGemmSpec`) and zero-init - -The global scratchpad is reinterpreted as a `MoEGemmSpec` (layout in -`csrc/fused_moe/monomoe/src/moe_internal.h`). It holds the inter-phase tensors (`temp_bf16`, -`temp_fp8`, `down_partial_out`) and, at its **tail**, the barrier Counter_Pairs -(`grid_barrier`, `partial_barrier`). The host sizes the buffer from -`sizeof(MoEGemmSpec)` (exported via `monomoe_scratchpad_size`) so Python -never re-derives the layout. - -**Zero-init discipline.** The barrier counters must start at 0 so the first -seeder's `atomicExch` commits the seed cleanly (§2). After that the ping-pong -reset makes the slots self-maintaining, so a given buffer pays the zero-init -*once*. The host keys a guard on `(ptr, size, device)` and `cudaMemsetAsync`es -the whole scratchpad whenever the buffer identity changes — a process-wide -one-shot flag would be wrong, because it would leave a second, distinct -scratchpad (different stream/device, or a freshly-malloc'd buffer) with -uninitialized counters and deadlock the spin. Zeroing the entire scratchpad -(not just the counter tail) is simpler and costs a few hundred µs once on H200. - -**`TEMP_FP8_OFFSET` invariant.** The host builds the down-activation TMA -descriptor (§5) by adding the compile-time `MoEGemmSpec::TEMP_FP8_OFFSET` -to the scratchpad base. That constant MUST equal -`offsetof(MoEGemmSpec, temp_fp8)`, enforced by a `static_assert` in -`csrc/fused_moe/monomoe/monomoe_wrapper.cuh`. New fields (e.g. extra barrier -counters) MUST be appended -*after* `temp_fp8` — anything inserted before it shifts the offset and silently -corrupts TMA fetches. - ---- - -## §5 — TMA descriptors and the tile-major SHM layout - -The BS8 path loads weights and activations with TMA -(`cp.async.bulk.tensor.2d`). Host-side `create_*_tma_desc` factories -(`csrc/fused_moe/monomoe/src/moe_tma.cu`, declared in `…/src/moe_tma.h`) build -the `CUtensorMap`s; the kernel takes them as `__grid_constant__ CUtensorMap -const` params. - -**Caller contracts** (encoded once in the factory doc comments): - -- **Up-projection weights** MUST be pre-interleaved in Python via - `interleave_for_tma_wgmma_up` (gate/up row interleave) so a single 128×128 TMA - fetches one full WGMMA A-tile. SWIZZLE_128B. -- **Down-projection weights** MUST be passed *raw* row-major `[E, K, N]` — the - TMA hardware applies the 8-row × 128-byte core-matrix XOR swizzle at write - time. SWIZZLE_128B, `row_box = DOWN_COL_TILE`. -- **Activations** use SWIZZLE_NONE. The down-activation descriptor reads - `spec->temp_fp8` inside the scratchpad (§4). - -**Tile-major SHM (`bf16_in_full`, `fp8_act_full`).** The BF16 input buffer is -shaped `[K_BLOCKS_TOTAL][BS][K_STEP_WGMMA]`, not the natural -`[BS][HIDDEN_STATES]`. The activation TMA descriptor is configured with -`boxDim = (128, 8)` (innermost = K, outer = tokens), SWIZZLE_NONE, so each -`cp.async.bulk.tensor.2d` writes a compact 8×128 BF16 box (2 KB) whose outer-row -stride equals the inner box dim (256 B), not the logical row stride. With a -`[BS][HIDDEN_STATES]` layout (row stride 4096 B for Qwen3.5) successive K-substep -writes would overlap and corrupt each other. The tile-major layout gives each -K-substep its own self-contained 2 KB slab matching exactly the bytes the TMA -writes, and consumers read `bf16_in_full[kblk][token]` as a natural -`[K_STEP_WGMMA]` row. Total size is unchanged (16 × 8 × 128 × 2 = 32 KB), so the -union with the weight tiles and the ≤ 228 KB per-block SHM budget are unaffected. - -Why 16 × 2 KB issues instead of one 32 KB issue: `cuTensorMapEncodeTiled` caps -per-axis `boxDim` at 256 elements, so a single-issue load with innermost axis -= `HIDDEN_STATES = 2048` is rejected by the Driver API. - -The `temp_fp8` tensor (down-projection input) is written by the Phase-3 epilogue -in a reorganized `[expert, token]` layout, so each expert's routed tokens form a -contiguous slab `[expert_slot_start[id], + routed_token_count[id])`. - ---- - -## §6 — Warp roles and group geometry - -**Warps** (`BLOCK_SIZE = 384` = 12 warps): calc warps `[0, 8)` do routing/top-K; -prefetch warps `[8, 12)` drive TMA and BF16→FP8 quantization. The TMA launcher -thread is warp 8 lane 0 (`is_tma_launcher_thread()`); mbarrier arms and -TMA issues run on it alone, gated so other threads never block on an -uninitialized mbarrier parity. - -**Up-projection groups** (Phase 3): `UP_GRID = 2*N / W_UP_TILE_EFFECTIVE = 8` -blocks cover one expert's `2*N` weight rows; -`UP_GROUPS = GRID_SIZE / UP_GRID = 16` expert groups run in parallel. Group `g` -(blocks `[g*UP_GRID, (g+1)*UP_GRID)`) iterates experts from index `g` stepping by -`UP_GROUPS`. Groups write disjoint `temp_fp8` slabs, so no write conflict. - -**Down-projection groups** (Phase 4): blocks partition into -`DOWN_GROUPS = 16` expert groups × `DOWN_GRID = 8` column blocks; each block owns -`DOWN_COL_TILE = 256` output cols. Phase 2a aligned `DOWN_GROUPS == UP_GROUPS` so -each Expert_Barrier producer set equals its consumer set (§2 site #2). Every -contributing block `atomicAdd`s into the single-buffer `down_partial_out`; Phase -5 reads each cell once (no cross-group reduction). - ---- - -## File map - -Paths are relative to `csrc/fused_moe/monomoe/`. - -| File | Role | -|------|------| -| `monomoe_wrapper.cuh` | host launcher template `monomoe_topk_launcher` (checks §3, zero-inits §4, builds §5 descriptors, launches §1) | -| `monomoe_binding.cu` | TVM-FFI exports (`monomoe_topk`, `monomoe_scratchpad_size`) | -| `src/moe_interface.h` | `Dims` shape, `MoEDimensions`, public kernel decl | -| `src/moe.cuh` | `moe_kernel_topk` / `moe_kernel_topk_BS8` — the §1 pipeline | -| `src/moe_grid_barrier.h` | §2 barriers | -| `src/moe_internal.h` | `MoEGemmSpec` (§4) and `MoE_SHM` layouts, `MoECoreDims` | -| `src/moe_routing.cuh` | Phase 1 routing / top-K (`topK_BS8`, `prepare_moe_topk_BS8`) | -| `src/moe_scale_inputs.cuh` | Phase 2 BF16→FP8 quantization | -| `src/moe_up_projection.cuh` | Phase 3 up-proj + SiLU | -| `src/moe_down_projection.cuh` | Phase 4 down-proj | -| `src/moe_tma.{h,cu}` | §5 TMA descriptor factories | -| `src/ptx_utils.h` | WGMMA / mbarrier / TMA inline-PTX wrappers | +# MoE Monokernel — Design + +A single persistent CUDA kernel that executes an entire FP8 block-wise MoE +layer for small decode batches (BS ≤ 8) on Hopper (sm_90a): routing → up +projection (+SiLU+re-quant) → down projection → weighted combine. One launch, +no intermediate kernel boundaries, capturable into a CUDA Graph. + +Fixed shape (`Dims_BS8_E256_N512_K2048_BlockFP8_WGMMA_TMA`): E=256 experts, +N=512 (`moe_intermediate_size` per half), K=2048 hidden, M ≤ 8 tokens. + +```text +GM in: activations [BS,K] bf16 router_logits [BS,E] bf16 + w_up [E,2N,K] fp8 + block scales [E,2N/128,K/128] fp32 + w_down [E,K,N] fp8 + block scales [E,K/128,N/128] fp32 +GM out: activations_out [BS,K] bf16 +``` + +## Execution model + +- `GRID_SIZE` blocks (default 128), `BLOCK_SIZE = 384` threads = 12 warps. + The whole grid is launched ONCE and persists through all five phases — + no blocks are created or retired between stages; a block changes *role* + (which expert / which output tile it works on) at each phase boundary. +- `__launch_bounds__(BLOCK_SIZE, 1)` + `GRID_SIZE <= SM count` pin one block + per SM. This co-residency invariant is what makes the cross-block + flag/sentinel handoffs (below) deadlock-free: every block is scheduled from + launch, so a block spinning on another block's flag can never wait on a + block that has not yet been scheduled. +- Warp roles (fixed for the whole kernel; the same physical warps take + phase-specific duties, detailed per stage below): + - warps 0–7 (threads 0–255): **calc warps**, forming two WGMMA + warpgroups — WG0 = warps 0–3, WG1 = warps 4–7. A WGMMA is issued by + all 128 threads of a warpgroup together. + - warp 8 lane 0 (thread 256): the single **TMA launcher thread** — + issues every `cp.async.bulk.tensor.2d` and arms every mbarrier in the + block, in all phases. + - warps 8–11 (threads 256–383): **prefetch warps** (PF0–PF3) — scale + loads, the deferred up-proj epilogue, the deferred down-proj + accumulate, and (warps 1–11) the Phase-2 quantization. + +The stage geometry is fixed by the shape's `KernelConfig` (`GRID_SIZE = 128`, +`DOWN_COL_TILE` = DCT = 256, `K_STEP_UP` = KUP = 256, `K_STEP_DOWN` = KDN = 256, +`UP_W_SLOTS` = SLOTS = 4; `UP_COL_HALVES` = UCH is derived). All stage geometry +follows from these and the (E, N, K) dims: + +| derived quantity | formula | value | meaning | +| ----------------- | --------------------------------------- | ----- | ----------------------------------- | +| `UCH` | `max(1, 2N·DCT / (128·K))` | 1 | 128-row M-atoms per up-block | +| `UP_GRID` | `2N / (128·UCH)` | 8 | blocks per expert, up-proj | +| `UP_GROUPS` | `GRID_SIZE / UP_GRID` | 16 | experts in parallel, up-proj | +| `K_TILES_UP` | `K / KUP` | 8 | up-proj outer K iterations | +| `K_SUBSTEPS_UP` | `KUP / 128` | 2 | 128-K substeps per iteration | +| `UP_ARM_DISTANCE` | `max(1, SLOTS − 2)` | 2 | weight-TMA prefetch distance | +| `DOWN_GRID` | `K / DCT` | 8 | blocks per expert, down-proj | +| `DOWN_GROUPS` | `GRID_SIZE / DOWN_GRID` | 16 | experts in parallel, down-proj | +| `DOWN_COL_HALVES` | `DCT / 128` | 2 | 128-col WGMMA passes per K-step | +| `K_TILES_DOWN` | `N / KDN` | 2 | down-proj outer K iterations | +| `K_SUBSTEPS_DOWN` | `KDN / 128` | 2 | 128-K substeps per iteration | +| `K_BLOCKS_TOTAL` | `K / 128` | 16 | routing-window / quantization atoms | + +`UP_GROUPS == DOWN_GROUPS` (16), so the site-#2 producer/consumer sets coincide. +The routing-window tile is 32 KB (BS=8). These constraints hold: `GRID_SIZE` is +a multiple of `UP_GRID` and `DOWN_GRID` and ≤ SM count; `K_TILES_UP` is a +multiple of SLOTS (cross-expert stitch slot alignment); `K_TILES_DOWN` is even +(the inter-expert lookahead lands in the slot the next expert reads); SHM fits +the 224 KB budget. + +## Phase pipeline + +```text +Phase 1 routing (calc warps: topK) ∥ routing-window TMA: + full [BS,K] bf16 tile + → SHM bf16_in_full, + completion on bar_rwin +Phase 2 warp 0: prepare_moe_topk ∥ warps 1..11: wait bar_rwin, + (expert tally / prefix sums / quantize bf16 → fp8_act_full + slot assignment) + per-128-K act_scale + __syncthreads() — publishes both +Phase 3 up-projection (WGMMA + weight-TMA pipeline) + → spec->temp_fp8 (expert-sorted rows) + temp_act_scale +Site #2 NO barrier — sentinel handoff: each act-scale cell doubles as the + readiness flag for its fp8 payload; the down-proj polls the cells + it consumes (per-expert granularity) +Phase 4 down-projection (WGMMA + weight/activation TMA double-buffer) + → atomicAdd into spec->down_partial_out [BS,K] fp32 +Site #3 NO barrier — flag counters: each block bumps its col stripe's + arrival counter; only that stripe's Phase-5 writer polls it +Phase 5 fp32 → bf16 cast + writeback (first DOWN_GRID blocks only) +``` + +Zero-fill of `down_partial_out` happens at kernel entry with no cross-block +sync: every block runs the full routing+quantize+up-proj pipeline (tens of µs) +before its first Phase-4 atomicAdd, while the zero-fill retires within the +launch's first ~µs. Phase 5 `=`-writes every output element, so no output +pre-zero pass or extra grid sync exists. + +## Stage-by-stage execution detail + +### Phase 1 — routing ∥ input prefetch (all GRID_SIZE blocks, replicated) + +Every block executes Phase 1 identically and independently — routing and +the input tile are needed by every block later, and each block has its own +SHM, so the work is *replicated* across the grid rather than partitioned +(the work is tiny: 8 tokens × E logits). No cross-block communication. + +Within one block, two things run concurrently: + +- **Calc warps 0–7 — top-k routing (`topK`)**: one warp per token + (warp w handles token w; warps ≥ `batch_size` return immediately). + Within a warp, lane t owns experts `{t, t+32, t+64, ...}` in registers + (`E/32` per lane — 8 for E=256). The warp runs `top_k` rounds of + warp-reduce-argmax and lane 0 writes the token's ids/weights to + `topk_ids_flat` / `topk_weights_flat`. Then `sync_calc_threads()` + (a 256-thread `bar.sync`) joins the 8 warps. +- **Warp 8 lane 0 — routing-window TMA**: arms `bar_rwin` once with the + full tile's byte count, then issues `K_BLOCKS_TOTAL = K/128 = 16` bulk + TMAs, one 8-token × 128-K bf16 box each, filling + `bf16_in_full`. Warp 8 lanes 1–31 and warps 9–11 are idle in Phase 1. + +### Phase 2 — routing tables ∥ quantization (all GRID_SIZE blocks, replicated) + +Warp split within each block: + +- **Warp 0 (lanes 0–31) — `prepare_moe_topk`**: single-warp, three + sub-phases (A tally, B fused prefix scans, C slot assignment) building + `experts[]`, `expert_count`, `expert_slot_start[]`, + `expert_routed_count[]`, `sorted_slot[]`, `down_rank[][]`. Warp 0 never + reads `bf16_in_full`, so it skips the `bar_rwin` wait. +- **Warps 1–11 (11 warps, 352 threads) — `routing_phase_quantize`**: each + thread first waits on `bar_rwin` (the Phase-1 TMA completion), then the + 11 warps split the `BS × K_BLOCKS_TOTAL` (token, 128-K-block) pairs + (128 pairs) stride-11 by warp. Each pair = one warp call to + `moe_streaming_quantize_k128`: 32 lanes × 4 bf16 values, warp-reduce + max, fp8 quantize into `fp8_act_full`, one scale into `act_scale`. + Note this uses calc warps 1–7 too — the Phase-1 role split does not + apply here; only warp 0 is reserved. + +One trailing `__syncthreads()` publishes both sides to all 12 warps. +There is intentionally no other sync between warp 0 and warps 1–11 — they +write disjoint SHM. + +### Phase 3 — up-projection (grid partitioned: UP_GROUPS × UP_GRID) + +Block assignment: `up_group = blockIdx.x / UP_GRID`, +`up_block_idx = blockIdx.x % UP_GRID`. + +- **Blocks per expert**: `UP_GRID = 2N/(128·UCH)` blocks jointly produce + one expert's full `2N` intermediate rows; block `up_block_idx` owns rows + `[up_block_idx · 128·UCH, +128·UCH)`. Here: 8 blocks × 128 rows (64 gate + + 64 up features each, interleaved — UCH = 1). +- **Experts in parallel**: `UP_GROUPS = GRID_SIZE/UP_GRID` = 16 expert groups + run concurrently, one active expert per group at a time. +- **Expert loop**: group g iterates the *active* expert list (built by + Phase 2, ascending id, length `expert_count ≤ min(E, BS·top_k)`) as + `e = g, g + UP_GROUPS, g + 2·UP_GROUPS, ...`. Each group therefore + visits ≤ `ceil(expert_count / UP_GROUPS)` experts — with BS=8, top_k=8 + at most 64 are active, so ≤ 4 per group at UP_GROUPS=16. A group whose + index exceeds `expert_count` skips Phase 3 entirely and waits at the + site-#2 barrier. +- **Per expert, warp duties**: + - warps 0–7 (WG0 + WG1): the K-loop — `K_TILES_UP = K/KUP = 8` + iterations, each + waiting `bar_w[s % SLOTS]` then chaining 4 WGMMAs per 128-K substep + per M-atom, with scale-apply at every 128-K boundary. WG0 computes + SHM weight rows [0..63] of each atom, WG1 rows [64..127]. At the + K-loop tail they do the per-lane `rw·up·silu(gate)` combine into + `post_silu_scratch` and snapshot the rank cache. 8 calc threads + (one per token) also populate the per-expert routing cache at the + K-loop top. + - warp 8 lane 0 (launcher): inside each K-iteration, arms + TMAs the + weight slot `UP_ARM_DISTANCE = max(1, SLOTS−2)` iterations ahead; on + the last `UP_ARM_DISTANCE` iterations it stitches the *next* expert's + first tiles instead, so the pipeline never drains across experts. + - warp 8 (lanes 0–31, as PF warp 0): cp.async-prefetches the *next* + expert's block-scale tile into the `up_scale` ping-pong during the + current K-loop. + - warps 8–11 (PF0–PF3): the **deferred epilogue of the previous + expert** — one warp per token, `ceil(BS/4)` waves spaced across the + first `K_TILES_UP - 1` iterations: read `post_silu_scratch`, + warp-reduce max over the block's 64 features, + fp8-quantize, store to `temp_fp8[sorted_slot_row]` + + `temp_act_scale`. The last visited expert has no successor and + drains inline on calc warps after the loop (one token per warp). + +### Site #2 — Phase 3 → 4 handoff (sentinel, no barrier) + +No barrier counter is involved. Each `temp_act_scale` cell is +release-published by its producing up-proj warp *after* the covering fp8 +payload segment (`moe_publish_act_scale`), and the down-projection polls +exactly the cells it consumes until they turn non-sentinel before reading +the payload. This gives per-expert granularity — a down-block starts an +expert as soon as THAT expert's rows are published (consumers wait on data, so +no barrier-counter protocol is needed). See "Cross-block synchronization" +for the sentinel value and reset discipline. + +### Phase 4 — down-projection (grid re-partitioned: DOWN_GROUPS × DOWN_GRID) + +The same 128 blocks re-map: `down_group = blockIdx.x / DOWN_GRID`, +`down_block_idx = blockIdx.x % DOWN_GRID`, +`base_col = down_block_idx · DOWN_COL_TILE`. + +- **Blocks per expert**: `DOWN_GRID = K/DCT = 8` blocks jointly + cover one expert's `K` output columns; each block owns `DCT = 256` + columns = `DOWN_COL_HALVES = DCT/128 = 2` sequential + 128-col WGMMA passes per K-step. +- **Experts in parallel**: `DOWN_GROUPS = GRID_SIZE/DOWN_GRID = 16` groups. +- **Expert loop**: `e = down_group, down_group + DOWN_GROUPS, ...` over + the same active-expert list. Note the up and down loops visit experts + in a different interleaving; correctness needs only that Phase 3 + finished the expert before Phase 4 reads it, which site #2 guarantees. +- **Per expert, warp duties**: + - warps 0–7: K-loop of `K_TILES_DOWN = N/KDN = 2` iterations, + each + waiting `bar_w[s&1]` + `bar_a[s&1]` (weight + activation double + buffers) then running the lo/hi WGMMA chains per substep per + col-half with scale-apply; at the loop tail they write the + accumulators to `down_out` in SHM. + - warp 8 lane 0 (launcher): prefetches K-step s+1 during step s; on + the last step prefetches the *next expert's* step-0 weight + + activation tiles instead (inter-expert lookahead). The activation + tile is one bulk TMA per 128-K substep covering all ≤ 8 routed rows + of the expert (fetched from the contiguous `temp_fp8` slab). + - warp 8 (PF0): loads the expert's per-token activation scales; + warp 9 (PF1): loads the expert's weight scales — both once per + expert, in parallel, before the K-loop. + - warps 8–11 (128 PF threads): the **deferred accumulate of the + previous expert** — `out_accum[tok][col] += down_out[col][rank]`, + the (tok, col) plane sliced across the first `K_TILES_DOWN − 1` + iterations (a single slice at s=0, since `K_TILES_DOWN = 2`). The + last visited expert's accumulate runs after the loop with all 12 + warps. +- After the expert loop: every block `atomicAdd`s its + `out_accum[BS][DOWN_COL_TILE]` slice into the global + `down_partial_out[BS][K]` (so each output cell receives + `DOWN_GROUPS` atomic adds). + +### Site #3 — Phase 4 → 5 handoff (flag counters, no barrier) + +`down_partial_out` is atomicAdd-accumulated, so readiness can't live in the +data. Instead every block bumps its col stripe's parity-selected arrival +counter (`down_ready[parity][blockIdx.x % DOWN_GRID]`, fence + add) after its +Phase-4 adds, and ONLY the stripe's single Phase-5 writer polls it up to +`DOWN_GROUPS`. The other blocks publish and run to kernel exit — no +grid-wide mutual spin (the old col-stripe barrier made all GRID_SIZE blocks +wait). + +### Phase 5 — writeback (first DOWN_GRID blocks only) + +Only blocks with `blockIdx.x < DOWN_GRID` (8) write: all 384 +threads of each stream-cast the block's own `DCT`-column stripe of +`down_partial_out` from fp32 to bf16 in `activations_out`, and zero-fill +the padding tokens `[batch_size, BS)`. The remaining +`GRID_SIZE − DOWN_GRID` blocks (120) exit after the site-#3 +barrier. + +## Grid carve + +Both projections partition the grid into groups that process different +experts in parallel: + +- Up: each block owns `UP_COL_HALVES` (UCH) stacked 128-row WGMMA M-atoms of + the `[2N, K]` weight matrix. + `UP_GRID = 2N / (128·UCH)` blocks cover one expert; + `UP_GROUPS = GRID_SIZE / UP_GRID` experts run in parallel. + Group g handles experts `g, g+UP_GROUPS, ...` in `shmem->experts[]` order. +- Down: each block owns `DOWN_COL_TILE` (DCT) output columns of `[K]`. + `DOWN_GRID = K / DCT`, `DOWN_GROUPS = GRID_SIZE / DOWN_GRID`. + +**Producer/consumer coupling.** The site-#2 handoff is symmetric: the 8 +blocks that produced an expert's `temp_fp8` rows are exactly the 8 blocks that +consume them, i.e. `UP_GROUPS == DOWN_GROUPS` (16). This holds because +`UCH = 2N·DCT / (128·K)` = 1 for this shape. + +**Interleaved up-proj weights (UCH == 1).** One 128-row A-tile packs 64 gate ++ 64 up rows in the gate/up *pair layout*. The tensor must be pre-interleaved +in Python (`interleave_for_tma_wgmma_up`) so a single 128×128 TMA fetches one +full WGMMA A-tile. Each lane then holds gate and up for the same output +feature, so silu(gate)·up is a register-local combine. + +## Up-projection mechanics (Phase 3 deep-dive) + +Per-expert loop; per expert a K-loop over `K_TILES_UP = K / K_STEP_UP` outer +steps, each step = `K_SUBSTEPS_UP` 128-K substeps (128 = SWZ128 atom width = +FP8 block-scale granularity). + +Weight-TMA lookahead pipeline: `UP_W_SLOTS` (S) physical `bar_w`/`w_wgmma` +slots, arm distance `A = max(1, S-2)`. At iter s the launcher arms slot +`(s+A) % S` for logical iter s+A; calc warps wait `bar_w[s % S]`. The last A +iters of an expert *stitch* the next expert's iters [0, A) into slots [0, A), +so the mbarrier parity chain carries across the expert boundary with no +barrier reinit (this requires `K_TILES_UP % S == 0`). A slot is never +re-armed before its previous consumer wait completed +(wraparound safety: `S >= A + 2` by construction). The per-slot parity +registers are hoisted OUT of the expert loop (like the down-proj's): a slot +completes `K_TILES_UP / S` phases per expert, and when that quotient is odd +(e.g. K_TILES=12, S=4) the mbarrier ends the expert at phase 1 — a +per-expert parity reset would then let the next expert's first wait pass on +the stale phase and corrupt the arm/wait pairing. + +Per 128-K substep, each WG chains 4 `wgmma.mma_async.m64n8k32.e4m3` reading: + +- A = weight tile from `w_wgmma` (SWZ128 canonical Major::K, LBO=16, + SBO=1024, swizzle=1), +- B = activations from `fp8_act_full` (SWIZZLE_NONE; LBO=144 — see SHM), + +then applies `weight_scale × act_scale` at the 128-K boundary into fp32 +accumulators. + +Cross-expert latency hiding: + +- the next expert's block-scale tile is prefetched via `cp.async` into a + ping-pong `up_scale[2]` buffer during the current K-loop; +- a per-expert routing cache (`up_rank_for_tok` / `up_rw_for_tok`) is + populated by 8 calc threads with one 16-B vector load per token, replacing + a dependent SHM scan; the same pre-K-loop `__syncthreads()` publishes both. + +**Deferred epilogue.** At the K-loop tail, calc warps only do the per-lane +`rw·up·silu(gate)` combine (`__fdividef` + `__expf`) and store fp32 to +`post_silu_scratch[feature][tok]`, plus snapshot the rank cache to +`up_rank_for_tok_prev`. The expensive part — warp-reduce max, fp8 quantize, +GM stores into `temp_fp8`/`temp_act_scale` — is *deferred to prefetch warps +inside the NEXT expert's K-loop* (one warp per token, waves spaced across the +first `K_TILES-1` iterations so DRAM store bursts don't bunch and the last +iter stays free for the cross-expert stitch). This is numerically +schedule-invariant: `post_silu_scratch` holds the previous expert's values +for the whole current K-loop, and routing tables are immutable. The last +expert in a block's range has no successor and drains inline on calc warps +after the loop. + +Output layout: the writeback row is `sorted_slot[tok·top_k + k]` — Phase 2 +assigns each routed (token, expert) pair a row so that each expert's tokens +occupy a *contiguous slab* `[expert_slot_start[id], +routed_count)` of +`temp_fp8`. That contiguity is what lets Phase 4 fetch a whole expert's +activations with one bulk TMA. One fp8 scale per (row, up-block) goes to +`temp_act_scale` (block size along N = UCH·64 features). + +## Down-projection mechanics (Phase 4 deep-dive) + +Per-expert loop with stride `DOWN_GROUPS` starting at `down_group`. Per +expert: + +- Prefetch warps load the expert's weight scales (warp 9) and the per-token + activation scales for the *whole* expert (warp 8) — hoisted out of the + K-loop. The activation-scale SHM layout is `[block][tok]` + (bank-conflict-free broadcast in the scale-apply). +- K-loop over `K_TILES_DOWN = N / K_STEP_DOWN` with a 2-slot weight + + activation TMA double-buffer (`bar_w[0..1]`, `bar_a[0..1]`, reinitialized in + the down-proj prologue). The launcher prefetches step s+1 during step s; + at the last step it instead prefetches the *next expert's* step-0 tiles + (inter-expert lookahead — requires `K_TILES_DOWN` even so the freed slot is + the one the next expert's s=0 wait reads). Parity state is hoisted out of + the expert loop and never reset. +- When `routed_count == 0` for an expert, no activation TMA is armed; the + WGMMA computes on garbage, but the rank-filtered accumulate never reads or + accumulates those results (every token's `rank` is `0xFF` for an unrouted + expert), so the garbage cannot reach the output. +- Epilogue: accumulators → `down_out[DCT][8]` in SHM. The + `out_accum[tok][col] += down_out[col][rank]` accumulate for the *previous* + expert runs deferred on prefetch warps, sliced across the first + `K_TILES_DOWN - 1` K-steps (the last step stays clean so the read of + `down_out` fully drains before this expert's epilogue overwrites it). + `rank = down_rank[expert_id][tok]` was recorded once in routing Phase C + (0xFF = token not routed to that expert) — nothing is recomputed here. +- After the expert loop: final accumulate for the last expert (all warps), + then `atomicAdd` of `out_accum` into the single global + `down_partial_out[BS][K]` buffer. Phase 5 reads each cell exactly once — + no cross-group reduction pass. + +## Routing mechanics (Phase 1/2 deep-dive) + +`topK` (one warp per token, experts distributed lane-cyclically, +`NUM_EXPERTS % 32 == 0` keeps score arrays in registers): + +- Fast path (softmax+renormalize, or sigmoid): select top-k on raw logits + (activations are monotone), then exponentiate only the k winners; for + softmax+renorm the global denominator cancels. Softmax+no-renorm needs the + full denominator and falls back to a full warp softmax. +- Ties break toward the lowest expert *index* (matching vLLM `topk_softmax`), + not the lowest lane. +- Optional GLM-style biased selection: rank by `sigmoid(logit) + bias[e]`, + weight stays the unbiased sigmoid (recovered as `metric - bias`); + `routed_scaling_factor` is folded into the shared normalizer. + +`prepare_moe_topk` (warp 0 only, 3 phases): + +- A: vectorized zero of `expert_routed_count`, 0xFF-seed of `down_rank`, + tally via `__match_any_sync` with routed pair eids cached in registers. +- B: fused dual warp scan (routed-count prefix + active-expert prefix) → + `expert_slot_start[]` (packed u16 stores), `experts[]` (ascending eid), and + `expert_count`. +- C: intra-expert rank per pair via `__match_any_sync` + cross-chunk carry → + `sorted_slot[pair]` and `down_rank[eid][tok]`. + +## Shared memory (`MoE_SHM`, ≤ 224 KB) + +The dominant space is a union whose members have strictly disjoint lifetimes +(separated by the Phase-2 trailing sync and the site-#2 barrier): + +| view | phase | size (N512_K2048 cfg0) | +| -------------------------------------- | ----- | --------------- | +| `bf16_in_full[K/128][BS][128]` | 1–2 | 32 KB | +| `w_wgmma[UP_W_SLOTS][M_total][128]` | 3 | 64 KB | +| `w_down_wgmma[2][DCT·K_SUBSTEPS][128]` | 4 | dominates | + +Other notable fields: + +- `fp8_act_full[K/128][8][T_TILE+1][16]` — single-buffer fp8 activations for + the whole K range (Phase 3 reads with no slot alternation). The 9th + token row per 16-B chunk is padding: it moves the chunk stride from 128 B + to 144 B so the routing-quantize stores and the WGMMA B reads are + bank-conflict-free. The WGMMA B descriptor's `LBO = 144` steps over the + pad. +- `a_down_wgmma[2][K_SUBSTEPS_DOWN][8][8][16]` — down-proj activation + double-buffer (SWZ128 atoms). +- `partial_result` union: `wgmma_out[128][9]` / `down_out[DCT][8]` / + `post_silu_scratch[UCH·128][9]` — the +1 column padding makes the + `[col][tok]` read pattern bijective over banks (gcd(9,32)=1). +- mbarriers (`bar_w[UP_W_SLOTS]`, `bar_a[2]`, `bar_rwin`), `alignas(16)`. +- Routing tables: `expert_slot_start[E]` (u16, `alignas(16)` — Phase B emits + packed STS.128 stores), `expert_routed_count[E]` (u8), + `sorted_slot[BS·8]` (u8), `down_rank[E][BS]` (u8, `alignas(16)` for the + uint4 seed), `up_rank_for_tok[_prev][BS]` + `up_rw_for_tok[BS]` (V2 only). +- `act_scale[K/128][BS]` — transposed `[blk][tok]` layout for conflict-free + scale-apply broadcasts. + +## Global scratchpad (`MoEGemmSpec`) + +Persistent GM workspace, one per process, zeroed once on first launch. +`mono_moe` allocates it automatically when the `scratchpad` argument is +omitted; callers that want to reuse a buffer across launches allocate one +explicitly with `alloc_scratchpad()`, sized by `get_scratchpad_size_bytes()` +(the `monomoe_scratchpad_size` binding, i.e. `sizeof(MoEGemmSpec)`): + +- `temp_fp8[TEMP_ROWS][N]` + `temp_act_scale[TEMP_ROWS][N/DOWN_ACT_BLOCK]` — + Phase 3 → Phase 4 handoff, expert-sorted rows. + **Layout invariant:** the host computes the device address of `temp_fp8` + as `scratchpad + TEMP_FP8_OFFSET` when building the down-activation TMA + descriptor, so no field may ever be inserted before `temp_fp8`; new fields + (handoff flags) go at the tail. A `static_assert` in + `monomoe_binding.cu` enforces this. +- `down_partial_out[BS][K]` fp32 — Phase 4 atomicAdd target. +- sentinel-handoff tail state: `temp_act_scale_alt` (the second scale + buffer), `launch_flip[GRID_SIZE]` (per-block private launch counters → + buffer parity), `down_ready[2][DOWN_GRID]` (Phase-4→5 arrival counters). + +## Cross-block synchronization (flag/sentinel handoffs) + +There are no grid barriers. The kernel launches via plain +`cudaLaunchKernel` (CUDA-Graph capturable) and orders its two cross-block +handoffs through the data path, so consumers wait only on the values they +actually need. Both handoffs rely on the one-block-per-SM co-residency +invariant (a spinning consumer needs its producers scheduled), enforced at +compile time by `__launch_bounds__(BLOCK_SIZE, 1)` and at runtime by the +`GRID_SIZE <= SM count` check in the wrapper. + +**Site #2 (Phase 3 → 4), sentinel-in-data:** each `temp_act_scale` cell +doubles as the readiness flag for the fp8 payload segment it covers. The +producing warp stores the payload, then `__syncwarp()` + +`__threadfence()` + `atomicExch` of the scale (`moe_publish_act_scale`), +clamped to >= FLT_MIN so the sentinel `+0.0f` is never a valid value. The +down-projection polls exactly the cells of the expert it is about to +consume (device-scope atomic reads) before reading scales or issuing the +activation TMA; the inter-expert lookahead TMA has its own sweep-poll +(`moe_wait_expert_scales_published`). This gives per-expert granularity — +down work for an expert starts as soon as that expert's rows are published. + +**Site #3 (Phase 4 → 5), arrival flags:** `down_partial_out` is +atomicAdd-accumulated, so readiness cannot live in the data (a partial sum +looks complete). Each block instead bumps its col stripe's arrival +counter (`__syncthreads()`, `__threadfence()`, `atomicAdd(+1)`) and runs +to exit; only the stripe's single Phase-5 writer polls the counter up to +`DOWN_GROUPS`. + +**Reset discipline (both sites):** flag state must never leak across +launches, so it is double-buffered by launch parity: every block bumps its +private `launch_flip` word once per launch (all blocks agree on parity +with no cross-block sync), the current parity's state is consumed, and the +OTHER parity's state is zero-refilled in the prologue, off the critical +path. A `torch.zeros` scratchpad allocation establishes the invariant for +the first launch — no host-side re-init is ever needed, and the scheme is +CUDA-Graph-replay safe (parity keeps alternating across replays). + +## TMA descriptors + +Four `CUtensorMap`s are built host-side per launch (`moe_tma.cu`) and passed +as `__grid_constant__` kernel parameters: + +| descriptor | tensor | box | swizzle | +| ---------------- | ------------------------------------ | ------- | ------- | +| up weights | `[E·2N, K]` fp8 (interleaved or raw) | 128×128 | 128B | +| activations | `[BS, K]` bf16 | 8×128 | none | +| down weights | `[E·K, N]` fp8 (raw) | 128×128 | 128B | +| down activations | `temp_fp8 [rows, N]` fp8 | 8×128 | 128B | + +The TMA hardware applies the 8-row × 128-B core-matrix XOR swizzle at write +time, producing the canonical CUTLASS Major::K B128 layout that the WGMMA +descriptors read (`LBO=16`, `SBO=1024`, swizzle=1). The activation +descriptor is SWIZZLE_NONE with a compact 8×128 box; the SHM destination is +therefore *tile-major* `[K/128][BS][128]` (each box gets its own 2 KB slab — +a `[BS][K]` layout would make consecutive boxes overlap because the TMA +writes with the box's own row stride, not the destination's logical stride). +The TMA `boxDim` cap of 256/axis is why the routing window is 16 separate +issues and why DCT=384 uses three 128-row weight TMAs per substep. diff --git a/flashinfer/aot.py b/flashinfer/aot.py index cc013bf6e4f..bab8dfeadb5 100644 --- a/flashinfer/aot.py +++ b/flashinfer/aot.py @@ -577,8 +577,9 @@ def gen_all_modules( jit_specs.append(gen_fp8_blockscale_gemm_sm90_module()) jit_specs.append(gen_fp4_quantization_sm90_module()) jit_specs.append(gen_cutlass_fused_moe_sm90_module()) - # MonoMoe kernel: single-kernel block-FP8 top-K MoE, - # Hopper (SM90a) only — uses wgmma.mma_async + TMA. + # MonoMoe kernel: single-kernel block-FP8 top-K MoE, Hopper + # (SM90a) only (uses wgmma.mma_async + TMA). Hard-specialized to + # the fixed E=256/N=512/K=2048 shape (BS8). jit_specs.append(gen_monomoe_module()) if has_sm100: jit_specs.append(gen_fp4_quantization_sm100_module()) diff --git a/flashinfer/fused_moe/monomoe.py b/flashinfer/fused_moe/monomoe.py index 6335bccb9cc..bb6e622310a 100644 --- a/flashinfer/fused_moe/monomoe.py +++ b/flashinfer/fused_moe/monomoe.py @@ -13,18 +13,14 @@ See the License for the specific language governing permissions and limitations under the License. -Single-kernel ("mono") top-K Mixture-of-Experts for the Qwen3.5-35B -block-FP8 shape on Hopper (SM90a). The full pipeline — routing, -up-projection, SiLU, down-projection and reduction — runs inside one -`__global__` launch. See csrc/fused_moe/monomoe/README.md for the design. - -This path is hard-specialized to a single shape: - E (experts) = 256 - N (== N_half) = 512 (up-projection produces 2*N = 1024 rows: gate || up) - K (hidden) = 2048 - BS (token cap) = 8 -Inputs that do not match are rejected up front rather than silently -corrupting memory. +Single-kernel ("mono") top-K Mixture-of-Experts, block-FP8, Hopper (SM90a). +The full pipeline — routing, up-projection, SiLU, down-projection and +reduction — runs inside one `__global__` launch. See +docs/design_docs/monomoe_kernel.md for the design. + +The kernel is hard-specialized to a single fixed shape: E=256 experts, +N=512 (intermediate half), K=2048 (hidden). Token count M <= 8 (the BS8 +kernel). A tensor whose ``(E, N, K)`` is not this shape is rejected up front. """ import contextlib @@ -37,14 +33,14 @@ from ..trace.templates.moe import mono_moe_trace from ..utils import backend_requirement, supported_compute_capability -# Hard-coded geometry of the only compiled variant -# (Dims_BS8_E256_Qwen3_5_35B_BlockFP8_WGMMA_TMA in +_BLOCK = 128 # block-wise FP8 quantization tile (128 x 128) + +# The single hard-specialized shape (must match # csrc/fused_moe/monomoe/src/moe_interface.h). _MONOMOE_E = 256 -_MONOMOE_N = 512 # N_half: gate and up each have N rows +_MONOMOE_N = 512 _MONOMOE_K = 2048 -_MONOMOE_BS = 8 -_BLOCK = 128 # block-wise FP8 quantization tile (128 x 128) +_MONOMOE_BS = 8 # BS8 kernel serves M <= 8 _SCORING_SIGMOID = 0 _SCORING_SOFTMAX = 1 @@ -59,9 +55,10 @@ def _get_monomoe_module(): return load_monomoe_module() except (ImportError, FileNotFoundError, RuntimeError) as e: raise ImportError( - f"Failed to load the MonoMoe kernel CUDA extension via JIT. " - f"Ensure a Hopper (SM90a) GPU and the CUDA toolkit are available and " - f"that csrc/fused_moe/monomoe/ sources exist.\nError: {e}" + "Failed to load the MonoMoe kernel CUDA extension via JIT. Ensure " + "a Hopper (SM90a) GPU and the CUDA toolkit are available and that " + "csrc/fused_moe/monomoe/ sources exist.\n" + f"Error: {e}" ) from e @@ -81,10 +78,8 @@ def has_monomoe() -> bool: def get_scratchpad_size_bytes() -> int: """Return the global scratchpad size (bytes) required by the kernel. - Sourced from the C++ `sizeof(MoEGemmSpec)` (exported as - `monomoe_scratchpad_size`) so the buffer can never desync from the - kernel's struct layout — the software-grid-barrier counters live at the - tail of that struct and must be backed by allocated memory. + Sourced from the C++ ``sizeof(MoEGemmSpec)`` so the buffer can never + desync from the kernel's struct layout. """ mod = _get_monomoe_module() return int(mod.monomoe_scratchpad_size()) @@ -94,22 +89,12 @@ def get_scratchpad_size_bytes() -> int: def alloc_scratchpad(device: torch.device) -> torch.Tensor: """Allocate a zero-initialized scratchpad on ``device`` for the kernel. - Returns a 1-D ``uint8`` tensor sized to ``get_scratchpad_size_bytes()``. - The buffer is reusable across calls (the kernel self-maintains its barrier - counters via the ping-pong reset discipline), so callers should allocate - once and pass the same tensor to every :func:`mono_moe` invocation to avoid - per-call allocation and the one-time counter zero-init on the C++ side. - - Parameters - ---------- - device : torch.device - The CUDA device on which to allocate the scratchpad buffer. - - Returns - ------- - torch.Tensor - A 1-D uint8 tensor of get_scratchpad_size_bytes() bytes, - zero-initialised and placed on *device*. + Returns a 1-D ``uint8`` tensor sized to :func:`get_scratchpad_size_bytes`. + The zero fill establishes the kernel's handoff invariants (the 0.0f + activation-scale sentinel, launch parity counters, and readiness flags — + see docs/design_docs/monomoe_kernel.md §2/§4); afterwards the kernel + self-maintains them, so allocate once and reuse the same tensor for every + :func:`mono_moe` invocation. """ nbytes = get_scratchpad_size_bytes() return torch.zeros(nbytes, dtype=torch.uint8, device=device) @@ -117,24 +102,27 @@ def alloc_scratchpad(device: torch.device) -> torch.Tensor: @flashinfer_api def interleave_for_tma_wgmma_up(w_fp8: torch.Tensor) -> torch.Tensor: - """Repack fp8 up-projection weights so one ``boxDim=(128, 128)`` - SWIZZLE_128B TMA issue fetches a full 128-row x 128-K WGMMA A-tile. + """Repack fp8 up-projection weights for the Pair_Layout WGMMA A-tile. + + Under the pair layout, each warp's 16-row SHM stripe holds 8 gate rows + and 8 up rows, so ``silu(gate) * up`` becomes a per-lane register + operation after the WGMMA (no cross-warp exchange). Input layout: ``[E, 2*N, K]`` row-major fp8 — the first ``N`` rows per expert are gate weights, the last ``N`` are up weights. ``N`` must be a multiple of 64. - Output layout (still ``[E, 2*N, K]``, identical byte footprint): for every - expert ``e`` and every 64-gate-row block ``k`` in ``[0, N/64)``:: + Output layout (still ``[E, 2*N, K]``, identical byte footprint): for + every expert ``e`` and every 64-gate-row block ``b``, the 128-row slab + at ``128*b`` packs, per warpgroup ``wg`` and warp ``w``:: - new[e, 128k + 0:128k+ 32] = gate[e, 64k :64k+32] - new[e, 128k + 32:128k+ 64] = up[e, 64k :64k+32] - new[e, 128k + 64:128k+ 96] = gate[e, 64k+32 :64k+64] - new[e, 128k + 96:128k+128] = up[e, 64k+32 :64k+64] + rows [wg*64 + w*16 .. +8) = gate[e, 64b + wg*32 + w*8 .. +8, :] + rows [wg*64 + w*16 + 8 .. +8) = up[e, 64b + wg*32 + w*8 .. +8, :] Under SWZ128 the TMA applies the 8-row x 128-byte core-matrix XOR swizzle - automatically, so this only rearranges GM rows (no byte-level permutation). - The result is cached on the input tensor as ``_tma_interleaved_up``. + automatically, so this only rearranges GM rows (no byte-level + permutation). The result is cached on the input tensor as + ``_tma_interleaved_up``. The down-projection weights need no preparation — the raw ``[E, K, N]`` row-major fp8 tensor is passed straight through. @@ -143,15 +131,11 @@ def interleave_for_tma_wgmma_up(w_fp8: torch.Tensor) -> torch.Tensor: ---------- w_fp8 : torch.Tensor FP8 up/gate weight tensor with shape [E, 2*N, K] (row-major). - The first N rows per expert are gate weights; the last N are - up weights. N must be a multiple of 64. Returns ------- torch.Tensor - Repacked weight tensor with the same shape and dtype as *w_fp8*, - laid out so that a single TMA boxDim=(128, 128) issue covers a - complete 128-row x 128-K WGMMA A-tile. + Repacked weight tensor with the same shape and dtype as *w_fp8*. """ cached = getattr(w_fp8, "_tma_interleaved_up", None) if cached is not None: @@ -170,14 +154,17 @@ def interleave_for_tma_wgmma_up(w_fp8: torch.Tensor) -> torch.Tensor: blocks = n_half // 64 gate_r = gate.reshape(E, blocks, 64, K) up_r = up.reshape(E, blocks, 64, K) - gate_lo = gate_r[:, :, :32, :] - gate_hi = gate_r[:, :, 32:, :] - up_lo = up_r[:, :, :32, :] - up_hi = up_r[:, :, 32:, :] - # gate_lo, up_lo, gate_hi, up_hi along a new stripe axis -> [E, blocks*128, K] - stripes = torch.stack([gate_lo, up_lo, gate_hi, up_hi], dim=2) - result = stripes.reshape(E, blocks * 128, K).contiguous() + # Per warpgroup (32 rows) and warp (8 rows): gate(8) then up(8) = one + # 16-row warp stripe; 4 warps per WG, 2 WGs per 128-row slab. + gate_wg0 = gate_r[:, :, :32, :].reshape(E, blocks, 4, 8, K) + gate_wg1 = gate_r[:, :, 32:, :].reshape(E, blocks, 4, 8, K) + up_wg0 = up_r[:, :, :32, :].reshape(E, blocks, 4, 8, K) + up_wg1 = up_r[:, :, 32:, :].reshape(E, blocks, 4, 8, K) + + wg0 = torch.stack([gate_wg0, up_wg0], dim=3).reshape(E, blocks, 64, K) + wg1 = torch.stack([gate_wg1, up_wg1], dim=3).reshape(E, blocks, 64, K) + result = torch.cat([wg0, wg1], dim=2).reshape(E, blocks * 128, K).contiguous() with contextlib.suppress(AttributeError, RuntimeError): w_fp8._tma_interleaved_up = result @@ -192,18 +179,39 @@ def _check_shapes( expert_weights_down: torch.Tensor, expert_scales_down: torch.Tensor, ) -> int: - """Validate the fixed-shape contract and return the active token count.""" - E, N, K, BS = _MONOMOE_E, _MONOMOE_N, _MONOMOE_K, _MONOMOE_BS + """Validate the input tensors against the fixed E=256/N=512/K=2048 shape. + + Confirms every operand's extents match the hard-specialized shape and + returns the token count ``m``. A different shape is refused. + """ + E, N, K = _MONOMOE_E, _MONOMOE_N, _MONOMOE_K # Explicit raises (not assert): these validate user-provided tensor # shapes that, if wrong, let the fixed-shape CUDA kernel read/write out - # of bounds. `assert` would be stripped under `python -O`, so the - # checks must always run. + # of bounds. `assert` would be stripped under `python -O`. if activations_in.dim() != 2: raise ValueError(f"activations_in must be [M, K], got {activations_in.dim()}D") + if expert_weights_down.dim() != 3: + raise ValueError( + f"expert_weights_down must be [E, K, N], got {expert_weights_down.dim()}D" + ) + if expert_weights_up.dim() != 3: + raise ValueError( + f"expert_weights_up must be [E, 2*N, K], got {expert_weights_up.dim()}D" + ) + + # (E, N, K) come from the down weights [E, K, N]; must equal the fixed + # shape the kernel is specialized for. + de, dk, dn = (int(x) for x in expert_weights_down.shape) + if (de, dn, dk) != (E, N, K): + raise ValueError( + f"monomoe: unsupported shape (E={de}, N={dn}, K={dk}). This kernel " + f"is hard-specialized to E={E}, N={N}, K={K} only." + ) + m = activations_in.size(0) - if m > BS: - raise ValueError(f"this kernel caps tokens at BS={BS}; got M={m}") + if m > _MONOMOE_BS: + raise ValueError(f"this kernel caps tokens at {_MONOMOE_BS}; got M={m}") if activations_in.size(1) != K: raise ValueError(f"activations K must be {K}, got {activations_in.size(1)}") if tuple(router_logits.shape) != (m, E): @@ -211,7 +219,7 @@ def _check_shapes( f"router_logits must be [{m}, {E}], got {tuple(router_logits.shape)}" ) - # Up weights: interleaved [E, 2*N, K]; up scales block-wise [E, 2N/128, K/128]. + # Up weights: [E, 2*N, K]; up scales block-wise [E, 2N/128, K/128]. if tuple(expert_weights_up.shape) != (E, 2 * N, K): raise ValueError( f"expert_weights_up must be [{E}, {2 * N}, {K}], got {tuple(expert_weights_up.shape)}" @@ -221,11 +229,7 @@ def _check_shapes( f"expert_scales_up must be [{E}, {(2 * N) // _BLOCK}, {K // _BLOCK}], " f"got {tuple(expert_scales_up.shape)}" ) - # Down weights: raw [E, K, N]; down scales block-wise [E, K/128, N/128]. - if tuple(expert_weights_down.shape) != (E, K, N): - raise ValueError( - f"expert_weights_down must be [{E}, {K}, {N}], got {tuple(expert_weights_down.shape)}" - ) + # Down scales block-wise [E, K/128, N/128]. if tuple(expert_scales_down.shape) != (E, K // _BLOCK, N // _BLOCK): raise ValueError( f"expert_scales_down must be [{E}, {K // _BLOCK}, {N // _BLOCK}], " @@ -254,15 +258,9 @@ def _check_mono_moe_supported( Carries the ``@supported_compute_capability([90])`` annotation so the ``@backend_requirement`` wrapper rejects any non-Hopper device with a clear ``BackendSupportedError`` *before* the SM90a-only kernel is JIT - compiled — otherwise a call on, say, SM80 would fail deep inside nvcc - with a cryptic ``wgmma`` / TMA build error. Also runs the fixed-shape - contract validation (delegated to :func:`_check_shapes`) so shape and - architecture support are decided in one place. - - Accepts ``mono_moe``'s full signature because ``@backend_requirement`` - forwards every (default-applied) argument to the checker. Returns - ``True`` when the call is supported; raises ``ValueError`` on a shape - mismatch. + compiled. Also runs the fixed-shape contract validation so shape and + architecture support are decided in one place. The signature mirrors + :func:`mono_moe` because ``@backend_requirement`` forwards all kwargs. """ _check_shapes( activations_in, @@ -291,16 +289,18 @@ def mono_moe( scratchpad: Optional[torch.Tensor] = None, interleave_up: bool = True, ) -> torch.Tensor: - """Single-kernel block-FP8 top-K MoE (Qwen3.5-35B shape, SM90a only). + """Single-kernel block-FP8 top-K MoE (fixed E256/N512/K2048 shape, SM90a). - Fixed shape: E=256 experts, N=512, K=2048 hidden, up to BS=8 tokens. + The ``(E, N, K)`` shape is derived from the weight tensors and must be the + fixed E=256/N=512/K=2048 shape the kernel is specialized for; up to 8 + tokens (the BS8 kernel). Args: activations_in: bf16 input activations ``[M, K]`` (``M <= 8``). router_logits: bf16 router logits ``[M, E]``. - expert_weights_up: fp8_e4m3 up/gate weights ``[E, 2*N, K]``. By default - this function applies :func:`interleave_for_tma_wgmma_up`; pass - ``interleave_up=False`` if the tensor is already interleaved. + expert_weights_up: fp8_e4m3 up/gate weights ``[E, 2*N, K]``. This + function applies :func:`interleave_for_tma_wgmma_up` by default; + pass ``interleave_up=False`` if the tensor is already interleaved. expert_scales_up: fp32 block-wise scales ``[E, 2N/128, K/128]``. expert_weights_down: fp8_e4m3 down weights ``[E, K, N]`` (raw row-major). expert_scales_down: fp32 block-wise scales ``[E, K/128, N/128]``. @@ -332,14 +332,14 @@ def mono_moe( expert_weights_down, expert_scales_down, ) + K = _MONOMOE_K + # The kernel reads the up weights in the interleaved Pair_Layout. if interleave_up: expert_weights_up = interleave_for_tma_wgmma_up(expert_weights_up) if out is None: - out = torch.empty( - m, _MONOMOE_K, dtype=torch.bfloat16, device=activations_in.device - ) + out = torch.empty(m, K, dtype=torch.bfloat16, device=activations_in.device) if scratchpad is None: scratchpad = alloc_scratchpad(activations_in.device) diff --git a/flashinfer/jit/monomoe.py b/flashinfer/jit/monomoe.py index df4faa34693..2f1e47dde6e 100644 --- a/flashinfer/jit/monomoe.py +++ b/flashinfer/jit/monomoe.py @@ -74,7 +74,6 @@ def get_monomoe_uri() -> str: "src/moe_scale_inputs.cuh", "src/moe_interface.h", "src/moe_internal.h", - "src/moe_grid_barrier.h", "src/moe_tma.h", "src/ptx_utils.h", ] @@ -86,9 +85,10 @@ def gen_monomoe_module(): Generate the JIT compilation spec for the MonoMoe kernel. Compiles the single-kernel top-K MoE pipeline (routing, up-projection, - SiLU, down-projection, reduction) for the Qwen3.5-35B block-FP8 - WGMMA+TMA path. Hopper (SM90a) only — the kernel uses - `wgmma.mma_async` and TMA, which require SM90. + SiLU, down-projection, reduction) for the block-FP8 WGMMA+TMA path, + hard-specialized to the fixed E=256/N=512/K=2048 shape (BS8, M <= 8). + Hopper (SM90a) only — the kernel uses `wgmma.mma_async` and TMA, which + require SM90. Returns: JitSpec that can be built and loaded. diff --git a/tests/moe/test_monomoe.py b/tests/moe/test_monomoe.py index cce15b07da9..68bbfd7c5e4 100644 --- a/tests/moe/test_monomoe.py +++ b/tests/moe/test_monomoe.py @@ -1,27 +1,33 @@ """Accuracy test for the single-kernel block-FP8 MoE (monomoe). -The kernel is hard-specialized to the Qwen3.5-35B shape on Hopper (SM90a): -E=256 experts, N=512, K=2048, up to BS=8 tokens, block-wise (128x128) FP8 -weights with per-token-dynamic 1x128 activation quantization. +The kernel serves the fixed E=256/N=512/K=2048 shape on Hopper (SM90a): +block-wise (128x128) FP8 weights, per-token-dynamic 1x128 activation +quantization, up to 8 tokens (the BS8 kernel). -The Python reference replicates the kernel's exact math (block-wise dequant -GEMM, SiLU gating, block-wise re-quant of the intermediate, block-wise down -GEMM) so the comparison is apples-to-apples in fp8. +The block-FP8 Python reference (inlined below) replicates the kernel's exact +math (block-wise dequant GEMM, SiLU gating, block-wise re-quant of the +intermediate, block-wise down GEMM), so the comparison is apples-to-apples in +fp8 and measures kernel bugs rather than fp8-vs-fp32 drift. """ import pytest import torch +import torch.nn.functional as F -from flashinfer.fused_moe import has_monomoe, mono_moe +from flashinfer.fused_moe import alloc_scratchpad, has_monomoe, mono_moe from flashinfer.utils import is_sm90a_supported -# Fixed geometry of the only compiled variant. -E = 256 -N = 512 # N_half: gate and up each have N rows -K = 2048 BLOCK = 128 +# ── Block-FP8 quantization / reference helpers (inlined) ───────────────────── +# The block-FP8 Python reference replicates the kernel's exact math (block-wise +# dequant GEMM, SiLU gating, block-wise re-quant of the intermediate, block-wise +# down GEMM), so the accuracy comparison is apples-to-apples in fp8 and measures +# kernel bugs rather than fp8-vs-fp32 drift. Pure PyTorch, single shape family. +_FP8_MAX = 448.0 # e4m3 dynamic range + + def _quant_fp8_block_wise(w, block_row=128, block_col=128): """Block-wise FP8 quantization. w: [E, rows, cols] -> (fp8, scales).""" Ee, rows, cols = w.shape @@ -36,9 +42,9 @@ def _quant_fp8_block_wise(w, block_row=128, block_col=128): c0, c1 = ci * block_col, min((ci + 1) * block_col, cols) block = wf[:, r0:r1, c0:c1] amax = block.abs().amax(dim=(1, 2), keepdim=True).clamp(min=1e-12) - s = amax / 448.0 + s = amax / _FP8_MAX scales[:, ri, ci] = s.reshape(Ee) - w_fp8[:, r0:r1, c0:c1] = (block / s).clamp(-448, 448) + w_fp8[:, r0:r1, c0:c1] = (block / s).clamp(-_FP8_MAX, _FP8_MAX) return w_fp8.to(torch.float8_e4m3fn), scales @@ -51,8 +57,12 @@ def _quant_act_block_wise(x_float, group_size=128): g0, g1 = g * group_size, (g + 1) * group_size block = x_float[g0:g1] amax = block.abs().max().clamp(min=1e-12) - scales[g] = amax / 448.0 - x_fp8[g0:g1] = (block * (448.0 / amax)).clamp(-448, 448).to(torch.float8_e4m3fn) + scales[g] = amax / _FP8_MAX + x_fp8[g0:g1] = ( + (block * (_FP8_MAX / amax)) + .clamp(-_FP8_MAX, _FP8_MAX) + .to(torch.float8_e4m3fn) + ) return x_fp8, scales @@ -88,7 +98,7 @@ def _routing_softmax_topk(logits, top_k): return wts, ids -def _python_reference(x, w13_fp8, s13, w2_fp8, s2, topk_w, topk_ids): +def _python_reference_fp8(x, w13_fp8, s13, w2_fp8, s2, topk_w, topk_ids, N, K): """Block-wise fp8 reference matching the kernel's math. Returns out [M, K].""" M, top_k = x.shape[0], topk_ids.shape[1] out = torch.zeros(M, K, device=x.device, dtype=torch.bfloat16) @@ -106,29 +116,29 @@ def _python_reference(x, w13_fp8, s13, w2_fp8, s2, topk_w, topk_ids): return out -@pytest.mark.parametrize("m", [1, 8]) -@pytest.mark.parametrize("top_k", [1, 8]) -def test_monomoe_accuracy(m, top_k): - dev = torch.device("cuda") - if not is_sm90a_supported(dev): - pytest.skip("monomoe requires SM90a (Hopper)") - if not has_monomoe(): - pytest.skip("monomoe extension unavailable (failed to build/load)") +def _cosine(a, b): + """Flattened cosine similarity of two tensors.""" + return F.cosine_similarity( + a.float().reshape(-1), b.float().reshape(-1), dim=0 + ).item() - torch.manual_seed(42) - # Up weights are stored [E, 2*N, K] = [gate(N rows) || up(N rows)]. - w13_f = torch.randn(E, 2 * N, K, device=dev) * 0.1 - w2_f = torch.randn(E, K, N, device=dev) * 0.1 + +def _make_weights(dev, E, N, K, scale=0.1, seed=42): + """Quantized block-FP8 up/down weights (fp8 tensors + scales) for a shape.""" + g = torch.Generator(device=dev).manual_seed(seed) + w13_f = torch.randn(E, 2 * N, K, device=dev, generator=g) * scale + w2_f = torch.randn(E, K, N, device=dev, generator=g) * scale w13_fp8, s13 = _quant_fp8_block_wise(w13_f) w2_fp8, s2 = _quant_fp8_block_wise(w2_f) + return w13_fp8, s13, w2_fp8, s2 - x = torch.randn(m, K, device=dev, dtype=torch.bfloat16) - logits = torch.randn(m, E, device=dev, dtype=torch.bfloat16) - topk_w, topk_ids = _routing_softmax_topk(logits, top_k) - ref = _python_reference(x, w13_fp8, s13, w2_fp8, s2, topk_w, topk_ids) +def _run_and_compare(x, logits, weights, N, K, top_k, scratchpad=None): + """Run mono_moe against the block-FP8 reference; return (out, cos).""" + w13_fp8, s13, w2_fp8, s2 = weights + topk_w, topk_ids = _routing_softmax_topk(logits, top_k) + ref = _python_reference_fp8(x, w13_fp8, s13, w2_fp8, s2, topk_w, topk_ids, N, K) - # mono_moe applies the up-weight TMA interleave internally by default. out = mono_moe( x, logits, @@ -139,14 +149,194 @@ def test_monomoe_accuracy(m, top_k): top_k=top_k, scoring_func="softmax", renormalize=True, + scratchpad=scratchpad, ) - - assert out.shape == (m, K) + assert out.shape == x.shape assert out.dtype == torch.bfloat16 + cos = _cosine(out, ref) + return out, cos - cos = torch.nn.functional.cosine_similarity( - out.float().reshape(-1), ref.float().reshape(-1), dim=0 - ).item() - max_abs = (out.float() - ref.float()).abs().max().item() - print(f"\n[monomoe] m={m} top_k={top_k}: cos_sim={cos:.5f} max_abs={max_abs:.4f}") + +def _require_monomoe(dev): + if not is_sm90a_supported(dev): + pytest.skip("monomoe requires SM90a (Hopper)") + if not has_monomoe(): + pytest.skip("monomoe unavailable for the E=256/N=512/K=2048 shape") + + +@pytest.mark.parametrize("m", [1, 2, 3, 4, 5, 6, 7, 8]) +@pytest.mark.parametrize("top_k", [1, 8]) +def test_monomoe_accuracy(m, top_k): + E, N, K = 256, 512, 2048 + dev = torch.device("cuda") + _require_monomoe(dev) + + torch.manual_seed(42) + weights = _make_weights(dev, E, N, K) + x = torch.randn(m, K, device=dev, dtype=torch.bfloat16) + logits = torch.randn(m, E, device=dev, dtype=torch.bfloat16) + + _, cos = _run_and_compare(x, logits, weights, N, K, top_k) + print(f"\n[monomoe] E={E} N={N} K={K} m={m} top_k={top_k}: cos_sim={cos:.5f}") + assert cos > 0.98, f"cosine similarity too low: {cos:.5f}" + + +@pytest.mark.parametrize("m", [1, 2, 4, 8]) +def test_monomoe_scratchpad_reuse_no_contamination(m): + """A scratchpad reused across calls with DIFFERENT inputs must not leak + state between launches. + + The kernel's cross-block handoffs (the act-scale sentinel and the + Phase-4->5 arrival counters) live in the scratchpad and are meant to be + self-maintaining via a per-launch parity double-buffer. If that reset + discipline were wrong, a second launch on the same buffer could observe + a stale scale/flag from the first and corrupt its output. We run several + independent problems through ONE scratchpad and require each to match its + own reference — a fresh-scratchpad control run is compared against too. + """ + E, N, K = 256, 512, 2048 + dev = torch.device("cuda") + _require_monomoe(dev) + + weights = _make_weights(dev, E, N, K, seed=7) + scratch = alloc_scratchpad(dev) + + # Distinct (x, logits) per iteration so a leaked buffer would show up as a + # mismatch against THIS iteration's reference. + prev_out = None + for i in range(4): + torch.manual_seed(100 + i) + x = torch.randn(m, K, device=dev, dtype=torch.bfloat16) + logits = torch.randn(m, E, device=dev, dtype=torch.bfloat16) + + out_reuse, cos_reuse = _run_and_compare( + x, logits, weights, N, K, top_k=8, scratchpad=scratch + ) + # Control: a fresh scratchpad for the same inputs must match exactly. + out_fresh, _ = _run_and_compare( + x, logits, weights, N, K, top_k=8, scratchpad=alloc_scratchpad(dev) + ) + + print(f"\n[monomoe reuse] m={m} iter={i}: cos_sim={cos_reuse:.5f}") + assert cos_reuse > 0.98, f"reuse iter {i}: cos too low {cos_reuse:.5f}" + # Reused-buffer output must match the fresh-buffer output for the same + # inputs. Not bit-exact: the Phase-4 cross-block atomicAdd reduces in + # nondeterministic order, so runs differ by up to a rounding ULP — + # contamination (a leaked scale/flag) would instead flip whole + # rows/experts, far above this tolerance. + cos_rf = _cosine(out_reuse, out_fresh) + assert cos_rf > 0.9999, ( + f"reuse iter {i}: reuse vs fresh diverged ({cos_rf:.6f})" + ) + if prev_out is not None: + # Different inputs must produce a different output (guards against + # the kernel silently returning a stale buffer). + assert not torch.equal(out_reuse, prev_out) + prev_out = out_reuse.clone() + + +@pytest.mark.parametrize("m", [1, 2, 4, 8]) +def test_monomoe_cuda_graph_replay(m): + """CUDA graph capture + multi-replay must produce correct results. + + The kernel uses TMA descriptors that bake in buffer addresses at capture + time, and the scratchpad's parity double-buffer must self-reset across + replays without an explicit cudaMemset. We capture once, then replay with + different input DATA (written into the same pre-allocated buffers) and + verify each replay matches the Python reference. + """ + E, N, K = 256, 512, 2048 + dev = torch.device("cuda") + _require_monomoe(dev) + + torch.manual_seed(77) + weights = _make_weights(dev, E, N, K) + w13_fp8, s13, w2_fp8, s2 = weights + + # Pre-allocate fixed buffers for graph capture. + x = torch.randn(m, K, device=dev, dtype=torch.bfloat16) + logits = torch.randn(m, E, device=dev, dtype=torch.bfloat16) + out = torch.empty(m, K, device=dev, dtype=torch.bfloat16) + scratch = alloc_scratchpad(dev) + + # Warmup (required before graph capture). + for _ in range(3): + mono_moe( + x, + logits, + w13_fp8, + s13, + w2_fp8, + s2, + top_k=8, + scoring_func="softmax", + renormalize=True, + out=out, + scratchpad=scratch, + ) + torch.cuda.synchronize() + + # Capture. + g = torch.cuda.CUDAGraph() + with torch.cuda.graph(g): + mono_moe( + x, + logits, + w13_fp8, + s13, + w2_fp8, + s2, + top_k=8, + scoring_func="softmax", + renormalize=True, + out=out, + scratchpad=scratch, + ) + torch.cuda.synchronize() + + # Replay with different inputs each time and verify. + for i in range(4): + torch.manual_seed(200 + i) + x.copy_(torch.randn(m, K, device=dev, dtype=torch.bfloat16)) + logits.copy_(torch.randn(m, E, device=dev, dtype=torch.bfloat16)) + + g.replay() + torch.cuda.synchronize() + + # Compute reference for this iteration's inputs. + topk_w, topk_ids = _routing_softmax_topk(logits, top_k=8) + ref = _python_reference_fp8(x, w13_fp8, s13, w2_fp8, s2, topk_w, topk_ids, N, K) + cos = _cosine(out, ref) + print(f"\n[monomoe graph] m={m} replay={i}: cos_sim={cos:.5f}") + assert cos > 0.98, f"graph replay {i}: cosine similarity too low: {cos:.5f}" + assert torch.isfinite(out.float()).all(), f"graph replay {i}: NaN/Inf in output" + + +@pytest.mark.parametrize("scale", [1e-2, 3e-3]) +def test_monomoe_small_scales(scale): + """Correctness must hold when weight/activation magnitudes are tiny. + + Block-FP8 rescales each 128x128 tile to the e4m3 range, so uniformly + scaling the inputs is numerically inert *until* the OUTPUT magnitude + (~scale^2 here) sinks below the fp8 pipeline's dynamic-range floor — at + which point the fp8 reference itself loses correlation with fp32, so the + kernel can no longer be distinguished from it. These scales keep the + output above that floor (~1e-6) while still exercising the tiny-scale + path: the act-scale sentinel publish clamps to >= FLT_MIN so a + legitimately small scale can never flush to the 0.0f "not published" + sentinel and mis-handoff a consumer. + """ + E, N, K = 256, 512, 2048 + dev = torch.device("cuda") + _require_monomoe(dev) + + torch.manual_seed(2024) + weights = _make_weights(dev, E, N, K, scale=scale, seed=11) + x = torch.randn(8, K, device=dev, dtype=torch.bfloat16) * scale + logits = torch.randn(8, E, device=dev, dtype=torch.bfloat16) + + out, cos = _run_and_compare(x, logits, weights, N, K, top_k=8) + # No NaN/Inf even at the fp8 subnormal boundary. + assert torch.isfinite(out.float()).all(), "small-scale output has NaN/Inf" + print(f"\n[monomoe small-scale] scale={scale:g}: cos_sim={cos:.5f}") assert cos > 0.98, f"cosine similarity too low: {cos:.5f}"